Implement Message::isBlank and Message::isDisabled.
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2 /**
3 * Global functions used everywhere
4 * @file
5 */
6
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 die( "This file is part of MediaWiki, it is not a valid entry point" );
9 }
10
11 require_once dirname( __FILE__ ) . '/normal/UtfNormalUtil.php';
12
13 // Hide compatibility functions from Doxygen
14 /// @cond
15
16 /**
17 * Compatibility functions
18 *
19 * We support PHP 5.1.x and up.
20 * Re-implementations of newer functions or functions in non-standard
21 * PHP extensions may be included here.
22 */
23
24 if( !function_exists( 'iconv' ) ) {
25 function iconv( $from, $to, $string ) {
26 return Fallback::iconv( $from, $to, $string );
27 }
28 }
29
30 if ( !function_exists( 'mb_substr' ) ) {
31 function mb_substr( $str, $start, $count='end' ) {
32 return Fallback::mb_substr( $str, $start, $count );
33 }
34
35 function mb_substr_split_unicode( $str, $splitPos ) {
36 return Fallback::mb_substr_split_unicode( $str, $splitPos );
37 }
38 }
39
40 if ( !function_exists( 'mb_strlen' ) ) {
41 function mb_strlen( $str, $enc = '' ) {
42 return Fallback::mb_strlen( $str, $enc );
43 }
44 }
45
46 if( !function_exists( 'mb_strpos' ) ) {
47
48 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
49 return Fallback::mb_strpos( $haystack, $needle, $offset, $encoding );
50 }
51
52 }
53
54 if( !function_exists( 'mb_strrpos' ) ) {
55 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
56 return Fallback::mb_strrpos( $haystack, $needle, $offset, $encoding );
57 }
58 }
59
60
61 // Support for Wietse Venema's taint feature
62 if ( !function_exists( 'istainted' ) ) {
63 function istainted( $var ) {
64 return 0;
65 }
66 function taint( $var, $level = 0 ) {}
67 function untaint( $var, $level = 0 ) {}
68 define( 'TC_HTML', 1 );
69 define( 'TC_SHELL', 1 );
70 define( 'TC_MYSQL', 1 );
71 define( 'TC_PCRE', 1 );
72 define( 'TC_SELF', 1 );
73 }
74 /// @endcond
75
76
77
78 /**
79 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
80 */
81 function wfArrayDiff2( $a, $b ) {
82 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
83 }
84 function wfArrayDiff2_cmp( $a, $b ) {
85 if ( !is_array( $a ) ) {
86 return strcmp( $a, $b );
87 } elseif ( count( $a ) !== count( $b ) ) {
88 return count( $a ) < count( $b ) ? -1 : 1;
89 } else {
90 reset( $a );
91 reset( $b );
92 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
93 $cmp = strcmp( $valueA, $valueB );
94 if ( $cmp !== 0 ) {
95 return $cmp;
96 }
97 }
98 return 0;
99 }
100 }
101
102 /**
103 * Get a random decimal value between 0 and 1, in a way
104 * not likely to give duplicate values for any realistic
105 * number of articles.
106 *
107 * @return string
108 */
109 function wfRandom() {
110 # The maximum random value is "only" 2^31-1, so get two random
111 # values to reduce the chance of dupes
112 $max = mt_getrandmax() + 1;
113 $rand = number_format( ( mt_rand() * $max + mt_rand() )
114 / $max / $max, 12, '.', '' );
115 return $rand;
116 }
117
118 /**
119 * We want some things to be included as literal characters in our title URLs
120 * for prettiness, which urlencode encodes by default. According to RFC 1738,
121 * all of the following should be safe:
122 *
123 * ;:@&=$-_.+!*'(),
124 *
125 * But + is not safe because it's used to indicate a space; &= are only safe in
126 * paths and not in queries (and we don't distinguish here); ' seems kind of
127 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
128 * is reserved, we don't care. So the list we unescape is:
129 *
130 * ;:@$!*(),/
131 *
132 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
133 * so no fancy : for IIS7.
134 *
135 * %2F in the page titles seems to fatally break for some reason.
136 *
137 * @param $s String:
138 * @return string
139 */
140 function wfUrlencode( $s ) {
141 static $needle;
142 if ( is_null( $needle ) ) {
143 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
144 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
145 $needle[] = '%3A';
146 }
147 }
148
149 $s = urlencode( $s );
150 $s = str_ireplace(
151 $needle,
152 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
153 $s
154 );
155
156 return $s;
157 }
158
159 /**
160 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
161 * In normal operation this is a NOP.
162 *
163 * Controlling globals:
164 * $wgDebugLogFile - points to the log file
165 * $wgProfileOnly - if set, normal debug messages will not be recorded.
166 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
167 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
168 *
169 * @param $text String
170 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
171 */
172 function wfDebug( $text, $logonly = false ) {
173 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
174 global $wgDebugLogPrefix, $wgShowDebug;
175
176 static $cache = array(); // Cache of unoutputted messages
177 $text = wfDebugTimer() . $text;
178
179 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
180 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
181 return;
182 }
183
184 if ( ( $wgDebugComments || $wgShowDebug ) && !$logonly ) {
185 $cache[] = $text;
186
187 if ( isset( $wgOut ) && StubObject::isRealObject( $wgOut ) ) {
188 // add the message and any cached messages to the output
189 array_map( array( $wgOut, 'debug' ), $cache );
190 $cache = array();
191 }
192 }
193 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
194 # Strip unprintables; they can switch terminal modes when binary data
195 # gets dumped, which is pretty annoying.
196 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
197 $text = $wgDebugLogPrefix . $text;
198 wfErrorLog( $text, $wgDebugLogFile );
199 }
200 }
201
202 function wfDebugTimer() {
203 global $wgDebugTimestamps;
204 if ( !$wgDebugTimestamps ) {
205 return '';
206 }
207 static $start = null;
208
209 if ( $start === null ) {
210 $start = microtime( true );
211 $prefix = "\n$start";
212 } else {
213 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
214 }
215
216 return $prefix . ' ';
217 }
218
219 /**
220 * Send a line giving PHP memory usage.
221 * @param $exact Bool: print exact values instead of kilobytes (default: false)
222 */
223 function wfDebugMem( $exact = false ) {
224 $mem = memory_get_usage();
225 if( !$exact ) {
226 $mem = floor( $mem / 1024 ) . ' kilobytes';
227 } else {
228 $mem .= ' bytes';
229 }
230 wfDebug( "Memory usage: $mem\n" );
231 }
232
233 /**
234 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
235 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
236 *
237 * @param $logGroup String
238 * @param $text String
239 * @param $public Bool: whether to log the event in the public log if no private
240 * log file is specified, (default true)
241 */
242 function wfDebugLog( $logGroup, $text, $public = true ) {
243 global $wgDebugLogGroups, $wgShowHostnames;
244 $text = trim( $text ) . "\n";
245 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
246 $time = wfTimestamp( TS_DB );
247 $wiki = wfWikiID();
248 if ( $wgShowHostnames ) {
249 $host = wfHostname();
250 } else {
251 $host = '';
252 }
253 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
254 } elseif ( $public === true ) {
255 wfDebug( $text, true );
256 }
257 }
258
259 /**
260 * Log for database errors
261 * @param $text String: database error message.
262 */
263 function wfLogDBError( $text ) {
264 global $wgDBerrorLog, $wgDBname;
265 if ( $wgDBerrorLog ) {
266 $host = trim(`hostname`);
267 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
268 wfErrorLog( $text, $wgDBerrorLog );
269 }
270 }
271
272 /**
273 * Log to a file without getting "file size exceeded" signals.
274 *
275 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
276 * send lines to the specified port, prefixed by the specified prefix and a space.
277 */
278 function wfErrorLog( $text, $file ) {
279 if ( substr( $file, 0, 4 ) == 'udp:' ) {
280 # Needs the sockets extension
281 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
282 // IPv6 bracketed host
283 $host = $m[2];
284 $port = intval( $m[3] );
285 $prefix = isset( $m[4] ) ? $m[4] : false;
286 $domain = AF_INET6;
287 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
288 $host = $m[2];
289 if ( !IP::isIPv4( $host ) ) {
290 $host = gethostbyname( $host );
291 }
292 $port = intval( $m[3] );
293 $prefix = isset( $m[4] ) ? $m[4] : false;
294 $domain = AF_INET;
295 } else {
296 throw new MWException( __METHOD__ . ': Invalid UDP specification' );
297 }
298 // Clean it up for the multiplexer
299 if ( strval( $prefix ) !== '' ) {
300 $text = preg_replace( '/^/m', $prefix . ' ', $text );
301 if ( substr( $text, -1 ) != "\n" ) {
302 $text .= "\n";
303 }
304 }
305
306 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
307 if ( !$sock ) {
308 return;
309 }
310 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
311 socket_close( $sock );
312 } else {
313 wfSuppressWarnings();
314 $exists = file_exists( $file );
315 $size = $exists ? filesize( $file ) : false;
316 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
317 error_log( $text, 3, $file );
318 }
319 wfRestoreWarnings();
320 }
321 }
322
323 /**
324 * @todo document
325 */
326 function wfLogProfilingData() {
327 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
328 global $wgProfiler, $wgProfileLimit, $wgUser;
329 # Profiling must actually be enabled...
330 if( is_null( $wgProfiler ) ) {
331 return;
332 }
333 # Get total page request time
334 $now = wfTime();
335 $elapsed = $now - $wgRequestTime;
336 # Only show pages that longer than $wgProfileLimit time (default is 0)
337 if( $elapsed <= $wgProfileLimit ) {
338 return;
339 }
340 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
341 $forward = '';
342 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
343 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
344 }
345 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
346 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
347 }
348 if( !empty( $_SERVER['HTTP_FROM'] ) ) {
349 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
350 }
351 if( $forward ) {
352 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
353 }
354 // Don't unstub $wgUser at this late stage just for statistics purposes
355 // FIXME: We can detect some anons even if it is not loaded. See User::getId()
356 if( $wgUser->mDataLoaded && $wgUser->isAnon() ) {
357 $forward .= ' anon';
358 }
359 $log = sprintf( "%s\t%04.3f\t%s\n",
360 gmdate( 'YmdHis' ), $elapsed,
361 urldecode( $wgRequest->getRequestURL() . $forward ) );
362 if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' || $wgDebugRawPage ) ) {
363 wfErrorLog( $log . $prof, $wgDebugLogFile );
364 }
365 }
366
367 /**
368 * Check if the wiki read-only lock file is present. This can be used to lock
369 * off editing functions, but doesn't guarantee that the database will not be
370 * modified.
371 * @return bool
372 */
373 function wfReadOnly() {
374 global $wgReadOnlyFile, $wgReadOnly;
375
376 if ( !is_null( $wgReadOnly ) ) {
377 return (bool)$wgReadOnly;
378 }
379 if ( $wgReadOnlyFile == '' ) {
380 return false;
381 }
382 // Set $wgReadOnly for faster access next time
383 if ( is_file( $wgReadOnlyFile ) ) {
384 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
385 } else {
386 $wgReadOnly = false;
387 }
388 return (bool)$wgReadOnly;
389 }
390
391 function wfReadOnlyReason() {
392 global $wgReadOnly;
393 wfReadOnly();
394 return $wgReadOnly;
395 }
396
397 /**
398 * Return a Language object from $langcode
399 * @param $langcode Mixed: either:
400 * - a Language object
401 * - code of the language to get the message for, if it is
402 * a valid code create a language for that language, if
403 * it is a string but not a valid code then make a basic
404 * language object
405 * - a boolean: if it's false then use the current users
406 * language (as a fallback for the old parameter
407 * functionality), or if it is true then use the wikis
408 * @return Language object
409 */
410 function wfGetLangObj( $langcode = false ) {
411 # Identify which language to get or create a language object for.
412 # Using is_object here due to Stub objects.
413 if( is_object( $langcode ) ) {
414 # Great, we already have the object (hopefully)!
415 return $langcode;
416 }
417
418 global $wgContLang, $wgLanguageCode;
419 if( $langcode === true || $langcode === $wgLanguageCode ) {
420 # $langcode is the language code of the wikis content language object.
421 # or it is a boolean and value is true
422 return $wgContLang;
423 }
424
425 global $wgLang;
426 if( $langcode === false || $langcode === $wgLang->getCode() ) {
427 # $langcode is the language code of user language object.
428 # or it was a boolean and value is false
429 return $wgLang;
430 }
431
432 $validCodes = array_keys( Language::getLanguageNames() );
433 if( in_array( $langcode, $validCodes ) ) {
434 # $langcode corresponds to a valid language.
435 return Language::factory( $langcode );
436 }
437
438 # $langcode is a string, but not a valid language code; use content language.
439 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
440 return $wgContLang;
441 }
442
443 /**
444 * Use this instead of $wgContLang, when working with user interface.
445 * User interface is currently hard coded according to wiki content language
446 * in many ways, especially regarding to text direction. There is lots stuff
447 * to fix, hence this function to keep the old behaviour unless the global
448 * $wgBetterDirectionality is enabled (or removed when everything works).
449 */
450 function wfUILang() {
451 global $wgBetterDirectionality;
452 return wfGetLangObj( !$wgBetterDirectionality );
453 }
454
455 /**
456 * This is the new function for getting translated interface messages.
457 * See the Message class for documentation how to use them.
458 * The intention is that this function replaces all old wfMsg* functions.
459 * @param $key \string Message key.
460 * Varargs: normal message parameters.
461 * @return \type{Message}
462 * @since 1.17
463 */
464 function wfMessage( $key /*...*/) {
465 $params = func_get_args();
466 array_shift( $params );
467 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
468 $params = $params[0];
469 }
470 return new Message( $key, $params );
471 }
472
473 /**
474 * This function accepts multiple message keys and returns a message instance
475 * for the first message which is non-empty. If all messages are empty then an
476 * instance of the first message key is returned.
477 * Varargs: message keys
478 * @return \type{Message}
479 * @since 1.18
480 */
481 function wfMessageFallback( /*...*/ ) {
482 $args = func_get_args();
483 return call_user_func_array( array( 'Message', 'newFallbackSequence' ), $args );
484 }
485
486 /**
487 * Get a message from anywhere, for the current user language.
488 *
489 * Use wfMsgForContent() instead if the message should NOT
490 * change depending on the user preferences.
491 *
492 * @param $key String: lookup key for the message, usually
493 * defined in languages/Language.php
494 *
495 * This function also takes extra optional parameters (not
496 * shown in the function definition), which can be used to
497 * insert variable text into the predefined message.
498 */
499 function wfMsg( $key ) {
500 $args = func_get_args();
501 array_shift( $args );
502 return wfMsgReal( $key, $args, true );
503 }
504
505 /**
506 * Same as above except doesn't transform the message
507 */
508 function wfMsgNoTrans( $key ) {
509 $args = func_get_args();
510 array_shift( $args );
511 return wfMsgReal( $key, $args, true, false, false );
512 }
513
514 /**
515 * Get a message from anywhere, for the current global language
516 * set with $wgLanguageCode.
517 *
518 * Use this if the message should NOT change dependent on the
519 * language set in the user's preferences. This is the case for
520 * most text written into logs, as well as link targets (such as
521 * the name of the copyright policy page). Link titles, on the
522 * other hand, should be shown in the UI language.
523 *
524 * Note that MediaWiki allows users to change the user interface
525 * language in their preferences, but a single installation
526 * typically only contains content in one language.
527 *
528 * Be wary of this distinction: If you use wfMsg() where you should
529 * use wfMsgForContent(), a user of the software may have to
530 * customize potentially hundreds of messages in
531 * order to, e.g., fix a link in every possible language.
532 *
533 * @param $key String: lookup key for the message, usually
534 * defined in languages/Language.php
535 */
536 function wfMsgForContent( $key ) {
537 global $wgForceUIMsgAsContentMsg;
538 $args = func_get_args();
539 array_shift( $args );
540 $forcontent = true;
541 if( is_array( $wgForceUIMsgAsContentMsg ) &&
542 in_array( $key, $wgForceUIMsgAsContentMsg ) )
543 {
544 $forcontent = false;
545 }
546 return wfMsgReal( $key, $args, true, $forcontent );
547 }
548
549 /**
550 * Same as above except doesn't transform the message
551 */
552 function wfMsgForContentNoTrans( $key ) {
553 global $wgForceUIMsgAsContentMsg;
554 $args = func_get_args();
555 array_shift( $args );
556 $forcontent = true;
557 if( is_array( $wgForceUIMsgAsContentMsg ) &&
558 in_array( $key, $wgForceUIMsgAsContentMsg ) )
559 {
560 $forcontent = false;
561 }
562 return wfMsgReal( $key, $args, true, $forcontent, false );
563 }
564
565 /**
566 * Get a message from the language file, for the UI elements
567 */
568 function wfMsgNoDB( $key ) {
569 $args = func_get_args();
570 array_shift( $args );
571 return wfMsgReal( $key, $args, false );
572 }
573
574 /**
575 * Get a message from the language file, for the content
576 */
577 function wfMsgNoDBForContent( $key ) {
578 global $wgForceUIMsgAsContentMsg;
579 $args = func_get_args();
580 array_shift( $args );
581 $forcontent = true;
582 if( is_array( $wgForceUIMsgAsContentMsg ) &&
583 in_array( $key, $wgForceUIMsgAsContentMsg ) )
584 {
585 $forcontent = false;
586 }
587 return wfMsgReal( $key, $args, false, $forcontent );
588 }
589
590
591 /**
592 * Really get a message
593 * @param $key String: key to get.
594 * @param $args
595 * @param $useDB Boolean
596 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
597 * @param $transform Boolean: Whether or not to transform the message.
598 * @return String: the requested message.
599 */
600 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
601 wfProfileIn( __METHOD__ );
602 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
603 $message = wfMsgReplaceArgs( $message, $args );
604 wfProfileOut( __METHOD__ );
605 return $message;
606 }
607
608 /**
609 * This function provides the message source for messages to be edited which are *not* stored in the database.
610 * @param $key String:
611 */
612 function wfMsgWeirdKey( $key ) {
613 $source = wfMsgGetKey( $key, false, true, false );
614 if ( wfEmptyMsg( $key, $source ) ) {
615 return '';
616 } else {
617 return $source;
618 }
619 }
620
621 /**
622 * Fetch a message string value, but don't replace any keys yet.
623 * @param $key String
624 * @param $useDB Bool
625 * @param $langCode String: Code of the language to get the message for, or
626 * behaves as a content language switch if it is a boolean.
627 * @param $transform Boolean: whether to parse magic words, etc.
628 * @return string
629 */
630 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
631 global $wgMessageCache;
632
633 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
634
635 if ( !is_object( $wgMessageCache ) ) {
636 throw new MWException( 'Trying to get message before message cache is initialised' );
637 }
638
639 $message = $wgMessageCache->get( $key, $useDB, $langCode );
640 if( $message === false ) {
641 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
642 } elseif ( $transform ) {
643 $message = $wgMessageCache->transform( $message );
644 }
645 return $message;
646 }
647
648 /**
649 * Replace message parameter keys on the given formatted output.
650 *
651 * @param $message String
652 * @param $args Array
653 * @return string
654 * @private
655 */
656 function wfMsgReplaceArgs( $message, $args ) {
657 # Fix windows line-endings
658 # Some messages are split with explode("\n", $msg)
659 $message = str_replace( "\r", '', $message );
660
661 // Replace arguments
662 if ( count( $args ) ) {
663 if ( is_array( $args[0] ) ) {
664 $args = array_values( $args[0] );
665 }
666 $replacementKeys = array();
667 foreach( $args as $n => $param ) {
668 $replacementKeys['$' . ( $n + 1 )] = $param;
669 }
670 $message = strtr( $message, $replacementKeys );
671 }
672
673 return $message;
674 }
675
676 /**
677 * Return an HTML-escaped version of a message.
678 * Parameter replacements, if any, are done *after* the HTML-escaping,
679 * so parameters may contain HTML (eg links or form controls). Be sure
680 * to pre-escape them if you really do want plaintext, or just wrap
681 * the whole thing in htmlspecialchars().
682 *
683 * @param $key String
684 * @param string ... parameters
685 * @return string
686 */
687 function wfMsgHtml( $key ) {
688 $args = func_get_args();
689 array_shift( $args );
690 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
691 }
692
693 /**
694 * Return an HTML version of message
695 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
696 * so parameters may contain HTML (eg links or form controls). Be sure
697 * to pre-escape them if you really do want plaintext, or just wrap
698 * the whole thing in htmlspecialchars().
699 *
700 * @param $key String
701 * @param string ... parameters
702 * @return string
703 */
704 function wfMsgWikiHtml( $key ) {
705 global $wgOut;
706 $args = func_get_args();
707 array_shift( $args );
708 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
709 }
710
711 /**
712 * Returns message in the requested format
713 * @param $key String: key of the message
714 * @param $options Array: processing rules. Can take the following options:
715 * <i>parse</i>: parses wikitext to HTML
716 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
717 * p's added by parser or tidy
718 * <i>escape</i>: filters message through htmlspecialchars
719 * <i>escapenoentities</i>: same, but allows entity references like &#160; through
720 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
721 * <i>parsemag</i>: transform the message using magic phrases
722 * <i>content</i>: fetch message for content language instead of interface
723 * Also can accept a single associative argument, of the form 'language' => 'xx':
724 * <i>language</i>: Language object or language code to fetch message for
725 * (overriden by <i>content</i>), its behaviour with parse, parseinline
726 * and parsemag is undefined.
727 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
728 */
729 function wfMsgExt( $key, $options ) {
730 global $wgOut;
731
732 $args = func_get_args();
733 array_shift( $args );
734 array_shift( $args );
735 $options = (array)$options;
736
737 foreach( $options as $arrayKey => $option ) {
738 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
739 # An unknown index, neither numeric nor "language"
740 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
741 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
742 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
743 'replaceafter', 'parsemag', 'content' ) ) ) {
744 # A numeric index with unknown value
745 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
746 }
747 }
748
749 if( in_array( 'content', $options, true ) ) {
750 $forContent = true;
751 $langCode = true;
752 $langCodeObj = null;
753 } elseif( array_key_exists( 'language', $options ) ) {
754 $forContent = false;
755 $langCode = wfGetLangObj( $options['language'] );
756 $langCodeObj = $langCode;
757 } else {
758 $forContent = false;
759 $langCode = false;
760 $langCodeObj = null;
761 }
762
763 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
764
765 if( !in_array( 'replaceafter', $options, true ) ) {
766 $string = wfMsgReplaceArgs( $string, $args );
767 }
768
769 if( in_array( 'parse', $options, true ) ) {
770 $string = $wgOut->parse( $string, true, !$forContent, $langCodeObj );
771 } elseif ( in_array( 'parseinline', $options, true ) ) {
772 $string = $wgOut->parse( $string, true, !$forContent, $langCodeObj );
773 $m = array();
774 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
775 $string = $m[1];
776 }
777 } elseif ( in_array( 'parsemag', $options, true ) ) {
778 global $wgMessageCache;
779 if ( isset( $wgMessageCache ) ) {
780 $string = $wgMessageCache->transform( $string,
781 !$forContent, $langCodeObj );
782 }
783 }
784
785 if ( in_array( 'escape', $options, true ) ) {
786 $string = htmlspecialchars ( $string );
787 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
788 $string = Sanitizer::escapeHtmlAllowEntities( $string );
789 }
790
791 if( in_array( 'replaceafter', $options, true ) ) {
792 $string = wfMsgReplaceArgs( $string, $args );
793 }
794
795 return $string;
796 }
797
798
799 /**
800 * Just like exit() but makes a note of it.
801 * Commits open transactions except if the error parameter is set
802 *
803 * @deprecated Please return control to the caller or throw an exception. Will
804 * be removed in 1.19.
805 */
806 function wfAbruptExit( $error = false ) {
807 static $called = false;
808 if ( $called ) {
809 exit( -1 );
810 }
811 $called = true;
812
813 wfDeprecated( __FUNCTION__ );
814 $bt = wfDebugBacktrace();
815 if( $bt ) {
816 for( $i = 0; $i < count( $bt ); $i++ ) {
817 $file = isset( $bt[$i]['file'] ) ? $bt[$i]['file'] : 'unknown';
818 $line = isset( $bt[$i]['line'] ) ? $bt[$i]['line'] : 'unknown';
819 wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
820 }
821 } else {
822 wfDebug( "WARNING: Abrupt exit\n" );
823 }
824
825 wfLogProfilingData();
826
827 if ( !$error ) {
828 wfGetLB()->closeAll();
829 }
830 exit( -1 );
831 }
832
833 /**
834 * @deprecated Please return control the caller or throw an exception. Will
835 * be removed in 1.19.
836 */
837 function wfErrorExit() {
838 wfDeprecated( __FUNCTION__ );
839 wfAbruptExit( true );
840 }
841
842 /**
843 * Print a simple message and die, returning nonzero to the shell if any.
844 * Plain die() fails to return nonzero to the shell if you pass a string.
845 * @param $msg String
846 */
847 function wfDie( $msg = '' ) {
848 echo $msg;
849 die( 1 );
850 }
851
852 /**
853 * Throw a debugging exception. This function previously once exited the process,
854 * but now throws an exception instead, with similar results.
855 *
856 * @param $msg String: message shown when dieing.
857 */
858 function wfDebugDieBacktrace( $msg = '' ) {
859 throw new MWException( $msg );
860 }
861
862 /**
863 * Fetch server name for use in error reporting etc.
864 * Use real server name if available, so we know which machine
865 * in a server farm generated the current page.
866 * @return string
867 */
868 function wfHostname() {
869 static $host;
870 if ( is_null( $host ) ) {
871 if ( function_exists( 'posix_uname' ) ) {
872 // This function not present on Windows
873 $uname = @posix_uname();
874 } else {
875 $uname = false;
876 }
877 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
878 $host = $uname['nodename'];
879 } elseif ( getenv( 'COMPUTERNAME' ) ) {
880 # Windows computer name
881 $host = getenv( 'COMPUTERNAME' );
882 } else {
883 # This may be a virtual server.
884 $host = $_SERVER['SERVER_NAME'];
885 }
886 }
887 return $host;
888 }
889
890 /**
891 * Returns a HTML comment with the elapsed time since request.
892 * This method has no side effects.
893 * @return string
894 */
895 function wfReportTime() {
896 global $wgRequestTime, $wgShowHostnames;
897
898 $now = wfTime();
899 $elapsed = $now - $wgRequestTime;
900
901 return $wgShowHostnames
902 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
903 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
904 }
905
906 /**
907 * Safety wrapper for debug_backtrace().
908 *
909 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
910 * murky circumstances, which may be triggered in part by stub objects
911 * or other fancy talkin'.
912 *
913 * Will return an empty array if Zend Optimizer is detected or if
914 * debug_backtrace is disabled, otherwise the output from
915 * debug_backtrace() (trimmed).
916 *
917 * @return array of backtrace information
918 */
919 function wfDebugBacktrace() {
920 static $disabled = null;
921
922 if( extension_loaded( 'Zend Optimizer' ) ) {
923 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
924 return array();
925 }
926
927 if ( is_null( $disabled ) ) {
928 $disabled = false;
929 $functions = explode( ',', ini_get( 'disable_functions' ) );
930 $functions = array_map( 'trim', $functions );
931 $functions = array_map( 'strtolower', $functions );
932 if ( in_array( 'debug_backtrace', $functions ) ) {
933 wfDebug( "debug_backtrace is in disabled_functions\n" );
934 $disabled = true;
935 }
936 }
937 if ( $disabled ) {
938 return array();
939 }
940
941 return array_slice( debug_backtrace(), 1 );
942 }
943
944 function wfBacktrace() {
945 global $wgCommandLineMode;
946
947 if ( $wgCommandLineMode ) {
948 $msg = '';
949 } else {
950 $msg = "<ul>\n";
951 }
952 $backtrace = wfDebugBacktrace();
953 foreach( $backtrace as $call ) {
954 if( isset( $call['file'] ) ) {
955 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
956 $file = $f[count( $f ) - 1];
957 } else {
958 $file = '-';
959 }
960 if( isset( $call['line'] ) ) {
961 $line = $call['line'];
962 } else {
963 $line = '-';
964 }
965 if ( $wgCommandLineMode ) {
966 $msg .= "$file line $line calls ";
967 } else {
968 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
969 }
970 if( !empty( $call['class'] ) ) {
971 $msg .= $call['class'] . '::';
972 }
973 $msg .= $call['function'] . '()';
974
975 if ( $wgCommandLineMode ) {
976 $msg .= "\n";
977 } else {
978 $msg .= "</li>\n";
979 }
980 }
981 if ( $wgCommandLineMode ) {
982 $msg .= "\n";
983 } else {
984 $msg .= "</ul>\n";
985 }
986
987 return $msg;
988 }
989
990
991 /* Some generic result counters, pulled out of SearchEngine */
992
993
994 /**
995 * @todo document
996 */
997 function wfShowingResults( $offset, $limit ) {
998 global $wgLang;
999 return wfMsgExt(
1000 'showingresults',
1001 array( 'parseinline' ),
1002 $wgLang->formatNum( $limit ),
1003 $wgLang->formatNum( $offset + 1 )
1004 );
1005 }
1006
1007 /**
1008 * @todo document
1009 */
1010 function wfShowingResultsNum( $offset, $limit, $num ) {
1011 global $wgLang;
1012 return wfMsgExt(
1013 'showingresultsnum',
1014 array( 'parseinline' ),
1015 $wgLang->formatNum( $limit ),
1016 $wgLang->formatNum( $offset + 1 ),
1017 $wgLang->formatNum( $num )
1018 );
1019 }
1020
1021 /**
1022 * Generate (prev x| next x) (20|50|100...) type links for paging
1023 * @param $offset String
1024 * @param $limit Integer
1025 * @param $link String
1026 * @param $query String: optional URL query parameter string
1027 * @param $atend Bool: optional param for specified if this is the last page
1028 */
1029 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1030 global $wgLang;
1031 $fmtLimit = $wgLang->formatNum( $limit );
1032 // FIXME: Why on earth this needs one message for the text and another one for tooltip??
1033 # Get prev/next link display text
1034 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1035 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1036 # Get prev/next link title text
1037 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1038 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1039 # Fetch the title object
1040 if( is_object( $link ) ) {
1041 $title =& $link;
1042 } else {
1043 $title = Title::newFromText( $link );
1044 if( is_null( $title ) ) {
1045 return false;
1046 }
1047 }
1048 # Make 'previous' link
1049 if( 0 != $offset ) {
1050 $po = $offset - $limit;
1051 $po = max( $po, 0 );
1052 $q = "limit={$limit}&offset={$po}";
1053 if( $query != '' ) {
1054 $q .= '&' . $query;
1055 }
1056 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1057 } else {
1058 $plink = $prev;
1059 }
1060 # Make 'next' link
1061 $no = $offset + $limit;
1062 $q = "limit={$limit}&offset={$no}";
1063 if( $query != '' ) {
1064 $q .= '&' . $query;
1065 }
1066 if( $atend ) {
1067 $nlink = $next;
1068 } else {
1069 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1070 }
1071 # Make links to set number of items per page
1072 $nums = $wgLang->pipeList( array(
1073 wfNumLink( $offset, 20, $title, $query ),
1074 wfNumLink( $offset, 50, $title, $query ),
1075 wfNumLink( $offset, 100, $title, $query ),
1076 wfNumLink( $offset, 250, $title, $query ),
1077 wfNumLink( $offset, 500, $title, $query )
1078 ) );
1079 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1080 }
1081
1082 /**
1083 * Generate links for (20|50|100...) items-per-page links
1084 * @param $offset String
1085 * @param $limit Integer
1086 * @param $title Title
1087 * @param $query String: optional URL query parameter string
1088 */
1089 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1090 global $wgLang;
1091 if( $query == '' ) {
1092 $q = '';
1093 } else {
1094 $q = $query.'&';
1095 }
1096 $q .= "limit={$limit}&offset={$offset}";
1097 $fmtLimit = $wgLang->formatNum( $limit );
1098 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1099 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1100 return $s;
1101 }
1102
1103 /**
1104 * @todo document
1105 * @todo FIXME: we may want to blacklist some broken browsers
1106 *
1107 * @return bool Whereas client accept gzip compression
1108 */
1109 function wfClientAcceptsGzip( $force = false ) {
1110 static $result = null;
1111 if ( $result === null || $force ) {
1112 $result = false;
1113 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1114 # FIXME: we may want to blacklist some broken browsers
1115 $m = array();
1116 if( preg_match(
1117 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1118 $_SERVER['HTTP_ACCEPT_ENCODING'],
1119 $m )
1120 )
1121 {
1122 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1123 $result = false;
1124 return $result;
1125 }
1126 wfDebug( " accepts gzip\n" );
1127 $result = true;
1128 }
1129 }
1130 }
1131 return $result;
1132 }
1133
1134 /**
1135 * Obtain the offset and limit values from the request string;
1136 * used in special pages
1137 *
1138 * @param $deflimit Default limit if none supplied
1139 * @param $optionname Name of a user preference to check against
1140 * @return array
1141 *
1142 */
1143 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1144 global $wgRequest;
1145 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1146 }
1147
1148 /**
1149 * Escapes the given text so that it may be output using addWikiText()
1150 * without any linking, formatting, etc. making its way through. This
1151 * is achieved by substituting certain characters with HTML entities.
1152 * As required by the callers, <nowiki> is not used. It currently does
1153 * not filter out characters which have special meaning only at the
1154 * start of a line, such as "*".
1155 *
1156 * @param $text String: text to be escaped
1157 */
1158 function wfEscapeWikiText( $text ) {
1159 $text = str_replace(
1160 array( '[', '|', ']', '\'', 'ISBN ',
1161 'RFC ', '://', "\n=", '{{', '}}' ),
1162 array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;',
1163 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;', '&#125;&#125;' ),
1164 htmlspecialchars( $text )
1165 );
1166 return $text;
1167 }
1168
1169 /**
1170 * @todo document
1171 * @return float
1172 */
1173 function wfTime() {
1174 return microtime( true );
1175 }
1176
1177 /**
1178 * Sets dest to source and returns the original value of dest
1179 * If source is NULL, it just returns the value, it doesn't set the variable
1180 * If force is true, it will set the value even if source is NULL
1181 */
1182 function wfSetVar( &$dest, $source, $force = false ) {
1183 $temp = $dest;
1184 if ( !is_null( $source ) || $force ) {
1185 $dest = $source;
1186 }
1187 return $temp;
1188 }
1189
1190 /**
1191 * As for wfSetVar except setting a bit
1192 */
1193 function wfSetBit( &$dest, $bit, $state = true ) {
1194 $temp = (bool)( $dest & $bit );
1195 if ( !is_null( $state ) ) {
1196 if ( $state ) {
1197 $dest |= $bit;
1198 } else {
1199 $dest &= ~$bit;
1200 }
1201 }
1202 return $temp;
1203 }
1204
1205 /**
1206 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1207 * "days=7&limit=100". Options in the first array override options in the second.
1208 * Options set to "" will not be output.
1209 */
1210 function wfArrayToCGI( $array1, $array2 = null ) {
1211 if ( !is_null( $array2 ) ) {
1212 $array1 = $array1 + $array2;
1213 }
1214
1215 $cgi = '';
1216 foreach ( $array1 as $key => $value ) {
1217 if ( $value !== '' ) {
1218 if ( $cgi != '' ) {
1219 $cgi .= '&';
1220 }
1221 if ( is_array( $value ) ) {
1222 $firstTime = true;
1223 foreach ( $value as $v ) {
1224 $cgi .= ( $firstTime ? '' : '&') .
1225 urlencode( $key . '[]' ) . '=' .
1226 urlencode( $v );
1227 $firstTime = false;
1228 }
1229 } else {
1230 if ( is_object( $value ) ) {
1231 $value = $value->__toString();
1232 }
1233 $cgi .= urlencode( $key ) . '=' .
1234 urlencode( $value );
1235 }
1236 }
1237 }
1238 return $cgi;
1239 }
1240
1241 /**
1242 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1243 * its argument and returns the same string in array form. This allows compa-
1244 * tibility with legacy functions that accept raw query strings instead of nice
1245 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1246 * valid query strings, or it will explode.
1247 *
1248 * @param $query String: query string
1249 * @return array Array version of input
1250 */
1251 function wfCgiToArray( $query ) {
1252 if( isset( $query[0] ) && $query[0] == '?' ) {
1253 $query = substr( $query, 1 );
1254 }
1255 $bits = explode( '&', $query );
1256 $ret = array();
1257 foreach( $bits as $bit ) {
1258 if( $bit === '' ) {
1259 continue;
1260 }
1261 list( $key, $value ) = explode( '=', $bit );
1262 $key = urldecode( $key );
1263 $value = urldecode( $value );
1264 $ret[$key] = $value;
1265 }
1266 return $ret;
1267 }
1268
1269 /**
1270 * Append a query string to an existing URL, which may or may not already
1271 * have query string parameters already. If so, they will be combined.
1272 *
1273 * @param $url String
1274 * @param $query Mixed: string or associative array
1275 * @return string
1276 */
1277 function wfAppendQuery( $url, $query ) {
1278 if ( is_array( $query ) ) {
1279 $query = wfArrayToCGI( $query );
1280 }
1281 if( $query != '' ) {
1282 if( false === strpos( $url, '?' ) ) {
1283 $url .= '?';
1284 } else {
1285 $url .= '&';
1286 }
1287 $url .= $query;
1288 }
1289 return $url;
1290 }
1291
1292 /**
1293 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1294 * and $wgProto are correct.
1295 *
1296 * @todo this won't work with current-path-relative URLs
1297 * like "subdir/foo.html", etc.
1298 *
1299 * @param $url String: either fully-qualified or a local path + query
1300 * @return string Fully-qualified URL
1301 */
1302 function wfExpandUrl( $url ) {
1303 if( substr( $url, 0, 2 ) == '//' ) {
1304 global $wgProto;
1305 return $wgProto . ':' . $url;
1306 } elseif( substr( $url, 0, 1 ) == '/' ) {
1307 global $wgServer;
1308 return $wgServer . $url;
1309 } else {
1310 return $url;
1311 }
1312 }
1313
1314 /**
1315 * Windows-compatible version of escapeshellarg()
1316 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1317 * function puts single quotes in regardless of OS.
1318 *
1319 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1320 * earlier distro releases of PHP)
1321 */
1322 function wfEscapeShellArg( ) {
1323 wfInitShellLocale();
1324
1325 $args = func_get_args();
1326 $first = true;
1327 $retVal = '';
1328 foreach ( $args as $arg ) {
1329 if ( !$first ) {
1330 $retVal .= ' ';
1331 } else {
1332 $first = false;
1333 }
1334
1335 if ( wfIsWindows() ) {
1336 // Escaping for an MSVC-style command line parser and CMD.EXE
1337 // Refs:
1338 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1339 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1340 // * Bug #13518
1341 // * CR r63214
1342 // Double the backslashes before any double quotes. Escape the double quotes.
1343 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1344 $arg = '';
1345 $iteration = 0;
1346 foreach ( $tokens as $token ) {
1347 if ( $iteration % 2 == 1 ) {
1348 // Delimiter, a double quote preceded by zero or more slashes
1349 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1350 } elseif ( $iteration % 4 == 2 ) {
1351 // ^ in $token will be outside quotes, need to be escaped
1352 $arg .= str_replace( '^', '^^', $token );
1353 } else { // $iteration % 4 == 0
1354 // ^ in $token will appear inside double quotes, so leave as is
1355 $arg .= $token;
1356 }
1357 $iteration++;
1358 }
1359 // Double the backslashes before the end of the string, because
1360 // we will soon add a quote
1361 $m = array();
1362 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1363 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1364 }
1365
1366 // Add surrounding quotes
1367 $retVal .= '"' . $arg . '"';
1368 } else {
1369 $retVal .= escapeshellarg( $arg );
1370 }
1371 }
1372 return $retVal;
1373 }
1374
1375 /**
1376 * wfMerge attempts to merge differences between three texts.
1377 * Returns true for a clean merge and false for failure or a conflict.
1378 */
1379 function wfMerge( $old, $mine, $yours, &$result ) {
1380 global $wgDiff3;
1381
1382 # This check may also protect against code injection in
1383 # case of broken installations.
1384 wfSuppressWarnings();
1385 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1386 wfRestoreWarnings();
1387
1388 if( !$haveDiff3 ) {
1389 wfDebug( "diff3 not found\n" );
1390 return false;
1391 }
1392
1393 # Make temporary files
1394 $td = wfTempDir();
1395 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1396 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1397 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1398
1399 fwrite( $oldtextFile, $old );
1400 fclose( $oldtextFile );
1401 fwrite( $mytextFile, $mine );
1402 fclose( $mytextFile );
1403 fwrite( $yourtextFile, $yours );
1404 fclose( $yourtextFile );
1405
1406 # Check for a conflict
1407 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1408 wfEscapeShellArg( $mytextName ) . ' ' .
1409 wfEscapeShellArg( $oldtextName ) . ' ' .
1410 wfEscapeShellArg( $yourtextName );
1411 $handle = popen( $cmd, 'r' );
1412
1413 if( fgets( $handle, 1024 ) ) {
1414 $conflict = true;
1415 } else {
1416 $conflict = false;
1417 }
1418 pclose( $handle );
1419
1420 # Merge differences
1421 $cmd = $wgDiff3 . ' -a -e --merge ' .
1422 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1423 $handle = popen( $cmd, 'r' );
1424 $result = '';
1425 do {
1426 $data = fread( $handle, 8192 );
1427 if ( strlen( $data ) == 0 ) {
1428 break;
1429 }
1430 $result .= $data;
1431 } while ( true );
1432 pclose( $handle );
1433 unlink( $mytextName );
1434 unlink( $oldtextName );
1435 unlink( $yourtextName );
1436
1437 if ( $result === '' && $old !== '' && !$conflict ) {
1438 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1439 $conflict = true;
1440 }
1441 return !$conflict;
1442 }
1443
1444 /**
1445 * Returns unified plain-text diff of two texts.
1446 * Useful for machine processing of diffs.
1447 * @param $before String: the text before the changes.
1448 * @param $after String: the text after the changes.
1449 * @param $params String: command-line options for the diff command.
1450 * @return String: unified diff of $before and $after
1451 */
1452 function wfDiff( $before, $after, $params = '-u' ) {
1453 if ( $before == $after ) {
1454 return '';
1455 }
1456
1457 global $wgDiff;
1458 wfSuppressWarnings();
1459 $haveDiff = $wgDiff && file_exists( $wgDiff );
1460 wfRestoreWarnings();
1461
1462 # This check may also protect against code injection in
1463 # case of broken installations.
1464 if( !$haveDiff ) {
1465 wfDebug( "diff executable not found\n" );
1466 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1467 $format = new UnifiedDiffFormatter();
1468 return $format->format( $diffs );
1469 }
1470
1471 # Make temporary files
1472 $td = wfTempDir();
1473 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1474 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1475
1476 fwrite( $oldtextFile, $before );
1477 fclose( $oldtextFile );
1478 fwrite( $newtextFile, $after );
1479 fclose( $newtextFile );
1480
1481 // Get the diff of the two files
1482 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1483
1484 $h = popen( $cmd, 'r' );
1485
1486 $diff = '';
1487
1488 do {
1489 $data = fread( $h, 8192 );
1490 if ( strlen( $data ) == 0 ) {
1491 break;
1492 }
1493 $diff .= $data;
1494 } while ( true );
1495
1496 // Clean up
1497 pclose( $h );
1498 unlink( $oldtextName );
1499 unlink( $newtextName );
1500
1501 // Kill the --- and +++ lines. They're not useful.
1502 $diff_lines = explode( "\n", $diff );
1503 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1504 unset( $diff_lines[0] );
1505 }
1506 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1507 unset( $diff_lines[1] );
1508 }
1509
1510 $diff = implode( "\n", $diff_lines );
1511
1512 return $diff;
1513 }
1514
1515 /**
1516 * A wrapper around the PHP function var_export().
1517 * Either print it or add it to the regular output ($wgOut).
1518 *
1519 * @param $var A PHP variable to dump.
1520 */
1521 function wfVarDump( $var ) {
1522 global $wgOut;
1523 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1524 if ( headers_sent() || !@is_object( $wgOut ) ) {
1525 print $s;
1526 } else {
1527 $wgOut->addHTML( $s );
1528 }
1529 }
1530
1531 /**
1532 * Provide a simple HTTP error.
1533 */
1534 function wfHttpError( $code, $label, $desc ) {
1535 global $wgOut;
1536 $wgOut->disable();
1537 header( "HTTP/1.0 $code $label" );
1538 header( "Status: $code $label" );
1539 $wgOut->sendCacheControl();
1540
1541 header( 'Content-type: text/html; charset=utf-8' );
1542 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1543 '<html><head><title>' .
1544 htmlspecialchars( $label ) .
1545 '</title></head><body><h1>' .
1546 htmlspecialchars( $label ) .
1547 '</h1><p>' .
1548 nl2br( htmlspecialchars( $desc ) ) .
1549 "</p></body></html>\n";
1550 }
1551
1552 /**
1553 * Clear away any user-level output buffers, discarding contents.
1554 *
1555 * Suitable for 'starting afresh', for instance when streaming
1556 * relatively large amounts of data without buffering, or wanting to
1557 * output image files without ob_gzhandler's compression.
1558 *
1559 * The optional $resetGzipEncoding parameter controls suppression of
1560 * the Content-Encoding header sent by ob_gzhandler; by default it
1561 * is left. See comments for wfClearOutputBuffers() for why it would
1562 * be used.
1563 *
1564 * Note that some PHP configuration options may add output buffer
1565 * layers which cannot be removed; these are left in place.
1566 *
1567 * @param $resetGzipEncoding Bool
1568 */
1569 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1570 if( $resetGzipEncoding ) {
1571 // Suppress Content-Encoding and Content-Length
1572 // headers from 1.10+s wfOutputHandler
1573 global $wgDisableOutputCompression;
1574 $wgDisableOutputCompression = true;
1575 }
1576 while( $status = ob_get_status() ) {
1577 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1578 // Probably from zlib.output_compression or other
1579 // PHP-internal setting which can't be removed.
1580 //
1581 // Give up, and hope the result doesn't break
1582 // output behavior.
1583 break;
1584 }
1585 if( !ob_end_clean() ) {
1586 // Could not remove output buffer handler; abort now
1587 // to avoid getting in some kind of infinite loop.
1588 break;
1589 }
1590 if( $resetGzipEncoding ) {
1591 if( $status['name'] == 'ob_gzhandler' ) {
1592 // Reset the 'Content-Encoding' field set by this handler
1593 // so we can start fresh.
1594 header( 'Content-Encoding:' );
1595 break;
1596 }
1597 }
1598 }
1599 }
1600
1601 /**
1602 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1603 *
1604 * Clear away output buffers, but keep the Content-Encoding header
1605 * produced by ob_gzhandler, if any.
1606 *
1607 * This should be used for HTTP 304 responses, where you need to
1608 * preserve the Content-Encoding header of the real result, but
1609 * also need to suppress the output of ob_gzhandler to keep to spec
1610 * and avoid breaking Firefox in rare cases where the headers and
1611 * body are broken over two packets.
1612 */
1613 function wfClearOutputBuffers() {
1614 wfResetOutputBuffers( false );
1615 }
1616
1617 /**
1618 * Converts an Accept-* header into an array mapping string values to quality
1619 * factors
1620 */
1621 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1622 # No arg means accept anything (per HTTP spec)
1623 if( !$accept ) {
1624 return array( $def => 1.0 );
1625 }
1626
1627 $prefs = array();
1628
1629 $parts = explode( ',', $accept );
1630
1631 foreach( $parts as $part ) {
1632 # FIXME: doesn't deal with params like 'text/html; level=1'
1633 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1634 $match = array();
1635 if( !isset( $qpart ) ) {
1636 $prefs[$value] = 1.0;
1637 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1638 $prefs[$value] = floatval( $match[1] );
1639 }
1640 }
1641
1642 return $prefs;
1643 }
1644
1645 /**
1646 * Checks if a given MIME type matches any of the keys in the given
1647 * array. Basic wildcards are accepted in the array keys.
1648 *
1649 * Returns the matching MIME type (or wildcard) if a match, otherwise
1650 * NULL if no match.
1651 *
1652 * @param $type String
1653 * @param $avail Array
1654 * @return string
1655 * @private
1656 */
1657 function mimeTypeMatch( $type, $avail ) {
1658 if( array_key_exists( $type, $avail ) ) {
1659 return $type;
1660 } else {
1661 $parts = explode( '/', $type );
1662 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1663 return $parts[0] . '/*';
1664 } elseif( array_key_exists( '*/*', $avail ) ) {
1665 return '*/*';
1666 } else {
1667 return null;
1668 }
1669 }
1670 }
1671
1672 /**
1673 * Returns the 'best' match between a client's requested internet media types
1674 * and the server's list of available types. Each list should be an associative
1675 * array of type to preference (preference is a float between 0.0 and 1.0).
1676 * Wildcards in the types are acceptable.
1677 *
1678 * @param $cprefs Array: client's acceptable type list
1679 * @param $sprefs Array: server's offered types
1680 * @return string
1681 *
1682 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1683 * XXX: generalize to negotiate other stuff
1684 */
1685 function wfNegotiateType( $cprefs, $sprefs ) {
1686 $combine = array();
1687
1688 foreach( array_keys($sprefs) as $type ) {
1689 $parts = explode( '/', $type );
1690 if( $parts[1] != '*' ) {
1691 $ckey = mimeTypeMatch( $type, $cprefs );
1692 if( $ckey ) {
1693 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1694 }
1695 }
1696 }
1697
1698 foreach( array_keys( $cprefs ) as $type ) {
1699 $parts = explode( '/', $type );
1700 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1701 $skey = mimeTypeMatch( $type, $sprefs );
1702 if( $skey ) {
1703 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1704 }
1705 }
1706 }
1707
1708 $bestq = 0;
1709 $besttype = null;
1710
1711 foreach( array_keys( $combine ) as $type ) {
1712 if( $combine[$type] > $bestq ) {
1713 $besttype = $type;
1714 $bestq = $combine[$type];
1715 }
1716 }
1717
1718 return $besttype;
1719 }
1720
1721 /**
1722 * Array lookup
1723 * Returns an array where the values in the first array are replaced by the
1724 * values in the second array with the corresponding keys
1725 *
1726 * @return array
1727 */
1728 function wfArrayLookup( $a, $b ) {
1729 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1730 }
1731
1732 /**
1733 * Convenience function; returns MediaWiki timestamp for the present time.
1734 * @return string
1735 */
1736 function wfTimestampNow() {
1737 # return NOW
1738 return wfTimestamp( TS_MW, time() );
1739 }
1740
1741 /**
1742 * Reference-counted warning suppression
1743 */
1744 function wfSuppressWarnings( $end = false ) {
1745 static $suppressCount = 0;
1746 static $originalLevel = false;
1747
1748 if ( $end ) {
1749 if ( $suppressCount ) {
1750 --$suppressCount;
1751 if ( !$suppressCount ) {
1752 error_reporting( $originalLevel );
1753 }
1754 }
1755 } else {
1756 if ( !$suppressCount ) {
1757 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE ) );
1758 }
1759 ++$suppressCount;
1760 }
1761 }
1762
1763 /**
1764 * Restore error level to previous value
1765 */
1766 function wfRestoreWarnings() {
1767 wfSuppressWarnings( true );
1768 }
1769
1770 # Autodetect, convert and provide timestamps of various types
1771
1772 /**
1773 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1774 */
1775 define( 'TS_UNIX', 0 );
1776
1777 /**
1778 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1779 */
1780 define( 'TS_MW', 1 );
1781
1782 /**
1783 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1784 */
1785 define( 'TS_DB', 2 );
1786
1787 /**
1788 * RFC 2822 format, for E-mail and HTTP headers
1789 */
1790 define( 'TS_RFC2822', 3 );
1791
1792 /**
1793 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1794 *
1795 * This is used by Special:Export
1796 */
1797 define( 'TS_ISO_8601', 4 );
1798
1799 /**
1800 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1801 *
1802 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1803 * DateTime tag and page 36 for the DateTimeOriginal and
1804 * DateTimeDigitized tags.
1805 */
1806 define( 'TS_EXIF', 5 );
1807
1808 /**
1809 * Oracle format time.
1810 */
1811 define( 'TS_ORACLE', 6 );
1812
1813 /**
1814 * Postgres format time.
1815 */
1816 define( 'TS_POSTGRES', 7 );
1817
1818 /**
1819 * DB2 format time
1820 */
1821 define( 'TS_DB2', 8 );
1822
1823 /**
1824 * ISO 8601 basic format with no timezone: 19860209T200000Z
1825 *
1826 * This is used by ResourceLoader
1827 */
1828 define( 'TS_ISO_8601_BASIC', 9 );
1829
1830 /**
1831 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1832 * function will autodetect which format is supplied and act
1833 * accordingly.
1834 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1835 * @return Mixed: String / false The same date in the format specified in $outputtype or false
1836 */
1837 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1838 $uts = 0;
1839 $da = array();
1840 $strtime = '';
1841
1842 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
1843 $uts = time();
1844 $strtime = "@$uts";
1845 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1846 # TS_DB
1847 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
1848 # TS_EXIF
1849 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
1850 # TS_MW
1851 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
1852 # TS_UNIX
1853 $uts = $ts;
1854 $strtime = "@$ts"; // Undocumented?
1855 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
1856 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1857 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1858 str_replace( '+00:00', 'UTC', $ts ) );
1859 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1860 # TS_ISO_8601
1861 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
1862 #TS_ISO_8601_BASIC
1863 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
1864 # TS_POSTGRES
1865 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
1866 # TS_POSTGRES
1867 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
1868 # TS_DB2
1869 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
1870 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
1871 '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S', $ts ) ) { # hh:mm:ss
1872 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
1873 # The regex is a superset of rfc2822 for readability
1874 $strtime = strtok( $ts, ';' );
1875 } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
1876 # TS_RFC850
1877 $strtime = $ts;
1878 } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
1879 # asctime
1880 $strtime = $ts;
1881 } else {
1882 # Bogus value...
1883 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
1884
1885 return false;
1886 }
1887
1888
1889
1890 static $formats = array(
1891 TS_UNIX => 'U',
1892 TS_MW => 'YmdHis',
1893 TS_DB => 'Y-m-d H:i:s',
1894 TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
1895 TS_ISO_8601_BASIC => 'Ymd\THis\Z',
1896 TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
1897 TS_RFC2822 => 'D, d M Y H:i:s',
1898 TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
1899 TS_POSTGRES => 'Y-m-d H:i:s',
1900 TS_DB2 => 'Y-m-d H:i:s',
1901 );
1902
1903 if ( !isset( $formats[$outputtype] ) ) {
1904 throw new MWException( 'wfTimestamp() called with illegal output type.' );
1905 }
1906
1907 if ( function_exists( "date_create" ) ) {
1908 if ( count( $da ) ) {
1909 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
1910 (int)$da[1], (int)$da[2], (int)$da[3],
1911 (int)$da[4], (int)$da[5], (int)$da[6]);
1912
1913 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
1914 } elseif ( $strtime ) {
1915 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
1916 } else {
1917 return false;
1918 }
1919
1920 if ( !$d ) {
1921 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1922 return false;
1923 }
1924
1925 $output = $d->format( $formats[$outputtype] );
1926 } else {
1927 if ( count( $da ) ) {
1928 // Warning! gmmktime() acts oddly if the month or day is set to 0
1929 // We may want to handle that explicitly at some point
1930 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
1931 (int)$da[2], (int)$da[3], (int)$da[1] );
1932 } elseif ( $strtime ) {
1933 $uts = strtotime( $strtime );
1934 }
1935
1936 if ( $uts === false ) {
1937 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
1938 return false;
1939 }
1940
1941 if ( TS_UNIX == $outputtype ) {
1942 return $uts;
1943 }
1944 $output = gmdate( $formats[$outputtype], $uts );
1945 }
1946
1947 if ( ( $outputtype == TS_RFC2822 ) || ( $outputtype == TS_POSTGRES ) ) {
1948 $output .= ' GMT';
1949 }
1950
1951 return $output;
1952 }
1953
1954 /**
1955 * Return a formatted timestamp, or null if input is null.
1956 * For dealing with nullable timestamp columns in the database.
1957 * @param $outputtype Integer
1958 * @param $ts String
1959 * @return String
1960 */
1961 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1962 if( is_null( $ts ) ) {
1963 return null;
1964 } else {
1965 return wfTimestamp( $outputtype, $ts );
1966 }
1967 }
1968
1969 /**
1970 * Check if the operating system is Windows
1971 *
1972 * @return Bool: true if it's Windows, False otherwise.
1973 */
1974 function wfIsWindows() {
1975 static $isWindows = null;
1976 if ( $isWindows === null ) {
1977 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
1978 }
1979 return $isWindows;
1980 }
1981
1982 /**
1983 * Swap two variables
1984 */
1985 function swap( &$x, &$y ) {
1986 $z = $x;
1987 $x = $y;
1988 $y = $z;
1989 }
1990
1991 function wfGetCachedNotice( $name ) {
1992 global $wgOut, $wgRenderHashAppend, $parserMemc;
1993 $fname = 'wfGetCachedNotice';
1994 wfProfileIn( $fname );
1995
1996 $needParse = false;
1997
1998 if( $name === 'default' ) {
1999 // special case
2000 global $wgSiteNotice;
2001 $notice = $wgSiteNotice;
2002 if( empty( $notice ) ) {
2003 wfProfileOut( $fname );
2004 return false;
2005 }
2006 } else {
2007 $msg = wfMessage( $name )->inContentLanguage();
2008 if( $msg->isDisabled() ) {
2009 wfProfileOut( $fname );
2010 return( false );
2011 }
2012 $notice = $msg->plain();
2013 }
2014
2015 // Use the extra hash appender to let eg SSL variants separately cache.
2016 $key = wfMemcKey( $name . $wgRenderHashAppend );
2017 $cachedNotice = $parserMemc->get( $key );
2018 if( is_array( $cachedNotice ) ) {
2019 if( md5( $notice ) == $cachedNotice['hash'] ) {
2020 $notice = $cachedNotice['html'];
2021 } else {
2022 $needParse = true;
2023 }
2024 } else {
2025 $needParse = true;
2026 }
2027
2028 if( $needParse ) {
2029 if( is_object( $wgOut ) ) {
2030 $parsed = $wgOut->parse( $notice );
2031 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2032 $notice = $parsed;
2033 } else {
2034 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
2035 $notice = '';
2036 }
2037 }
2038 $notice = '<div id="localNotice">' .$notice . '</div>';
2039 wfProfileOut( $fname );
2040 return $notice;
2041 }
2042
2043 function wfGetNamespaceNotice() {
2044 global $wgTitle;
2045
2046 # Paranoia
2047 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) ) {
2048 return '';
2049 }
2050
2051 $fname = 'wfGetNamespaceNotice';
2052 wfProfileIn( $fname );
2053
2054 $key = 'namespacenotice-' . $wgTitle->getNsText();
2055 $namespaceNotice = wfGetCachedNotice( $key );
2056 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p>&lt;' ) {
2057 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
2058 } else {
2059 $namespaceNotice = '';
2060 }
2061
2062 wfProfileOut( $fname );
2063 return $namespaceNotice;
2064 }
2065
2066 function wfGetSiteNotice() {
2067 global $wgUser;
2068 $fname = 'wfGetSiteNotice';
2069 wfProfileIn( $fname );
2070 $siteNotice = '';
2071
2072 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2073 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2074 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2075 } else {
2076 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2077 if( !$anonNotice ) {
2078 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2079 } else {
2080 $siteNotice = $anonNotice;
2081 }
2082 }
2083 if( !$siteNotice ) {
2084 $siteNotice = wfGetCachedNotice( 'default' );
2085 }
2086 }
2087
2088 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2089 wfProfileOut( $fname );
2090 return $siteNotice;
2091 }
2092
2093 /**
2094 * BC wrapper for MimeMagic::singleton()
2095 * @deprecated No longer needed as of 1.17 (r68836). Remove in 1.19.
2096 */
2097 function &wfGetMimeMagic() {
2098 wfDeprecated( __FUNCTION__ );
2099 return MimeMagic::singleton();
2100 }
2101
2102 /**
2103 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2104 * TEMP environment variables are then checked in sequence, and if none are set
2105 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2106 * or C:\Windows\Temp for Windows and hope for the best.
2107 * It is common to call it with tempnam().
2108 *
2109 * NOTE: When possible, use instead the tmpfile() function to create
2110 * temporary files to avoid race conditions on file creation, etc.
2111 *
2112 * @return String
2113 */
2114 function wfTempDir() {
2115 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2116 $tmp = getenv( $var );
2117 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2118 return $tmp;
2119 }
2120 }
2121 if( function_exists( 'sys_get_temp_dir' ) ) {
2122 return sys_get_temp_dir();
2123 }
2124 # Usual defaults
2125 return wfIsWindows() ? 'C:\Windows\Temp' : '/tmp';
2126 }
2127
2128 /**
2129 * Make directory, and make all parent directories if they don't exist
2130 *
2131 * @param $dir String: full path to directory to create
2132 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2133 * @param $caller String: optional caller param for debugging.
2134 * @return bool
2135 */
2136 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2137 global $wgDirectoryMode;
2138
2139 if ( !is_null( $caller ) ) {
2140 wfDebug( "$caller: called wfMkdirParents($dir)" );
2141 }
2142
2143 if( strval( $dir ) === '' || file_exists( $dir ) ) {
2144 return true;
2145 }
2146
2147 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2148
2149 if ( is_null( $mode ) ) {
2150 $mode = $wgDirectoryMode;
2151 }
2152
2153 // Turn off the normal warning, we're doing our own below
2154 wfSuppressWarnings();
2155 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2156 wfRestoreWarnings();
2157
2158 if( !$ok ) {
2159 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2160 trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
2161 }
2162 return $ok;
2163 }
2164
2165 /**
2166 * Increment a statistics counter
2167 */
2168 function wfIncrStats( $key ) {
2169 global $wgStatsMethod;
2170
2171 if( $wgStatsMethod == 'udp' ) {
2172 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2173 static $socket;
2174 if ( !$socket ) {
2175 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
2176 $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2177 socket_sendto(
2178 $socket,
2179 $statline,
2180 strlen( $statline ),
2181 0,
2182 $wgUDPProfilerHost,
2183 $wgUDPProfilerPort
2184 );
2185 }
2186 $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2187 wfSuppressWarnings();
2188 socket_sendto(
2189 $socket,
2190 $statline,
2191 strlen( $statline ),
2192 0,
2193 $wgUDPProfilerHost,
2194 $wgUDPProfilerPort
2195 );
2196 wfRestoreWarnings();
2197 } elseif( $wgStatsMethod == 'cache' ) {
2198 global $wgMemc;
2199 $key = wfMemcKey( 'stats', $key );
2200 if ( is_null( $wgMemc->incr( $key ) ) ) {
2201 $wgMemc->add( $key, 1 );
2202 }
2203 } else {
2204 // Disabled
2205 }
2206 }
2207
2208 /**
2209 * @param $nr Mixed: the number to format
2210 * @param $acc Integer: the number of digits after the decimal point, default 2
2211 * @param $round Boolean: whether or not to round the value, default true
2212 * @return float
2213 */
2214 function wfPercent( $nr, $acc = 2, $round = true ) {
2215 $ret = sprintf( "%.${acc}f", $nr );
2216 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2217 }
2218
2219 /**
2220 * Encrypt a username/password.
2221 *
2222 * @param $userid Integer: ID of the user
2223 * @param $password String: password of the user
2224 * @return String: hashed password
2225 * @deprecated Use User::crypt() or User::oldCrypt() instead
2226 */
2227 function wfEncryptPassword( $userid, $password ) {
2228 wfDeprecated(__FUNCTION__);
2229 # Just wrap around User::oldCrypt()
2230 return User::oldCrypt( $password, $userid );
2231 }
2232
2233 /**
2234 * Appends to second array if $value differs from that in $default
2235 */
2236 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2237 if ( is_null( $changed ) ) {
2238 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
2239 }
2240 if ( $default[$key] !== $value ) {
2241 $changed[$key] = $value;
2242 }
2243 }
2244
2245 /**
2246 * Since wfMsg() and co suck, they don't return false if the message key they
2247 * looked up didn't exist but a XHTML string, this function checks for the
2248 * nonexistance of messages by looking at wfMsg() output
2249 *
2250 * @param $key String: the message key looked up
2251 * @return Boolean True if the message *doesn't* exist.
2252 */
2253 function wfEmptyMsg( $key ) {
2254 global $wgMessageCache;
2255 return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
2256 }
2257
2258 /**
2259 * Find out whether or not a mixed variable exists in a string
2260 *
2261 * @param $needle String
2262 * @param $str String
2263 * @param $insensitive Boolean
2264 * @return Boolean
2265 */
2266 function in_string( $needle, $str, $insensitive = false ) {
2267 $func = 'strpos';
2268 if( $insensitive ) $func = 'stripos';
2269
2270 return $func( $str, $needle ) !== false;
2271 }
2272
2273 function wfSpecialList( $page, $details ) {
2274 global $wgContLang;
2275 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : '';
2276 return $page . $details;
2277 }
2278
2279 /**
2280 * Returns a regular expression of url protocols
2281 *
2282 * @return String
2283 */
2284 function wfUrlProtocols() {
2285 global $wgUrlProtocols;
2286
2287 static $retval = null;
2288 if ( !is_null( $retval ) ) {
2289 return $retval;
2290 }
2291
2292 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2293 // with LocalSettings files from 1.5
2294 if ( is_array( $wgUrlProtocols ) ) {
2295 $protocols = array();
2296 foreach ( $wgUrlProtocols as $protocol ) {
2297 $protocols[] = preg_quote( $protocol, '/' );
2298 }
2299
2300 $retval = implode( '|', $protocols );
2301 } else {
2302 $retval = $wgUrlProtocols;
2303 }
2304 return $retval;
2305 }
2306
2307 /**
2308 * Safety wrapper around ini_get() for boolean settings.
2309 * The values returned from ini_get() are pre-normalized for settings
2310 * set via php.ini or php_flag/php_admin_flag... but *not*
2311 * for those set via php_value/php_admin_value.
2312 *
2313 * It's fairly common for people to use php_value instead of php_flag,
2314 * which can leave you with an 'off' setting giving a false positive
2315 * for code that just takes the ini_get() return value as a boolean.
2316 *
2317 * To make things extra interesting, setting via php_value accepts
2318 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2319 * Unrecognized values go false... again opposite PHP's own coercion
2320 * from string to bool.
2321 *
2322 * Luckily, 'properly' set settings will always come back as '0' or '1',
2323 * so we only have to worry about them and the 'improper' settings.
2324 *
2325 * I frickin' hate PHP... :P
2326 *
2327 * @param $setting String
2328 * @return Bool
2329 */
2330 function wfIniGetBool( $setting ) {
2331 $val = ini_get( $setting );
2332 // 'on' and 'true' can't have whitespace around them, but '1' can.
2333 return strtolower( $val ) == 'on'
2334 || strtolower( $val ) == 'true'
2335 || strtolower( $val ) == 'yes'
2336 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2337 }
2338
2339 /**
2340 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2341 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2342 *
2343 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2344 * should be omitted
2345 * @return Bool - Whether or not the extension is loaded
2346 */
2347 function wfDl( $extension ) {
2348 if( extension_loaded( $extension ) ) {
2349 return true;
2350 }
2351
2352 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2353 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2354
2355 if( $canDl ) {
2356 wfSuppressWarnings();
2357 dl( $extension . '.' . PHP_SHLIB_SUFFIX );
2358 wfRestoreWarnings();
2359 }
2360 return extension_loaded( $extension );
2361 }
2362
2363 /**
2364 * Execute a shell command, with time and memory limits mirrored from the PHP
2365 * configuration if supported.
2366 * @param $cmd String Command line, properly escaped for shell.
2367 * @param &$retval optional, will receive the program's exit code.
2368 * (non-zero is usually failure)
2369 * @param $environ Array optional environment variables which should be
2370 * added to the executed command environment.
2371 * @return collected stdout as a string (trailing newlines stripped)
2372 */
2373 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2374 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2375
2376 static $disabled;
2377 if ( is_null( $disabled ) ) {
2378 $disabled = false;
2379 if( wfIniGetBool( 'safe_mode' ) ) {
2380 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2381 $disabled = 'safemode';
2382 } else {
2383 $functions = explode( ',', ini_get( 'disable_functions' ) );
2384 $functions = array_map( 'trim', $functions );
2385 $functions = array_map( 'strtolower', $functions );
2386 if ( in_array( 'passthru', $functions ) ) {
2387 wfDebug( "passthru is in disabled_functions\n" );
2388 $disabled = 'passthru';
2389 }
2390 }
2391 }
2392 if ( $disabled ) {
2393 $retval = 1;
2394 return $disabled == 'safemode' ?
2395 'Unable to run external programs in safe mode.' :
2396 'Unable to run external programs, passthru() is disabled.';
2397 }
2398
2399 wfInitShellLocale();
2400
2401 $envcmd = '';
2402 foreach( $environ as $k => $v ) {
2403 if ( wfIsWindows() ) {
2404 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2405 * appear in the environment variable, so we must use carat escaping as documented in
2406 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2407 * Note however that the quote isn't listed there, but is needed, and the parentheses
2408 * are listed there but doesn't appear to need it.
2409 */
2410 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2411 } else {
2412 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2413 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2414 */
2415 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2416 }
2417 }
2418 $cmd = $envcmd . $cmd;
2419
2420 if ( wfIsWindows() ) {
2421 if ( version_compare( PHP_VERSION, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2422 ( version_compare( PHP_VERSION, '5.2.1', '>=' ) || php_uname( 's' ) == 'Windows NT' ) )
2423 {
2424 # Hack to work around PHP's flawed invocation of cmd.exe
2425 # http://news.php.net/php.internals/21796
2426 # Windows 9x doesn't accept any kind of quotes
2427 $cmd = '"' . $cmd . '"';
2428 }
2429 } elseif ( php_uname( 's' ) == 'Linux' ) {
2430 $time = intval( $wgMaxShellTime );
2431 $mem = intval( $wgMaxShellMemory );
2432 $filesize = intval( $wgMaxShellFileSize );
2433
2434 if ( $time > 0 && $mem > 0 ) {
2435 $script = "$IP/bin/ulimit4.sh";
2436 if ( is_executable( $script ) ) {
2437 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2438 }
2439 }
2440 }
2441 wfDebug( "wfShellExec: $cmd\n" );
2442
2443 $retval = 1; // error by default?
2444 ob_start();
2445 passthru( $cmd, $retval );
2446 $output = ob_get_contents();
2447 ob_end_clean();
2448
2449 if ( $retval == 127 ) {
2450 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2451 }
2452 return $output;
2453 }
2454
2455 /**
2456 * Workaround for http://bugs.php.net/bug.php?id=45132
2457 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2458 */
2459 function wfInitShellLocale() {
2460 static $done = false;
2461 if ( $done ) {
2462 return;
2463 }
2464 $done = true;
2465 global $wgShellLocale;
2466 if ( !wfIniGetBool( 'safe_mode' ) ) {
2467 putenv( "LC_CTYPE=$wgShellLocale" );
2468 setlocale( LC_CTYPE, $wgShellLocale );
2469 }
2470 }
2471
2472 /**
2473 * This function works like "use VERSION" in Perl, the program will die with a
2474 * backtrace if the current version of PHP is less than the version provided
2475 *
2476 * This is useful for extensions which due to their nature are not kept in sync
2477 * with releases, and might depend on other versions of PHP than the main code
2478 *
2479 * Note: PHP might die due to parsing errors in some cases before it ever
2480 * manages to call this function, such is life
2481 *
2482 * @see perldoc -f use
2483 *
2484 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2485 * a float
2486 */
2487 function wfUsePHP( $req_ver ) {
2488 $php_ver = PHP_VERSION;
2489
2490 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2491 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2492 }
2493 }
2494
2495 /**
2496 * This function works like "use VERSION" in Perl except it checks the version
2497 * of MediaWiki, the program will die with a backtrace if the current version
2498 * of MediaWiki is less than the version provided.
2499 *
2500 * This is useful for extensions which due to their nature are not kept in sync
2501 * with releases
2502 *
2503 * @see perldoc -f use
2504 *
2505 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2506 * a float
2507 */
2508 function wfUseMW( $req_ver ) {
2509 global $wgVersion;
2510
2511 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2512 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2513 }
2514 }
2515
2516 /**
2517 * Return the final portion of a pathname.
2518 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2519 * http://bugs.php.net/bug.php?id=33898
2520 *
2521 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2522 * We'll consider it so always, as we don't want \s in our Unix paths either.
2523 *
2524 * @param $path String
2525 * @param $suffix String: to remove if present
2526 * @return String
2527 */
2528 function wfBaseName( $path, $suffix = '' ) {
2529 $encSuffix = ( $suffix == '' )
2530 ? ''
2531 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2532 $matches = array();
2533 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2534 return $matches[1];
2535 } else {
2536 return '';
2537 }
2538 }
2539
2540 /**
2541 * Generate a relative path name to the given file.
2542 * May explode on non-matching case-insensitive paths,
2543 * funky symlinks, etc.
2544 *
2545 * @param $path String: absolute destination path including target filename
2546 * @param $from String: Absolute source path, directory only
2547 * @return String
2548 */
2549 function wfRelativePath( $path, $from ) {
2550 // Normalize mixed input on Windows...
2551 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2552 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2553
2554 // Trim trailing slashes -- fix for drive root
2555 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2556 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2557
2558 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2559 $against = explode( DIRECTORY_SEPARATOR, $from );
2560
2561 if( $pieces[0] !== $against[0] ) {
2562 // Non-matching Windows drive letters?
2563 // Return a full path.
2564 return $path;
2565 }
2566
2567 // Trim off common prefix
2568 while( count( $pieces ) && count( $against )
2569 && $pieces[0] == $against[0] ) {
2570 array_shift( $pieces );
2571 array_shift( $against );
2572 }
2573
2574 // relative dots to bump us to the parent
2575 while( count( $against ) ) {
2576 array_unshift( $pieces, '..' );
2577 array_shift( $against );
2578 }
2579
2580 array_push( $pieces, wfBaseName( $path ) );
2581
2582 return implode( DIRECTORY_SEPARATOR, $pieces );
2583 }
2584
2585 /**
2586 * Backwards array plus for people who haven't bothered to read the PHP manual
2587 * XXX: will not darn your socks for you.
2588 *
2589 * @param $array1 Array
2590 * @param [$array2, [...]] Arrays
2591 * @return Array
2592 */
2593 function wfArrayMerge( $array1/* ... */ ) {
2594 $args = func_get_args();
2595 $args = array_reverse( $args, true );
2596 $out = array();
2597 foreach ( $args as $arg ) {
2598 $out += $arg;
2599 }
2600 return $out;
2601 }
2602
2603 /**
2604 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2605 * e.g.
2606 * wfMergeErrorArrays(
2607 * array( array( 'x' ) ),
2608 * array( array( 'x', '2' ) ),
2609 * array( array( 'x' ) ),
2610 * array( array( 'y') )
2611 * );
2612 * returns:
2613 * array(
2614 * array( 'x', '2' ),
2615 * array( 'x' ),
2616 * array( 'y' )
2617 * )
2618 */
2619 function wfMergeErrorArrays( /*...*/ ) {
2620 $args = func_get_args();
2621 $out = array();
2622 foreach ( $args as $errors ) {
2623 foreach ( $errors as $params ) {
2624 # FIXME: sometimes get nested arrays for $params,
2625 # which leads to E_NOTICEs
2626 $spec = implode( "\t", $params );
2627 $out[$spec] = $params;
2628 }
2629 }
2630 return array_values( $out );
2631 }
2632
2633 /**
2634 * parse_url() work-alike, but non-broken. Differences:
2635 *
2636 * 1) Does not raise warnings on bad URLs (just returns false)
2637 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2638 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2639 *
2640 * @param $url String: a URL to parse
2641 * @return Array: bits of the URL in an associative array, per PHP docs
2642 */
2643 function wfParseUrl( $url ) {
2644 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2645 wfSuppressWarnings();
2646 $bits = parse_url( $url );
2647 wfRestoreWarnings();
2648 if ( !$bits ) {
2649 return false;
2650 }
2651
2652 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2653 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2654 $bits['delimiter'] = '://';
2655 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2656 $bits['delimiter'] = ':';
2657 // parse_url detects for news: and mailto: the host part of an url as path
2658 // We have to correct this wrong detection
2659 if ( isset( $bits['path'] ) ) {
2660 $bits['host'] = $bits['path'];
2661 $bits['path'] = '';
2662 }
2663 } else {
2664 return false;
2665 }
2666
2667 return $bits;
2668 }
2669
2670 /**
2671 * Make a URL index, appropriate for the el_index field of externallinks.
2672 */
2673 function wfMakeUrlIndex( $url ) {
2674 $bits = wfParseUrl( $url );
2675
2676 // Reverse the labels in the hostname, convert to lower case
2677 // For emails reverse domainpart only
2678 if ( $bits['scheme'] == 'mailto' ) {
2679 $mailparts = explode( '@', $bits['host'], 2 );
2680 if ( count( $mailparts ) === 2 ) {
2681 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2682 } else {
2683 // No domain specified, don't mangle it
2684 $domainpart = '';
2685 }
2686 $reversedHost = $domainpart . '@' . $mailparts[0];
2687 } else {
2688 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2689 }
2690 // Add an extra dot to the end
2691 // Why? Is it in wrong place in mailto links?
2692 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2693 $reversedHost .= '.';
2694 }
2695 // Reconstruct the pseudo-URL
2696 $prot = $bits['scheme'];
2697 $index = $prot . $bits['delimiter'] . $reversedHost;
2698 // Leave out user and password. Add the port, path, query and fragment
2699 if ( isset( $bits['port'] ) ) {
2700 $index .= ':' . $bits['port'];
2701 }
2702 if ( isset( $bits['path'] ) ) {
2703 $index .= $bits['path'];
2704 } else {
2705 $index .= '/';
2706 }
2707 if ( isset( $bits['query'] ) ) {
2708 $index .= '?' . $bits['query'];
2709 }
2710 if ( isset( $bits['fragment'] ) ) {
2711 $index .= '#' . $bits['fragment'];
2712 }
2713 return $index;
2714 }
2715
2716 /**
2717 * Do any deferred updates and clear the list
2718 *
2719 * @param $commit String: set to 'commit' to commit after every update to
2720 * prevent lock contention
2721 */
2722 function wfDoUpdates( $commit = '' ) {
2723 global $wgDeferredUpdateList;
2724
2725 wfProfileIn( __METHOD__ );
2726
2727 // No need to get master connections in case of empty updates array
2728 if ( !count( $wgDeferredUpdateList ) ) {
2729 wfProfileOut( __METHOD__ );
2730 return;
2731 }
2732
2733 $doCommit = $commit == 'commit';
2734 if ( $doCommit ) {
2735 $dbw = wfGetDB( DB_MASTER );
2736 }
2737
2738 foreach ( $wgDeferredUpdateList as $update ) {
2739 $update->doUpdate();
2740
2741 if ( $doCommit && $dbw->trxLevel() ) {
2742 $dbw->commit();
2743 }
2744 }
2745
2746 $wgDeferredUpdateList = array();
2747 wfProfileOut( __METHOD__ );
2748 }
2749
2750 /**
2751 * Convert an arbitrarily-long digit string from one numeric base
2752 * to another, optionally zero-padding to a minimum column width.
2753 *
2754 * Supports base 2 through 36; digit values 10-36 are represented
2755 * as lowercase letters a-z. Input is case-insensitive.
2756 *
2757 * @param $input String: of digits
2758 * @param $sourceBase Integer: 2-36
2759 * @param $destBase Integer: 2-36
2760 * @param $pad Integer: 1 or greater
2761 * @param $lowercase Boolean
2762 * @return String or false on invalid input
2763 */
2764 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2765 $input = strval( $input );
2766 if( $sourceBase < 2 ||
2767 $sourceBase > 36 ||
2768 $destBase < 2 ||
2769 $destBase > 36 ||
2770 $pad < 1 ||
2771 $sourceBase != intval( $sourceBase ) ||
2772 $destBase != intval( $destBase ) ||
2773 $pad != intval( $pad ) ||
2774 !is_string( $input ) ||
2775 $input == '' ) {
2776 return false;
2777 }
2778 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2779 $inDigits = array();
2780 $outChars = '';
2781
2782 // Decode and validate input string
2783 $input = strtolower( $input );
2784 for( $i = 0; $i < strlen( $input ); $i++ ) {
2785 $n = strpos( $digitChars, $input{$i} );
2786 if( $n === false || $n > $sourceBase ) {
2787 return false;
2788 }
2789 $inDigits[] = $n;
2790 }
2791
2792 // Iterate over the input, modulo-ing out an output digit
2793 // at a time until input is gone.
2794 while( count( $inDigits ) ) {
2795 $work = 0;
2796 $workDigits = array();
2797
2798 // Long division...
2799 foreach( $inDigits as $digit ) {
2800 $work *= $sourceBase;
2801 $work += $digit;
2802
2803 if( $work < $destBase ) {
2804 // Gonna need to pull another digit.
2805 if( count( $workDigits ) ) {
2806 // Avoid zero-padding; this lets us find
2807 // the end of the input very easily when
2808 // length drops to zero.
2809 $workDigits[] = 0;
2810 }
2811 } else {
2812 // Finally! Actual division!
2813 $workDigits[] = intval( $work / $destBase );
2814
2815 // Isn't it annoying that most programming languages
2816 // don't have a single divide-and-remainder operator,
2817 // even though the CPU implements it that way?
2818 $work = $work % $destBase;
2819 }
2820 }
2821
2822 // All that division leaves us with a remainder,
2823 // which is conveniently our next output digit.
2824 $outChars .= $digitChars[$work];
2825
2826 // And we continue!
2827 $inDigits = $workDigits;
2828 }
2829
2830 while( strlen( $outChars ) < $pad ) {
2831 $outChars .= '0';
2832 }
2833
2834 return strrev( $outChars );
2835 }
2836
2837 /**
2838 * Create an object with a given name and an array of construct parameters
2839 * @param $name String
2840 * @param $p Array: parameters
2841 * @deprecated
2842 */
2843 function wfCreateObject( $name, $p ) {
2844 return MWFunction::newObj( $name, $p );
2845 }
2846
2847 function wfHttpOnlySafe() {
2848 global $wgHttpOnlyBlacklist;
2849 if( !version_compare( '5.2', PHP_VERSION, '<' ) ) {
2850 return false;
2851 }
2852
2853 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2854 foreach( $wgHttpOnlyBlacklist as $regex ) {
2855 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2856 return false;
2857 }
2858 }
2859 }
2860
2861 return true;
2862 }
2863
2864 /**
2865 * Initialise php session
2866 */
2867 function wfSetupSession( $sessionId = false ) {
2868 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2869 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2870 if( $wgSessionsInMemcached ) {
2871 require_once( 'MemcachedSessions.php' );
2872 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2873 # Only set this if $wgSessionHandler isn't null and session.save_handler
2874 # hasn't already been set to the desired value (that causes errors)
2875 ini_set( 'session.save_handler', $wgSessionHandler );
2876 }
2877 $httpOnlySafe = wfHttpOnlySafe();
2878 wfDebugLog( 'cookie',
2879 'session_set_cookie_params: "' . implode( '", "',
2880 array(
2881 0,
2882 $wgCookiePath,
2883 $wgCookieDomain,
2884 $wgCookieSecure,
2885 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2886 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2887 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2888 } else {
2889 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2890 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2891 }
2892 session_cache_limiter( 'private, must-revalidate' );
2893 if ( $sessionId ) {
2894 session_id( $sessionId );
2895 }
2896 wfSuppressWarnings();
2897 session_start();
2898 wfRestoreWarnings();
2899 }
2900
2901 /**
2902 * Get an object from the precompiled serialized directory
2903 *
2904 * @return Mixed: the variable on success, false on failure
2905 */
2906 function wfGetPrecompiledData( $name ) {
2907 global $IP;
2908
2909 $file = "$IP/serialized/$name";
2910 if ( file_exists( $file ) ) {
2911 $blob = file_get_contents( $file );
2912 if ( $blob ) {
2913 return unserialize( $blob );
2914 }
2915 }
2916 return false;
2917 }
2918
2919 function wfGetCaller( $level = 2 ) {
2920 $backtrace = wfDebugBacktrace();
2921 if ( isset( $backtrace[$level] ) ) {
2922 return wfFormatStackFrame( $backtrace[$level] );
2923 } else {
2924 $caller = 'unknown';
2925 }
2926 return $caller;
2927 }
2928
2929 /**
2930 * Return a string consisting of callers in the stack. Useful sometimes
2931 * for profiling specific points.
2932 *
2933 * @param $limit The maximum depth of the stack frame to return, or false for
2934 * the entire stack.
2935 */
2936 function wfGetAllCallers( $limit = 3 ) {
2937 $trace = array_reverse( wfDebugBacktrace() );
2938 if ( !$limit || $limit > count( $trace ) - 1 ) {
2939 $limit = count( $trace ) - 1;
2940 }
2941 $trace = array_slice( $trace, -$limit - 1, $limit );
2942 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2943 }
2944
2945 /**
2946 * Return a string representation of frame
2947 */
2948 function wfFormatStackFrame( $frame ) {
2949 return isset( $frame['class'] ) ?
2950 $frame['class'] . '::' . $frame['function'] :
2951 $frame['function'];
2952 }
2953
2954 /**
2955 * Get a cache key
2956 */
2957 function wfMemcKey( /*... */ ) {
2958 $args = func_get_args();
2959 $key = wfWikiID() . ':' . implode( ':', $args );
2960 $key = str_replace( ' ', '_', $key );
2961 return $key;
2962 }
2963
2964 /**
2965 * Get a cache key for a foreign DB
2966 */
2967 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2968 $args = array_slice( func_get_args(), 2 );
2969 if ( $prefix ) {
2970 $key = "$db-$prefix:" . implode( ':', $args );
2971 } else {
2972 $key = $db . ':' . implode( ':', $args );
2973 }
2974 return $key;
2975 }
2976
2977 /**
2978 * Get an ASCII string identifying this wiki
2979 * This is used as a prefix in memcached keys
2980 */
2981 function wfWikiID() {
2982 global $wgDBprefix, $wgDBname;
2983 if ( $wgDBprefix ) {
2984 return "$wgDBname-$wgDBprefix";
2985 } else {
2986 return $wgDBname;
2987 }
2988 }
2989
2990 /**
2991 * Split a wiki ID into DB name and table prefix
2992 */
2993 function wfSplitWikiID( $wiki ) {
2994 $bits = explode( '-', $wiki, 2 );
2995 if ( count( $bits ) < 2 ) {
2996 $bits[] = '';
2997 }
2998 return $bits;
2999 }
3000
3001 /**
3002 * Get a Database object.
3003 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3004 * master (for write queries), DB_SLAVE for potentially lagged read
3005 * queries, or an integer >= 0 for a particular server.
3006 *
3007 * @param $groups Mixed: query groups. An array of group names that this query
3008 * belongs to. May contain a single string if the query is only
3009 * in one group.
3010 *
3011 * @param $wiki String: the wiki ID, or false for the current wiki
3012 *
3013 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3014 * will always return the same object, unless the underlying connection or load
3015 * balancer is manually destroyed.
3016 *
3017 * @return DatabaseBase
3018 */
3019 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3020 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3021 }
3022
3023 /**
3024 * Get a load balancer object.
3025 *
3026 * @param $wiki String: wiki ID, or false for the current wiki
3027 * @return LoadBalancer
3028 */
3029 function wfGetLB( $wiki = false ) {
3030 return wfGetLBFactory()->getMainLB( $wiki );
3031 }
3032
3033 /**
3034 * Get the load balancer factory object
3035 * @return LBFactory
3036 */
3037 function &wfGetLBFactory() {
3038 return LBFactory::singleton();
3039 }
3040
3041 /**
3042 * Find a file.
3043 * Shortcut for RepoGroup::singleton()->findFile()
3044 * @param $title String or Title object
3045 * @param $options Associative array of options:
3046 * time: requested time for an archived image, or false for the
3047 * current version. An image object will be returned which was
3048 * created at the specified time.
3049 *
3050 * ignoreRedirect: If true, do not follow file redirects
3051 *
3052 * private: If true, return restricted (deleted) files if the current
3053 * user is allowed to view them. Otherwise, such files will not
3054 * be found.
3055 *
3056 * bypassCache: If true, do not use the process-local cache of File objects
3057 *
3058 * @return File, or false if the file does not exist
3059 */
3060 function wfFindFile( $title, $options = array() ) {
3061 return RepoGroup::singleton()->findFile( $title, $options );
3062 }
3063
3064 /**
3065 * Get an object referring to a locally registered file.
3066 * Returns a valid placeholder object if the file does not exist.
3067 * @param $title Title or String
3068 * @return File, or null if passed an invalid Title
3069 */
3070 function wfLocalFile( $title ) {
3071 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3072 }
3073
3074 /**
3075 * Should low-performance queries be disabled?
3076 *
3077 * @return Boolean
3078 */
3079 function wfQueriesMustScale() {
3080 global $wgMiserMode;
3081 return $wgMiserMode
3082 || ( SiteStats::pages() > 100000
3083 && SiteStats::edits() > 1000000
3084 && SiteStats::users() > 10000 );
3085 }
3086
3087 /**
3088 * Get the path to a specified script file, respecting file
3089 * extensions; this is a wrapper around $wgScriptExtension etc.
3090 *
3091 * @param $script String: script filename, sans extension
3092 * @return String
3093 */
3094 function wfScript( $script = 'index' ) {
3095 global $wgScriptPath, $wgScriptExtension;
3096 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3097 }
3098
3099 /**
3100 * Get the script URL.
3101 *
3102 * @return script URL
3103 */
3104 function wfGetScriptUrl() {
3105 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3106 #
3107 # as it was called, minus the query string.
3108 #
3109 # Some sites use Apache rewrite rules to handle subdomains,
3110 # and have PHP set up in a weird way that causes PHP_SELF
3111 # to contain the rewritten URL instead of the one that the
3112 # outside world sees.
3113 #
3114 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3115 # provides containing the "before" URL.
3116 return $_SERVER['SCRIPT_NAME'];
3117 } else {
3118 return $_SERVER['URL'];
3119 }
3120 }
3121
3122 /**
3123 * Convenience function converts boolean values into "true"
3124 * or "false" (string) values
3125 *
3126 * @param $value Boolean
3127 * @return String
3128 */
3129 function wfBoolToStr( $value ) {
3130 return $value ? 'true' : 'false';
3131 }
3132
3133 /**
3134 * Load an extension messages file
3135 * @deprecated in 1.16, warnings in 1.18, remove in 1.20
3136 */
3137 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3138 wfDeprecated( __FUNCTION__ );
3139 }
3140
3141 /**
3142 * Get a platform-independent path to the null file, e.g.
3143 * /dev/null
3144 *
3145 * @return string
3146 */
3147 function wfGetNull() {
3148 return wfIsWindows()
3149 ? 'NUL'
3150 : '/dev/null';
3151 }
3152
3153 /**
3154 * Displays a maxlag error
3155 *
3156 * @param $host String: server that lags the most
3157 * @param $lag Integer: maxlag (actual)
3158 * @param $maxLag Integer: maxlag (requested)
3159 */
3160 function wfMaxlagError( $host, $lag, $maxLag ) {
3161 global $wgShowHostnames;
3162 header( 'HTTP/1.1 503 Service Unavailable' );
3163 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3164 header( 'X-Database-Lag: ' . intval( $lag ) );
3165 header( 'Content-Type: text/plain' );
3166 if( $wgShowHostnames ) {
3167 echo "Waiting for $host: $lag seconds lagged\n";
3168 } else {
3169 echo "Waiting for a database server: $lag seconds lagged\n";
3170 }
3171 }
3172
3173 /**
3174 * Throws a warning that $function is deprecated
3175 * @param $function String
3176 * @return null
3177 */
3178 function wfDeprecated( $function ) {
3179 static $functionsWarned = array();
3180 if ( !isset( $functionsWarned[$function] ) ) {
3181 $functionsWarned[$function] = true;
3182 wfWarn( "Use of $function is deprecated.", 2 );
3183 }
3184 }
3185
3186 /**
3187 * Send a warning either to the debug log or in a PHP error depending on
3188 * $wgDevelopmentWarnings
3189 *
3190 * @param $msg String: message to send
3191 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3192 * find the correct caller (1 = function calling wfWarn, ...)
3193 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3194 * is true
3195 */
3196 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
3197 $callers = wfDebugBacktrace();
3198 if( isset( $callers[$callerOffset + 1] ) ){
3199 $callerfunc = $callers[$callerOffset + 1];
3200 $callerfile = $callers[$callerOffset];
3201 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3202 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3203 } else {
3204 $file = '(internal function)';
3205 }
3206 $func = '';
3207 if( isset( $callerfunc['class'] ) ) {
3208 $func .= $callerfunc['class'] . '::';
3209 }
3210 if( isset( $callerfunc['function'] ) ) {
3211 $func .= $callerfunc['function'];
3212 }
3213 $msg .= " [Called from $func in $file]";
3214 }
3215
3216 global $wgDevelopmentWarnings;
3217 if ( $wgDevelopmentWarnings ) {
3218 trigger_error( $msg, $level );
3219 } else {
3220 wfDebug( "$msg\n" );
3221 }
3222 }
3223
3224 /**
3225 * Sleep until the worst slave's replication lag is less than or equal to
3226 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3227 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3228 * a no-op if there are no slaves.
3229 *
3230 * Every time the function has to wait for a slave, it will print a message to
3231 * that effect (and then sleep for a little while), so it's probably not best
3232 * to use this outside maintenance scripts in its present form.
3233 *
3234 * @param $maxLag Integer
3235 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3236 * @return null
3237 */
3238 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3239 if( $maxLag ) {
3240 $lb = wfGetLB( $wiki );
3241 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3242 while( $lag > $maxLag ) {
3243 wfSuppressWarnings();
3244 $name = gethostbyaddr( $host );
3245 wfRestoreWarnings();
3246 if( $name !== false ) {
3247 $host = $name;
3248 }
3249 print "Waiting for $host (lagged $lag seconds)...\n";
3250 sleep( $maxLag );
3251 list( $host, $lag ) = $lb->getMaxLag();
3252 }
3253 }
3254 }
3255
3256 /**
3257 * Used to be used for outputting text in the installer/updater
3258 * @deprecated Warnings in 1.19, removal in 1.20
3259 */
3260 function wfOut( $s ) {
3261 global $wgCommandLineMode;
3262 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3263 echo $s;
3264 } else {
3265 echo htmlspecialchars( $s );
3266 }
3267 flush();
3268 }
3269
3270 /**
3271 * Count down from $n to zero on the terminal, with a one-second pause
3272 * between showing each number. For use in command-line scripts.
3273 */
3274 function wfCountDown( $n ) {
3275 for ( $i = $n; $i >= 0; $i-- ) {
3276 if ( $i != $n ) {
3277 echo str_repeat( "\x08", strlen( $i + 1 ) );
3278 }
3279 echo $i;
3280 flush();
3281 if ( $i ) {
3282 sleep( 1 );
3283 }
3284 }
3285 echo "\n";
3286 }
3287
3288 /**
3289 * Generate a random 32-character hexadecimal token.
3290 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3291 * characters before hashing.
3292 */
3293 function wfGenerateToken( $salt = '' ) {
3294 $salt = serialize( $salt );
3295 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3296 }
3297
3298 /**
3299 * Replace all invalid characters with -
3300 * @param $name Mixed: filename to process
3301 */
3302 function wfStripIllegalFilenameChars( $name ) {
3303 global $wgIllegalFileChars;
3304 $name = wfBaseName( $name );
3305 $name = preg_replace(
3306 "/[^" . Title::legalChars() . "]" .
3307 ( $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '' ) .
3308 "/",
3309 '-',
3310 $name
3311 );
3312 return $name;
3313 }
3314
3315 /**
3316 * Insert array into another array after the specified *KEY*
3317 * @param $array Array: The array.
3318 * @param $insert Array: The array to insert.
3319 * @param $after Mixed: The key to insert after
3320 */
3321 function wfArrayInsertAfter( $array, $insert, $after ) {
3322 // Find the offset of the element to insert after.
3323 $keys = array_keys( $array );
3324 $offsetByKey = array_flip( $keys );
3325
3326 $offset = $offsetByKey[$after];
3327
3328 // Insert at the specified offset
3329 $before = array_slice( $array, 0, $offset + 1, true );
3330 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
3331
3332 $output = $before + $insert + $after;
3333
3334 return $output;
3335 }
3336
3337 /* Recursively converts the parameter (an object) to an array with the same data */
3338 function wfObjectToArray( $object, $recursive = true ) {
3339 $array = array();
3340 foreach ( get_object_vars( $object ) as $key => $value ) {
3341 if ( is_object( $value ) && $recursive ) {
3342 $value = wfObjectToArray( $value );
3343 }
3344
3345 $array[$key] = $value;
3346 }
3347
3348 return $array;
3349 }
3350
3351 /**
3352 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3353 * @return Integer value memory was set to.
3354 */
3355 function wfMemoryLimit() {
3356 global $wgMemoryLimit;
3357 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3358 if( $memlimit != -1 ) {
3359 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3360 if( $conflimit == -1 ) {
3361 wfDebug( "Removing PHP's memory limit\n" );
3362 wfSuppressWarnings();
3363 ini_set( 'memory_limit', $conflimit );
3364 wfRestoreWarnings();
3365 return $conflimit;
3366 } elseif ( $conflimit > $memlimit ) {
3367 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3368 wfSuppressWarnings();
3369 ini_set( 'memory_limit', $conflimit );
3370 wfRestoreWarnings();
3371 return $conflimit;
3372 }
3373 }
3374 return $memlimit;
3375 }
3376
3377 /**
3378 * Converts shorthand byte notation to integer form
3379 * @param $string String
3380 * @return Integer
3381 */
3382 function wfShorthandToInteger( $string = '' ) {
3383 $string = trim( $string );
3384 if( $string === '' ) {
3385 return -1;
3386 }
3387 $last = $string[strlen( $string ) - 1];
3388 $val = intval( $string );
3389 switch( $last ) {
3390 case 'g':
3391 case 'G':
3392 $val *= 1024;
3393 // break intentionally missing
3394 case 'm':
3395 case 'M':
3396 $val *= 1024;
3397 // break intentionally missing
3398 case 'k':
3399 case 'K':
3400 $val *= 1024;
3401 }
3402
3403 return $val;
3404 }
3405
3406 /**
3407 * Get the normalised IETF language tag
3408 * @param $code String: The language code.
3409 * @return $langCode String: The language code which complying with BCP 47 standards.
3410 */
3411 function wfBCP47( $code ) {
3412 $codeSegment = explode( '-', $code );
3413 foreach ( $codeSegment as $segNo => $seg ) {
3414 if ( count( $codeSegment ) > 0 ) {
3415 // ISO 3166 country code
3416 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3417 $codeBCP[$segNo] = strtoupper( $seg );
3418 // ISO 15924 script code
3419 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3420 $codeBCP[$segNo] = ucfirst( $seg );
3421 // Use lowercase for other cases
3422 } else {
3423 $codeBCP[$segNo] = strtolower( $seg );
3424 }
3425 } else {
3426 // Use lowercase for single segment
3427 $codeBCP[$segNo] = strtolower( $seg );
3428 }
3429 }
3430 $langCode = implode( '-', $codeBCP );
3431 return $langCode;
3432 }
3433
3434 function wfArrayMap( $function, $input ) {
3435 $ret = array_map( $function, $input );
3436 foreach ( $ret as $key => $value ) {
3437 $taint = istainted( $input[$key] );
3438 if ( $taint ) {
3439 taint( $ret[$key], $taint );
3440 }
3441 }
3442 return $ret;
3443 }