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