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