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