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