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