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