Introduced Maintenance::getDB() and corresponding setDB() to control externally what...
[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 * Since wfMsg() and co suck, they don't return false if the message key they
994 * looked up didn't exist but a XHTML string, this function checks for the
995 * nonexistance of messages by checking the MessageCache::get() result directly.
996 *
997 * @param $key String: the message key looked up
998 * @return Boolean True if the message *doesn't* exist.
999 */
1000 function wfEmptyMsg( $key ) {
1001 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1002 }
1003
1004 /**
1005 * Print an error message and die, returning nonzero to the shell if any. Plain die()
1006 * fails to return nonzero to the shell if you pass a string. Entry points may customise
1007 * this function to return a prettier error message, but implementations must not assume
1008 * access to any of the usual MediaWiki infrastructure (AutoLoader, localisation, database,
1009 * etc). This should not be called directly once $wgFullyInitialised is set; instead,
1010 * throw an exception and let Exception.php handle whether or not it's possible to show
1011 * a prettier error.
1012 *
1013 * @param $msg String
1014 */
1015 if( !function_exists( 'wfDie' ) ){
1016 function wfDie( $msg = '' ) {
1017 echo $msg;
1018 die( 1 );
1019 }
1020 }
1021
1022 /**
1023 * Throw a debugging exception. This function previously once exited the process,
1024 * but now throws an exception instead, with similar results.
1025 *
1026 * @param $msg String: message shown when dieing.
1027 */
1028 function wfDebugDieBacktrace( $msg = '' ) {
1029 throw new MWException( $msg );
1030 }
1031
1032 /**
1033 * Fetch server name for use in error reporting etc.
1034 * Use real server name if available, so we know which machine
1035 * in a server farm generated the current page.
1036 *
1037 * @return string
1038 */
1039 function wfHostname() {
1040 static $host;
1041 if ( is_null( $host ) ) {
1042 if ( function_exists( 'posix_uname' ) ) {
1043 // This function not present on Windows
1044 $uname = @posix_uname();
1045 } else {
1046 $uname = false;
1047 }
1048 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1049 $host = $uname['nodename'];
1050 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1051 # Windows computer name
1052 $host = getenv( 'COMPUTERNAME' );
1053 } else {
1054 # This may be a virtual server.
1055 $host = $_SERVER['SERVER_NAME'];
1056 }
1057 }
1058 return $host;
1059 }
1060
1061 /**
1062 * Returns a HTML comment with the elapsed time since request.
1063 * This method has no side effects.
1064 *
1065 * @return string
1066 */
1067 function wfReportTime() {
1068 global $wgRequestTime, $wgShowHostnames;
1069
1070 $now = wfTime();
1071 $elapsed = $now - $wgRequestTime;
1072
1073 return $wgShowHostnames
1074 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1075 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1076 }
1077
1078 /**
1079 * Safety wrapper for debug_backtrace().
1080 *
1081 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1082 * murky circumstances, which may be triggered in part by stub objects
1083 * or other fancy talkin'.
1084 *
1085 * Will return an empty array if Zend Optimizer is detected or if
1086 * debug_backtrace is disabled, otherwise the output from
1087 * debug_backtrace() (trimmed).
1088 *
1089 * @return array of backtrace information
1090 */
1091 function wfDebugBacktrace() {
1092 static $disabled = null;
1093
1094 if( extension_loaded( 'Zend Optimizer' ) ) {
1095 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1096 return array();
1097 }
1098
1099 if ( is_null( $disabled ) ) {
1100 $disabled = false;
1101 $functions = explode( ',', ini_get( 'disable_functions' ) );
1102 $functions = array_map( 'trim', $functions );
1103 $functions = array_map( 'strtolower', $functions );
1104 if ( in_array( 'debug_backtrace', $functions ) ) {
1105 wfDebug( "debug_backtrace is in disabled_functions\n" );
1106 $disabled = true;
1107 }
1108 }
1109 if ( $disabled ) {
1110 return array();
1111 }
1112
1113 return array_slice( debug_backtrace(), 1 );
1114 }
1115
1116 /**
1117 * Get a debug backtrace as a string
1118 *
1119 * @return string
1120 */
1121 function wfBacktrace() {
1122 global $wgCommandLineMode;
1123
1124 if ( $wgCommandLineMode ) {
1125 $msg = '';
1126 } else {
1127 $msg = "<ul>\n";
1128 }
1129 $backtrace = wfDebugBacktrace();
1130 foreach( $backtrace as $call ) {
1131 if( isset( $call['file'] ) ) {
1132 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
1133 $file = $f[count( $f ) - 1];
1134 } else {
1135 $file = '-';
1136 }
1137 if( isset( $call['line'] ) ) {
1138 $line = $call['line'];
1139 } else {
1140 $line = '-';
1141 }
1142 if ( $wgCommandLineMode ) {
1143 $msg .= "$file line $line calls ";
1144 } else {
1145 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1146 }
1147 if( !empty( $call['class'] ) ) {
1148 $msg .= $call['class'] . '::';
1149 }
1150 $msg .= $call['function'] . '()';
1151
1152 if ( $wgCommandLineMode ) {
1153 $msg .= "\n";
1154 } else {
1155 $msg .= "</li>\n";
1156 }
1157 }
1158 if ( $wgCommandLineMode ) {
1159 $msg .= "\n";
1160 } else {
1161 $msg .= "</ul>\n";
1162 }
1163
1164 return $msg;
1165 }
1166
1167
1168 /* Some generic result counters, pulled out of SearchEngine */
1169
1170
1171 /**
1172 * @todo document
1173 *
1174 * @param $offset Int
1175 * @param $limit Int
1176 * @return String
1177 */
1178 function wfShowingResults( $offset, $limit ) {
1179 global $wgLang;
1180 return wfMsgExt(
1181 'showingresults',
1182 array( 'parseinline' ),
1183 $wgLang->formatNum( $limit ),
1184 $wgLang->formatNum( $offset + 1 )
1185 );
1186 }
1187
1188 /**
1189 * @todo document
1190 *
1191 * @param $offset Int
1192 * @param $limit Int
1193 * @param $num Int
1194 * @return String
1195 */
1196 function wfShowingResultsNum( $offset, $limit, $num ) {
1197 global $wgLang;
1198 return wfMsgExt(
1199 'showingresultsnum',
1200 array( 'parseinline' ),
1201 $wgLang->formatNum( $limit ),
1202 $wgLang->formatNum( $offset + 1 ),
1203 $wgLang->formatNum( $num )
1204 );
1205 }
1206
1207 /**
1208 * Generate (prev x| next x) (20|50|100...) type links for paging
1209 *
1210 * @param $offset String
1211 * @param $limit Integer
1212 * @param $link String
1213 * @param $query String: optional URL query parameter string
1214 * @param $atend Bool: optional param for specified if this is the last page
1215 * @return String
1216 */
1217 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1218 global $wgLang;
1219 $fmtLimit = $wgLang->formatNum( $limit );
1220 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
1221 # Get prev/next link display text
1222 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1223 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1224 # Get prev/next link title text
1225 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1226 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1227 # Fetch the title object
1228 if( is_object( $link ) ) {
1229 $title =& $link;
1230 } else {
1231 $title = Title::newFromText( $link );
1232 if( is_null( $title ) ) {
1233 return false;
1234 }
1235 }
1236 # Make 'previous' link
1237 if( 0 != $offset ) {
1238 $po = $offset - $limit;
1239 $po = max( $po, 0 );
1240 $q = "limit={$limit}&offset={$po}";
1241 if( $query != '' ) {
1242 $q .= '&' . $query;
1243 }
1244 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1245 } else {
1246 $plink = $prev;
1247 }
1248 # Make 'next' link
1249 $no = $offset + $limit;
1250 $q = "limit={$limit}&offset={$no}";
1251 if( $query != '' ) {
1252 $q .= '&' . $query;
1253 }
1254 if( $atend ) {
1255 $nlink = $next;
1256 } else {
1257 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1258 }
1259 # Make links to set number of items per page
1260 $nums = $wgLang->pipeList( array(
1261 wfNumLink( $offset, 20, $title, $query ),
1262 wfNumLink( $offset, 50, $title, $query ),
1263 wfNumLink( $offset, 100, $title, $query ),
1264 wfNumLink( $offset, 250, $title, $query ),
1265 wfNumLink( $offset, 500, $title, $query )
1266 ) );
1267 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1268 }
1269
1270 /**
1271 * Generate links for (20|50|100...) items-per-page links
1272 *
1273 * @param $offset String
1274 * @param $limit Integer
1275 * @param $title Title
1276 * @param $query String: optional URL query parameter string
1277 */
1278 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1279 global $wgLang;
1280 if( $query == '' ) {
1281 $q = '';
1282 } else {
1283 $q = $query.'&';
1284 }
1285 $q .= "limit={$limit}&offset={$offset}";
1286 $fmtLimit = $wgLang->formatNum( $limit );
1287 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1288 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1289 return $s;
1290 }
1291
1292 /**
1293 * @todo document
1294 * @todo FIXME: We may want to blacklist some broken browsers
1295 *
1296 * @param $force Bool
1297 * @return bool Whereas client accept gzip compression
1298 */
1299 function wfClientAcceptsGzip( $force = false ) {
1300 static $result = null;
1301 if ( $result === null || $force ) {
1302 $result = false;
1303 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1304 # @todo FIXME: We may want to blacklist some broken browsers
1305 $m = array();
1306 if( preg_match(
1307 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1308 $_SERVER['HTTP_ACCEPT_ENCODING'],
1309 $m )
1310 )
1311 {
1312 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1313 $result = false;
1314 return $result;
1315 }
1316 wfDebug( " accepts gzip\n" );
1317 $result = true;
1318 }
1319 }
1320 }
1321 return $result;
1322 }
1323
1324 /**
1325 * Obtain the offset and limit values from the request string;
1326 * used in special pages
1327 *
1328 * @param $deflimit Int default limit if none supplied
1329 * @param $optionname String Name of a user preference to check against
1330 * @return array
1331 *
1332 */
1333 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1334 global $wgRequest;
1335 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1336 }
1337
1338 /**
1339 * Escapes the given text so that it may be output using addWikiText()
1340 * without any linking, formatting, etc. making its way through. This
1341 * is achieved by substituting certain characters with HTML entities.
1342 * As required by the callers, <nowiki> is not used.
1343 *
1344 * @param $text String: text to be escaped
1345 * @return String
1346 */
1347 function wfEscapeWikiText( $text ) {
1348 $text = strtr( "\n$text", array(
1349 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1350 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1351 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1352 "\n#" => "\n&#35;", "\n*" => "\n&#42;",
1353 "\n:" => "\n&#58;", "\n;" => "\n&#59;",
1354 '://' => '&#58;//', 'ISBN ' => 'ISBN&#32;', 'RFC ' => 'RFC&#32;',
1355 ) );
1356 return substr( $text, 1 );
1357 }
1358
1359 /**
1360 * Get the current unix timetstamp with microseconds. Useful for profiling
1361 * @return Float
1362 */
1363 function wfTime() {
1364 return microtime( true );
1365 }
1366
1367 /**
1368 * Sets dest to source and returns the original value of dest
1369 * If source is NULL, it just returns the value, it doesn't set the variable
1370 * If force is true, it will set the value even if source is NULL
1371 *
1372 * @param $dest Mixed
1373 * @param $source Mixed
1374 * @param $force Bool
1375 * @return Mixed
1376 */
1377 function wfSetVar( &$dest, $source, $force = false ) {
1378 $temp = $dest;
1379 if ( !is_null( $source ) || $force ) {
1380 $dest = $source;
1381 }
1382 return $temp;
1383 }
1384
1385 /**
1386 * As for wfSetVar except setting a bit
1387 *
1388 * @param $dest Int
1389 * @param $bit Int
1390 * @param $state Bool
1391 */
1392 function wfSetBit( &$dest, $bit, $state = true ) {
1393 $temp = (bool)( $dest & $bit );
1394 if ( !is_null( $state ) ) {
1395 if ( $state ) {
1396 $dest |= $bit;
1397 } else {
1398 $dest &= ~$bit;
1399 }
1400 }
1401 return $temp;
1402 }
1403
1404 /**
1405 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1406 * "days=7&limit=100". Options in the first array override options in the second.
1407 * Options set to "" will not be output.
1408 *
1409 * @param $array1 Array( String|Array )
1410 * @param $array2 Array( String|Array )
1411 * @return String
1412 */
1413 function wfArrayToCGI( $array1, $array2 = null ) {
1414 if ( !is_null( $array2 ) ) {
1415 $array1 = $array1 + $array2;
1416 }
1417
1418 $cgi = '';
1419 foreach ( $array1 as $key => $value ) {
1420 if ( $value !== '' ) {
1421 if ( $cgi != '' ) {
1422 $cgi .= '&';
1423 }
1424 if ( is_array( $value ) ) {
1425 $firstTime = true;
1426 foreach ( $value as $v ) {
1427 $cgi .= ( $firstTime ? '' : '&') .
1428 urlencode( $key . '[]' ) . '=' .
1429 urlencode( $v );
1430 $firstTime = false;
1431 }
1432 } else {
1433 if ( is_object( $value ) ) {
1434 $value = $value->__toString();
1435 }
1436 $cgi .= urlencode( $key ) . '=' .
1437 urlencode( $value );
1438 }
1439 }
1440 }
1441 return $cgi;
1442 }
1443
1444 /**
1445 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1446 * its argument and returns the same string in array form. This allows compa-
1447 * tibility with legacy functions that accept raw query strings instead of nice
1448 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1449 * valid query strings, or it will explode.
1450 *
1451 * @param $query String: query string
1452 * @return array Array version of input
1453 */
1454 function wfCgiToArray( $query ) {
1455 if( isset( $query[0] ) && $query[0] == '?' ) {
1456 $query = substr( $query, 1 );
1457 }
1458 $bits = explode( '&', $query );
1459 $ret = array();
1460 foreach( $bits as $bit ) {
1461 if( $bit === '' ) {
1462 continue;
1463 }
1464 list( $key, $value ) = explode( '=', $bit );
1465 $key = urldecode( $key );
1466 $value = urldecode( $value );
1467 $ret[$key] = $value;
1468 }
1469 return $ret;
1470 }
1471
1472 /**
1473 * Append a query string to an existing URL, which may or may not already
1474 * have query string parameters already. If so, they will be combined.
1475 *
1476 * @param $url String
1477 * @param $query Mixed: string or associative array
1478 * @return string
1479 */
1480 function wfAppendQuery( $url, $query ) {
1481 if ( is_array( $query ) ) {
1482 $query = wfArrayToCGI( $query );
1483 }
1484 if( $query != '' ) {
1485 if( false === strpos( $url, '?' ) ) {
1486 $url .= '?';
1487 } else {
1488 $url .= '&';
1489 }
1490 $url .= $query;
1491 }
1492 return $url;
1493 }
1494
1495 /**
1496 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1497 * and $wgProto are correct.
1498 *
1499 * @todo this won't work with current-path-relative URLs
1500 * like "subdir/foo.html", etc.
1501 *
1502 * @param $url String: either fully-qualified or a local path + query
1503 * @return string Fully-qualified URL
1504 */
1505 function wfExpandUrl( $url ) {
1506 if( substr( $url, 0, 2 ) == '//' ) {
1507 global $wgProto;
1508 return $wgProto . ':' . $url;
1509 } elseif( substr( $url, 0, 1 ) == '/' ) {
1510 global $wgServer;
1511 return $wgServer . $url;
1512 } else {
1513 return $url;
1514 }
1515 }
1516
1517 /**
1518 * Windows-compatible version of escapeshellarg()
1519 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1520 * function puts single quotes in regardless of OS.
1521 *
1522 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1523 * earlier distro releases of PHP)
1524 *
1525 * @param varargs
1526 * @return String
1527 */
1528 function wfEscapeShellArg( ) {
1529 wfInitShellLocale();
1530
1531 $args = func_get_args();
1532 $first = true;
1533 $retVal = '';
1534 foreach ( $args as $arg ) {
1535 if ( !$first ) {
1536 $retVal .= ' ';
1537 } else {
1538 $first = false;
1539 }
1540
1541 if ( wfIsWindows() ) {
1542 // Escaping for an MSVC-style command line parser and CMD.EXE
1543 // Refs:
1544 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1545 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1546 // * Bug #13518
1547 // * CR r63214
1548 // Double the backslashes before any double quotes. Escape the double quotes.
1549 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1550 $arg = '';
1551 $iteration = 0;
1552 foreach ( $tokens as $token ) {
1553 if ( $iteration % 2 == 1 ) {
1554 // Delimiter, a double quote preceded by zero or more slashes
1555 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1556 } elseif ( $iteration % 4 == 2 ) {
1557 // ^ in $token will be outside quotes, need to be escaped
1558 $arg .= str_replace( '^', '^^', $token );
1559 } else { // $iteration % 4 == 0
1560 // ^ in $token will appear inside double quotes, so leave as is
1561 $arg .= $token;
1562 }
1563 $iteration++;
1564 }
1565 // Double the backslashes before the end of the string, because
1566 // we will soon add a quote
1567 $m = array();
1568 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1569 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1570 }
1571
1572 // Add surrounding quotes
1573 $retVal .= '"' . $arg . '"';
1574 } else {
1575 $retVal .= escapeshellarg( $arg );
1576 }
1577 }
1578 return $retVal;
1579 }
1580
1581 /**
1582 * wfMerge attempts to merge differences between three texts.
1583 * Returns true for a clean merge and false for failure or a conflict.
1584 *
1585 * @param $old String
1586 * @param $mine String
1587 * @param $yours String
1588 * @param $result String
1589 * @return Bool
1590 */
1591 function wfMerge( $old, $mine, $yours, &$result ) {
1592 global $wgDiff3;
1593
1594 # This check may also protect against code injection in
1595 # case of broken installations.
1596 wfSuppressWarnings();
1597 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1598 wfRestoreWarnings();
1599
1600 if( !$haveDiff3 ) {
1601 wfDebug( "diff3 not found\n" );
1602 return false;
1603 }
1604
1605 # Make temporary files
1606 $td = wfTempDir();
1607 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1608 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1609 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1610
1611 fwrite( $oldtextFile, $old );
1612 fclose( $oldtextFile );
1613 fwrite( $mytextFile, $mine );
1614 fclose( $mytextFile );
1615 fwrite( $yourtextFile, $yours );
1616 fclose( $yourtextFile );
1617
1618 # Check for a conflict
1619 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1620 wfEscapeShellArg( $mytextName ) . ' ' .
1621 wfEscapeShellArg( $oldtextName ) . ' ' .
1622 wfEscapeShellArg( $yourtextName );
1623 $handle = popen( $cmd, 'r' );
1624
1625 if( fgets( $handle, 1024 ) ) {
1626 $conflict = true;
1627 } else {
1628 $conflict = false;
1629 }
1630 pclose( $handle );
1631
1632 # Merge differences
1633 $cmd = $wgDiff3 . ' -a -e --merge ' .
1634 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1635 $handle = popen( $cmd, 'r' );
1636 $result = '';
1637 do {
1638 $data = fread( $handle, 8192 );
1639 if ( strlen( $data ) == 0 ) {
1640 break;
1641 }
1642 $result .= $data;
1643 } while ( true );
1644 pclose( $handle );
1645 unlink( $mytextName );
1646 unlink( $oldtextName );
1647 unlink( $yourtextName );
1648
1649 if ( $result === '' && $old !== '' && !$conflict ) {
1650 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1651 $conflict = true;
1652 }
1653 return !$conflict;
1654 }
1655
1656 /**
1657 * Returns unified plain-text diff of two texts.
1658 * Useful for machine processing of diffs.
1659 *
1660 * @param $before String: the text before the changes.
1661 * @param $after String: the text after the changes.
1662 * @param $params String: command-line options for the diff command.
1663 * @return String: unified diff of $before and $after
1664 */
1665 function wfDiff( $before, $after, $params = '-u' ) {
1666 if ( $before == $after ) {
1667 return '';
1668 }
1669
1670 global $wgDiff;
1671 wfSuppressWarnings();
1672 $haveDiff = $wgDiff && file_exists( $wgDiff );
1673 wfRestoreWarnings();
1674
1675 # This check may also protect against code injection in
1676 # case of broken installations.
1677 if( !$haveDiff ) {
1678 wfDebug( "diff executable not found\n" );
1679 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1680 $format = new UnifiedDiffFormatter();
1681 return $format->format( $diffs );
1682 }
1683
1684 # Make temporary files
1685 $td = wfTempDir();
1686 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1687 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1688
1689 fwrite( $oldtextFile, $before );
1690 fclose( $oldtextFile );
1691 fwrite( $newtextFile, $after );
1692 fclose( $newtextFile );
1693
1694 // Get the diff of the two files
1695 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1696
1697 $h = popen( $cmd, 'r' );
1698
1699 $diff = '';
1700
1701 do {
1702 $data = fread( $h, 8192 );
1703 if ( strlen( $data ) == 0 ) {
1704 break;
1705 }
1706 $diff .= $data;
1707 } while ( true );
1708
1709 // Clean up
1710 pclose( $h );
1711 unlink( $oldtextName );
1712 unlink( $newtextName );
1713
1714 // Kill the --- and +++ lines. They're not useful.
1715 $diff_lines = explode( "\n", $diff );
1716 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1717 unset( $diff_lines[0] );
1718 }
1719 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1720 unset( $diff_lines[1] );
1721 }
1722
1723 $diff = implode( "\n", $diff_lines );
1724
1725 return $diff;
1726 }
1727
1728 /**
1729 * A wrapper around the PHP function var_export().
1730 * Either print it or add it to the regular output ($wgOut).
1731 *
1732 * @param $var A PHP variable to dump.
1733 */
1734 function wfVarDump( $var ) {
1735 global $wgOut;
1736 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1737 if ( headers_sent() || !@is_object( $wgOut ) ) {
1738 print $s;
1739 } else {
1740 $wgOut->addHTML( $s );
1741 }
1742 }
1743
1744 /**
1745 * Provide a simple HTTP error.
1746 *
1747 * @param $code Int|String
1748 * @param $label String
1749 * @param $desc String
1750 */
1751 function wfHttpError( $code, $label, $desc ) {
1752 global $wgOut;
1753 $wgOut->disable();
1754 header( "HTTP/1.0 $code $label" );
1755 header( "Status: $code $label" );
1756 $wgOut->sendCacheControl();
1757
1758 header( 'Content-type: text/html; charset=utf-8' );
1759 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1760 '<html><head><title>' .
1761 htmlspecialchars( $label ) .
1762 '</title></head><body><h1>' .
1763 htmlspecialchars( $label ) .
1764 '</h1><p>' .
1765 nl2br( htmlspecialchars( $desc ) ) .
1766 "</p></body></html>\n";
1767 }
1768
1769 /**
1770 * Clear away any user-level output buffers, discarding contents.
1771 *
1772 * Suitable for 'starting afresh', for instance when streaming
1773 * relatively large amounts of data without buffering, or wanting to
1774 * output image files without ob_gzhandler's compression.
1775 *
1776 * The optional $resetGzipEncoding parameter controls suppression of
1777 * the Content-Encoding header sent by ob_gzhandler; by default it
1778 * is left. See comments for wfClearOutputBuffers() for why it would
1779 * be used.
1780 *
1781 * Note that some PHP configuration options may add output buffer
1782 * layers which cannot be removed; these are left in place.
1783 *
1784 * @param $resetGzipEncoding Bool
1785 */
1786 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1787 if( $resetGzipEncoding ) {
1788 // Suppress Content-Encoding and Content-Length
1789 // headers from 1.10+s wfOutputHandler
1790 global $wgDisableOutputCompression;
1791 $wgDisableOutputCompression = true;
1792 }
1793 while( $status = ob_get_status() ) {
1794 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1795 // Probably from zlib.output_compression or other
1796 // PHP-internal setting which can't be removed.
1797 //
1798 // Give up, and hope the result doesn't break
1799 // output behavior.
1800 break;
1801 }
1802 if( !ob_end_clean() ) {
1803 // Could not remove output buffer handler; abort now
1804 // to avoid getting in some kind of infinite loop.
1805 break;
1806 }
1807 if( $resetGzipEncoding ) {
1808 if( $status['name'] == 'ob_gzhandler' ) {
1809 // Reset the 'Content-Encoding' field set by this handler
1810 // so we can start fresh.
1811 if ( function_exists( 'header_remove' ) ) {
1812 // Available since PHP 5.3.0
1813 header_remove( 'Content-Encoding' );
1814 } else {
1815 // We need to provide a valid content-coding. See bug 28069
1816 header( 'Content-Encoding: identity' );
1817 }
1818 break;
1819 }
1820 }
1821 }
1822 }
1823
1824 /**
1825 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1826 *
1827 * Clear away output buffers, but keep the Content-Encoding header
1828 * produced by ob_gzhandler, if any.
1829 *
1830 * This should be used for HTTP 304 responses, where you need to
1831 * preserve the Content-Encoding header of the real result, but
1832 * also need to suppress the output of ob_gzhandler to keep to spec
1833 * and avoid breaking Firefox in rare cases where the headers and
1834 * body are broken over two packets.
1835 */
1836 function wfClearOutputBuffers() {
1837 wfResetOutputBuffers( false );
1838 }
1839
1840 /**
1841 * Converts an Accept-* header into an array mapping string values to quality
1842 * factors
1843 *
1844 * @param $accept String
1845 * @param $def String default
1846 * @return Array
1847 */
1848 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1849 # No arg means accept anything (per HTTP spec)
1850 if( !$accept ) {
1851 return array( $def => 1.0 );
1852 }
1853
1854 $prefs = array();
1855
1856 $parts = explode( ',', $accept );
1857
1858 foreach( $parts as $part ) {
1859 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1860 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1861 $match = array();
1862 if( !isset( $qpart ) ) {
1863 $prefs[$value] = 1.0;
1864 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1865 $prefs[$value] = floatval( $match[1] );
1866 }
1867 }
1868
1869 return $prefs;
1870 }
1871
1872 /**
1873 * Checks if a given MIME type matches any of the keys in the given
1874 * array. Basic wildcards are accepted in the array keys.
1875 *
1876 * Returns the matching MIME type (or wildcard) if a match, otherwise
1877 * NULL if no match.
1878 *
1879 * @param $type String
1880 * @param $avail Array
1881 * @return string
1882 * @private
1883 */
1884 function mimeTypeMatch( $type, $avail ) {
1885 if( array_key_exists( $type, $avail ) ) {
1886 return $type;
1887 } else {
1888 $parts = explode( '/', $type );
1889 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1890 return $parts[0] . '/*';
1891 } elseif( array_key_exists( '*/*', $avail ) ) {
1892 return '*/*';
1893 } else {
1894 return null;
1895 }
1896 }
1897 }
1898
1899 /**
1900 * Returns the 'best' match between a client's requested internet media types
1901 * and the server's list of available types. Each list should be an associative
1902 * array of type to preference (preference is a float between 0.0 and 1.0).
1903 * Wildcards in the types are acceptable.
1904 *
1905 * @param $cprefs Array: client's acceptable type list
1906 * @param $sprefs Array: server's offered types
1907 * @return string
1908 *
1909 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
1910 * XXX: generalize to negotiate other stuff
1911 */
1912 function wfNegotiateType( $cprefs, $sprefs ) {
1913 $combine = array();
1914
1915 foreach( array_keys($sprefs) as $type ) {
1916 $parts = explode( '/', $type );
1917 if( $parts[1] != '*' ) {
1918 $ckey = mimeTypeMatch( $type, $cprefs );
1919 if( $ckey ) {
1920 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1921 }
1922 }
1923 }
1924
1925 foreach( array_keys( $cprefs ) as $type ) {
1926 $parts = explode( '/', $type );
1927 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1928 $skey = mimeTypeMatch( $type, $sprefs );
1929 if( $skey ) {
1930 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1931 }
1932 }
1933 }
1934
1935 $bestq = 0;
1936 $besttype = null;
1937
1938 foreach( array_keys( $combine ) as $type ) {
1939 if( $combine[$type] > $bestq ) {
1940 $besttype = $type;
1941 $bestq = $combine[$type];
1942 }
1943 }
1944
1945 return $besttype;
1946 }
1947
1948 /**
1949 * Reference-counted warning suppression
1950 *
1951 * @param $end Bool
1952 */
1953 function wfSuppressWarnings( $end = false ) {
1954 static $suppressCount = 0;
1955 static $originalLevel = false;
1956
1957 if ( $end ) {
1958 if ( $suppressCount ) {
1959 --$suppressCount;
1960 if ( !$suppressCount ) {
1961 error_reporting( $originalLevel );
1962 }
1963 }
1964 } else {
1965 if ( !$suppressCount ) {
1966 // E_DEPRECATED is undefined in PHP 5.2
1967 if( !defined( 'E_DEPRECATED' ) ){
1968 define( 'E_DEPRECATED', 8192 );
1969 }
1970 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED ) );
1971 }
1972 ++$suppressCount;
1973 }
1974 }
1975
1976 /**
1977 * Restore error level to previous value
1978 */
1979 function wfRestoreWarnings() {
1980 wfSuppressWarnings( true );
1981 }
1982
1983 # Autodetect, convert and provide timestamps of various types
1984
1985 /**
1986 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1987 */
1988 define( 'TS_UNIX', 0 );
1989
1990 /**
1991 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1992 */
1993 define( 'TS_MW', 1 );
1994
1995 /**
1996 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1997 */
1998 define( 'TS_DB', 2 );
1999
2000 /**
2001 * RFC 2822 format, for E-mail and HTTP headers
2002 */
2003 define( 'TS_RFC2822', 3 );
2004
2005 /**
2006 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2007 *
2008 * This is used by Special:Export
2009 */
2010 define( 'TS_ISO_8601', 4 );
2011
2012 /**
2013 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2014 *
2015 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2016 * DateTime tag and page 36 for the DateTimeOriginal and
2017 * DateTimeDigitized tags.
2018 */
2019 define( 'TS_EXIF', 5 );
2020
2021 /**
2022 * Oracle format time.
2023 */
2024 define( 'TS_ORACLE', 6 );
2025
2026 /**
2027 * Postgres format time.
2028 */
2029 define( 'TS_POSTGRES', 7 );
2030
2031 /**
2032 * DB2 format time
2033 */
2034 define( 'TS_DB2', 8 );
2035
2036 /**
2037 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2038 */
2039 define( 'TS_ISO_8601_BASIC', 9 );
2040
2041 /**
2042 * Get a timestamp string in one of various formats
2043 *
2044 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
2045 * function will autodetect which format is supplied and act
2046 * accordingly.
2047 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
2048 * @return Mixed: String / false The same date in the format specified in $outputtype or false
2049 */
2050 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
2051 $uts = 0;
2052 $da = array();
2053 $strtime = '';
2054
2055 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
2056 $uts = time();
2057 $strtime = "@$uts";
2058 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2059 # TS_DB
2060 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2061 # TS_EXIF
2062 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
2063 # TS_MW
2064 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
2065 # TS_UNIX
2066 $uts = $ts;
2067 $strtime = "@$ts"; // Undocumented?
2068 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
2069 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
2070 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
2071 str_replace( '+00:00', 'UTC', $ts ) );
2072 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2073 # TS_ISO_8601
2074 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2075 #TS_ISO_8601_BASIC
2076 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2077 # TS_POSTGRES
2078 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2079 # TS_POSTGRES
2080 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2081 # TS_DB2
2082 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
2083 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
2084 '[ \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
2085 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
2086 # The regex is a superset of rfc2822 for readability
2087 $strtime = strtok( $ts, ';' );
2088 } 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 ) ) {
2089 # TS_RFC850
2090 $strtime = $ts;
2091 } 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 ) ) {
2092 # asctime
2093 $strtime = $ts;
2094 } else {
2095 # Bogus value...
2096 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
2097
2098 return false;
2099 }
2100
2101
2102
2103 static $formats = array(
2104 TS_UNIX => 'U',
2105 TS_MW => 'YmdHis',
2106 TS_DB => 'Y-m-d H:i:s',
2107 TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
2108 TS_ISO_8601_BASIC => 'Ymd\THis\Z',
2109 TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2110 TS_RFC2822 => 'D, d M Y H:i:s',
2111 TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2112 TS_POSTGRES => 'Y-m-d H:i:s',
2113 TS_DB2 => 'Y-m-d H:i:s',
2114 );
2115
2116 if ( !isset( $formats[$outputtype] ) ) {
2117 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2118 }
2119
2120 if ( function_exists( "date_create" ) ) {
2121 if ( count( $da ) ) {
2122 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2123 (int)$da[1], (int)$da[2], (int)$da[3],
2124 (int)$da[4], (int)$da[5], (int)$da[6]);
2125
2126 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2127 } elseif ( $strtime ) {
2128 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2129 } else {
2130 return false;
2131 }
2132
2133 if ( !$d ) {
2134 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2135 return false;
2136 }
2137
2138 $output = $d->format( $formats[$outputtype] );
2139 } else {
2140 if ( count( $da ) ) {
2141 // Warning! gmmktime() acts oddly if the month or day is set to 0
2142 // We may want to handle that explicitly at some point
2143 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2144 (int)$da[2], (int)$da[3], (int)$da[1] );
2145 } elseif ( $strtime ) {
2146 $uts = strtotime( $strtime );
2147 }
2148
2149 if ( $uts === false ) {
2150 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2151 return false;
2152 }
2153
2154 if ( TS_UNIX == $outputtype ) {
2155 return $uts;
2156 }
2157 $output = gmdate( $formats[$outputtype], $uts );
2158 }
2159
2160 if ( ( $outputtype == TS_RFC2822 ) || ( $outputtype == TS_POSTGRES ) ) {
2161 $output .= ' GMT';
2162 }
2163
2164 return $output;
2165 }
2166
2167 /**
2168 * Return a formatted timestamp, or null if input is null.
2169 * For dealing with nullable timestamp columns in the database.
2170 *
2171 * @param $outputtype Integer
2172 * @param $ts String
2173 * @return String
2174 */
2175 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2176 if( is_null( $ts ) ) {
2177 return null;
2178 } else {
2179 return wfTimestamp( $outputtype, $ts );
2180 }
2181 }
2182
2183 /**
2184 * Convenience function; returns MediaWiki timestamp for the present time.
2185 *
2186 * @return string
2187 */
2188 function wfTimestampNow() {
2189 # return NOW
2190 return wfTimestamp( TS_MW, time() );
2191 }
2192
2193 /**
2194 * Check if the operating system is Windows
2195 *
2196 * @return Bool: true if it's Windows, False otherwise.
2197 */
2198 function wfIsWindows() {
2199 static $isWindows = null;
2200 if ( $isWindows === null ) {
2201 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2202 }
2203 return $isWindows;
2204 }
2205
2206 /**
2207 * Check if we are running under HipHop
2208 *
2209 * @return Bool
2210 */
2211 function wfIsHipHop() {
2212 return function_exists( 'hphp_thread_set_warmup_enabled' );
2213 }
2214
2215 /**
2216 * Swap two variables
2217 *
2218 * @param $x Mixed
2219 * @param $y Mixed
2220 */
2221 function swap( &$x, &$y ) {
2222 $z = $x;
2223 $x = $y;
2224 $y = $z;
2225 }
2226
2227 /**
2228 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2229 * TEMP environment variables are then checked in sequence, and if none are set
2230 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2231 * or C:\Windows\Temp for Windows and hope for the best.
2232 * It is common to call it with tempnam().
2233 *
2234 * NOTE: When possible, use instead the tmpfile() function to create
2235 * temporary files to avoid race conditions on file creation, etc.
2236 *
2237 * @return String
2238 */
2239 function wfTempDir() {
2240 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2241 $tmp = getenv( $var );
2242 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2243 return $tmp;
2244 }
2245 }
2246 if( function_exists( 'sys_get_temp_dir' ) ) {
2247 return sys_get_temp_dir();
2248 }
2249 # Usual defaults
2250 return wfIsWindows() ? 'C:\Windows\Temp' : '/tmp';
2251 }
2252
2253 /**
2254 * Make directory, and make all parent directories if they don't exist
2255 *
2256 * @param $dir String: full path to directory to create
2257 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2258 * @param $caller String: optional caller param for debugging.
2259 * @return bool
2260 */
2261 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2262 global $wgDirectoryMode;
2263
2264 if ( !is_null( $caller ) ) {
2265 wfDebug( "$caller: called wfMkdirParents($dir)" );
2266 }
2267
2268 if( strval( $dir ) === '' || file_exists( $dir ) ) {
2269 return true;
2270 }
2271
2272 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2273
2274 if ( is_null( $mode ) ) {
2275 $mode = $wgDirectoryMode;
2276 }
2277
2278 // Turn off the normal warning, we're doing our own below
2279 wfSuppressWarnings();
2280 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2281 wfRestoreWarnings();
2282
2283 if( !$ok ) {
2284 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2285 trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
2286 }
2287 return $ok;
2288 }
2289
2290 /**
2291 * Increment a statistics counter
2292 *
2293 * @param $key String
2294 * @param $count Int
2295 */
2296 function wfIncrStats( $key, $count = 1 ) {
2297 global $wgStatsMethod;
2298
2299 $count = intval( $count );
2300
2301 if( $wgStatsMethod == 'udp' ) {
2302 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname, $wgAggregateStatsID;
2303 static $socket;
2304
2305 $id = $wgAggregateStatsID !== false ? $wgAggregateStatsID : $wgDBname;
2306
2307 if ( !$socket ) {
2308 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
2309 $statline = "stats/{$id} - {$count} 1 1 1 1 -total\n";
2310 socket_sendto(
2311 $socket,
2312 $statline,
2313 strlen( $statline ),
2314 0,
2315 $wgUDPProfilerHost,
2316 $wgUDPProfilerPort
2317 );
2318 }
2319 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n";
2320 wfSuppressWarnings();
2321 socket_sendto(
2322 $socket,
2323 $statline,
2324 strlen( $statline ),
2325 0,
2326 $wgUDPProfilerHost,
2327 $wgUDPProfilerPort
2328 );
2329 wfRestoreWarnings();
2330 } elseif( $wgStatsMethod == 'cache' ) {
2331 global $wgMemc;
2332 $key = wfMemcKey( 'stats', $key );
2333 if ( is_null( $wgMemc->incr( $key, $count ) ) ) {
2334 $wgMemc->add( $key, $count );
2335 }
2336 } else {
2337 // Disabled
2338 }
2339 }
2340
2341 /**
2342 * @param $nr Mixed: the number to format
2343 * @param $acc Integer: the number of digits after the decimal point, default 2
2344 * @param $round Boolean: whether or not to round the value, default true
2345 * @return float
2346 */
2347 function wfPercent( $nr, $acc = 2, $round = true ) {
2348 $ret = sprintf( "%.${acc}f", $nr );
2349 return $round ? round( $ret, $acc ) . '%' : "$ret%";
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, warnings in 1.19, removal in 1.20
2914 */
2915 function wfCreateObject( $name, $p ) {
2916 wfDeprecated( __FUNCTION__ );
2917 return MWFunction::newObj( $name, $p );
2918 }
2919
2920 function wfHttpOnlySafe() {
2921 global $wgHttpOnlyBlacklist;
2922
2923 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2924 foreach( $wgHttpOnlyBlacklist as $regex ) {
2925 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2926 return false;
2927 }
2928 }
2929 }
2930
2931 return true;
2932 }
2933
2934 /**
2935 * Initialise php session
2936 *
2937 * @param $sessionId Bool
2938 */
2939 function wfSetupSession( $sessionId = false ) {
2940 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2941 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2942 if( $wgSessionsInMemcached ) {
2943 if ( !defined( 'MW_COMPILED' ) ) {
2944 global $IP;
2945 require_once( "$IP/includes/cache/MemcachedSessions.php" );
2946 }
2947 session_set_save_handler( 'memsess_open', 'memsess_close', 'memsess_read',
2948 'memsess_write', 'memsess_destroy', 'memsess_gc' );
2949
2950 // It's necessary to register a shutdown function to call session_write_close(),
2951 // because by the time the request shutdown function for the session module is
2952 // called, $wgMemc has already been destroyed. Shutdown functions registered
2953 // this way are called before object destruction.
2954 register_shutdown_function( 'memsess_write_close' );
2955 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2956 # Only set this if $wgSessionHandler isn't null and session.save_handler
2957 # hasn't already been set to the desired value (that causes errors)
2958 ini_set( 'session.save_handler', $wgSessionHandler );
2959 }
2960 $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
2961 wfDebugLog( 'cookie',
2962 'session_set_cookie_params: "' . implode( '", "',
2963 array(
2964 0,
2965 $wgCookiePath,
2966 $wgCookieDomain,
2967 $wgCookieSecure,
2968 $httpOnlySafe ) ) . '"' );
2969 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
2970 session_cache_limiter( 'private, must-revalidate' );
2971 if ( $sessionId ) {
2972 session_id( $sessionId );
2973 }
2974 wfSuppressWarnings();
2975 session_start();
2976 wfRestoreWarnings();
2977 }
2978
2979 /**
2980 * Get an object from the precompiled serialized directory
2981 *
2982 * @param $name String
2983 * @return Mixed: the variable on success, false on failure
2984 */
2985 function wfGetPrecompiledData( $name ) {
2986 global $IP;
2987
2988 $file = "$IP/serialized/$name";
2989 if ( file_exists( $file ) ) {
2990 $blob = file_get_contents( $file );
2991 if ( $blob ) {
2992 return unserialize( $blob );
2993 }
2994 }
2995 return false;
2996 }
2997
2998 /**
2999 * Get the name of the function which called this function
3000 *
3001 * @param $level Int
3002 * @return Bool|string
3003 */
3004 function wfGetCaller( $level = 2 ) {
3005 $backtrace = wfDebugBacktrace();
3006 if ( isset( $backtrace[$level] ) ) {
3007 return wfFormatStackFrame( $backtrace[$level] );
3008 } else {
3009 $caller = 'unknown';
3010 }
3011 return $caller;
3012 }
3013
3014 /**
3015 * Return a string consisting of callers in the stack. Useful sometimes
3016 * for profiling specific points.
3017 *
3018 * @param $limit The maximum depth of the stack frame to return, or false for
3019 * the entire stack.
3020 * @return String
3021 */
3022 function wfGetAllCallers( $limit = 3 ) {
3023 $trace = array_reverse( wfDebugBacktrace() );
3024 if ( !$limit || $limit > count( $trace ) - 1 ) {
3025 $limit = count( $trace ) - 1;
3026 }
3027 $trace = array_slice( $trace, -$limit - 1, $limit );
3028 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
3029 }
3030
3031 /**
3032 * Return a string representation of frame
3033 *
3034 * @param $frame Array
3035 * @return Bool
3036 */
3037 function wfFormatStackFrame( $frame ) {
3038 return isset( $frame['class'] ) ?
3039 $frame['class'] . '::' . $frame['function'] :
3040 $frame['function'];
3041 }
3042
3043 /**
3044 * Get a cache key
3045 *
3046 * @param varargs
3047 * @return String
3048 */
3049 function wfMemcKey( /*... */ ) {
3050 $args = func_get_args();
3051 $key = wfWikiID() . ':' . implode( ':', $args );
3052 $key = str_replace( ' ', '_', $key );
3053 return $key;
3054 }
3055
3056 /**
3057 * Get a cache key for a foreign DB
3058 *
3059 * @param $db String
3060 * @param $prefix String
3061 * @param varargs String
3062 * @return String
3063 */
3064 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3065 $args = array_slice( func_get_args(), 2 );
3066 if ( $prefix ) {
3067 $key = "$db-$prefix:" . implode( ':', $args );
3068 } else {
3069 $key = $db . ':' . implode( ':', $args );
3070 }
3071 return $key;
3072 }
3073
3074 /**
3075 * Get an ASCII string identifying this wiki
3076 * This is used as a prefix in memcached keys
3077 *
3078 * @return String
3079 */
3080 function wfWikiID() {
3081 global $wgDBprefix, $wgDBname;
3082 if ( $wgDBprefix ) {
3083 return "$wgDBname-$wgDBprefix";
3084 } else {
3085 return $wgDBname;
3086 }
3087 }
3088
3089 /**
3090 * Split a wiki ID into DB name and table prefix
3091 *
3092 * @param $wiki String
3093 * @param $bits String
3094 */
3095 function wfSplitWikiID( $wiki ) {
3096 $bits = explode( '-', $wiki, 2 );
3097 if ( count( $bits ) < 2 ) {
3098 $bits[] = '';
3099 }
3100 return $bits;
3101 }
3102
3103 /**
3104 * Get a Database object.
3105 *
3106 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3107 * master (for write queries), DB_SLAVE for potentially lagged read
3108 * queries, or an integer >= 0 for a particular server.
3109 *
3110 * @param $groups Mixed: query groups. An array of group names that this query
3111 * belongs to. May contain a single string if the query is only
3112 * in one group.
3113 *
3114 * @param $wiki String: the wiki ID, or false for the current wiki
3115 *
3116 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3117 * will always return the same object, unless the underlying connection or load
3118 * balancer is manually destroyed.
3119 *
3120 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3121 * updater to ensure that a proper database is being updated.
3122 *
3123 * @return DatabaseBase
3124 */
3125 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3126 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3127 }
3128
3129 /**
3130 * Get a load balancer object.
3131 *
3132 * @param $wiki String: wiki ID, or false for the current wiki
3133 * @return LoadBalancer
3134 */
3135 function wfGetLB( $wiki = false ) {
3136 return wfGetLBFactory()->getMainLB( $wiki );
3137 }
3138
3139 /**
3140 * Get the load balancer factory object
3141 *
3142 * @return LBFactory
3143 */
3144 function &wfGetLBFactory() {
3145 return LBFactory::singleton();
3146 }
3147
3148 /**
3149 * Find a file.
3150 * Shortcut for RepoGroup::singleton()->findFile()
3151 *
3152 * @param $title String or Title object
3153 * @param $options Associative array of options:
3154 * time: requested time for an archived image, or false for the
3155 * current version. An image object will be returned which was
3156 * created at the specified time.
3157 *
3158 * ignoreRedirect: If true, do not follow file redirects
3159 *
3160 * private: If true, return restricted (deleted) files if the current
3161 * user is allowed to view them. Otherwise, such files will not
3162 * be found.
3163 *
3164 * bypassCache: If true, do not use the process-local cache of File objects
3165 *
3166 * @return File, or false if the file does not exist
3167 */
3168 function wfFindFile( $title, $options = array() ) {
3169 return RepoGroup::singleton()->findFile( $title, $options );
3170 }
3171
3172 /**
3173 * Get an object referring to a locally registered file.
3174 * Returns a valid placeholder object if the file does not exist.
3175 *
3176 * @param $title Title or String
3177 * @return File, or null if passed an invalid Title
3178 */
3179 function wfLocalFile( $title ) {
3180 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3181 }
3182
3183 /**
3184 * Should low-performance queries be disabled?
3185 *
3186 * @return Boolean
3187 * @codeCoverageIgnore
3188 */
3189 function wfQueriesMustScale() {
3190 global $wgMiserMode;
3191 return $wgMiserMode
3192 || ( SiteStats::pages() > 100000
3193 && SiteStats::edits() > 1000000
3194 && SiteStats::users() > 10000 );
3195 }
3196
3197 /**
3198 * Get the path to a specified script file, respecting file
3199 * extensions; this is a wrapper around $wgScriptExtension etc.
3200 *
3201 * @param $script String: script filename, sans extension
3202 * @return String
3203 */
3204 function wfScript( $script = 'index' ) {
3205 global $wgScriptPath, $wgScriptExtension;
3206 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3207 }
3208
3209 /**
3210 * Get the script URL.
3211 *
3212 * @return script URL
3213 */
3214 function wfGetScriptUrl() {
3215 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3216 #
3217 # as it was called, minus the query string.
3218 #
3219 # Some sites use Apache rewrite rules to handle subdomains,
3220 # and have PHP set up in a weird way that causes PHP_SELF
3221 # to contain the rewritten URL instead of the one that the
3222 # outside world sees.
3223 #
3224 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3225 # provides containing the "before" URL.
3226 return $_SERVER['SCRIPT_NAME'];
3227 } else {
3228 return $_SERVER['URL'];
3229 }
3230 }
3231
3232 /**
3233 * Convenience function converts boolean values into "true"
3234 * or "false" (string) values
3235 *
3236 * @param $value Boolean
3237 * @return String
3238 */
3239 function wfBoolToStr( $value ) {
3240 return $value ? 'true' : 'false';
3241 }
3242
3243 /**
3244 * Load an extension messages file
3245 *
3246 * @deprecated since 1.16, warnings in 1.18, remove in 1.20
3247 * @codeCoverageIgnore
3248 */
3249 function wfLoadExtensionMessages() {
3250 wfDeprecated( __FUNCTION__ );
3251 }
3252
3253 /**
3254 * Get a platform-independent path to the null file, e.g. /dev/null
3255 *
3256 * @return string
3257 */
3258 function wfGetNull() {
3259 return wfIsWindows()
3260 ? 'NUL'
3261 : '/dev/null';
3262 }
3263
3264 /**
3265 * Throws a warning that $function is deprecated
3266 *
3267 * @param $function String
3268 * @return null
3269 */
3270 function wfDeprecated( $function ) {
3271 static $functionsWarned = array();
3272 if ( !isset( $functionsWarned[$function] ) ) {
3273 $functionsWarned[$function] = true;
3274 wfWarn( "Use of $function is deprecated.", 2 );
3275 }
3276 }
3277
3278 /**
3279 * Send a warning either to the debug log or in a PHP error depending on
3280 * $wgDevelopmentWarnings
3281 *
3282 * @param $msg String: message to send
3283 * @param $callerOffset Integer: number of items to go back in the backtrace to
3284 * find the correct caller (1 = function calling wfWarn, ...)
3285 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3286 * is true
3287 */
3288 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
3289 global $wgDevelopmentWarnings;
3290
3291 $callers = wfDebugBacktrace();
3292 if ( isset( $callers[$callerOffset + 1] ) ) {
3293 $callerfunc = $callers[$callerOffset + 1];
3294 $callerfile = $callers[$callerOffset];
3295 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3296 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3297 } else {
3298 $file = '(internal function)';
3299 }
3300 $func = '';
3301 if ( isset( $callerfunc['class'] ) ) {
3302 $func .= $callerfunc['class'] . '::';
3303 }
3304 if ( isset( $callerfunc['function'] ) ) {
3305 $func .= $callerfunc['function'];
3306 }
3307 $msg .= " [Called from $func in $file]";
3308 }
3309
3310 if ( $wgDevelopmentWarnings ) {
3311 trigger_error( $msg, $level );
3312 } else {
3313 wfDebug( "$msg\n" );
3314 }
3315 }
3316
3317 /**
3318 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3319 * and waiting for it to go down, this waits for the slaves to catch up to the
3320 * master position. Use this when updating very large numbers of rows, as
3321 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3322 * a no-op if there are no slaves.
3323 *
3324 * @param $maxLag Integer (deprecated)
3325 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3326 * @return null
3327 */
3328 function wfWaitForSlaves( $maxLag = false, $wiki = false ) {
3329 $lb = wfGetLB( $wiki );
3330 // bug 27975 - Don't try to wait for slaves if there are none
3331 // Prevents permission error when getting master position
3332 if ( $lb->getServerCount() > 1 ) {
3333 $dbw = $lb->getConnection( DB_MASTER );
3334 $pos = $dbw->getMasterPos();
3335 $lb->waitForAll( $pos );
3336 }
3337 }
3338
3339 /**
3340 * Used to be used for outputting text in the installer/updater
3341 * @deprecated since 1.18, warnings in 1.19, remove in 1.20
3342 */
3343 function wfOut( $s ) {
3344 wfDeprecated( __METHOD__ );
3345 global $wgCommandLineMode;
3346 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3347 echo $s;
3348 } else {
3349 echo htmlspecialchars( $s );
3350 }
3351 flush();
3352 }
3353
3354 /**
3355 * Count down from $n to zero on the terminal, with a one-second pause
3356 * between showing each number. For use in command-line scripts.
3357 * @codeCoverageIgnore
3358 */
3359 function wfCountDown( $n ) {
3360 for ( $i = $n; $i >= 0; $i-- ) {
3361 if ( $i != $n ) {
3362 echo str_repeat( "\x08", strlen( $i + 1 ) );
3363 }
3364 echo $i;
3365 flush();
3366 if ( $i ) {
3367 sleep( 1 );
3368 }
3369 }
3370 echo "\n";
3371 }
3372
3373 /**
3374 * Generate a random 32-character hexadecimal token.
3375 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3376 * characters before hashing.
3377 * @return string
3378 * @codeCoverageIgnore
3379 */
3380 function wfGenerateToken( $salt = '' ) {
3381 $salt = serialize( $salt );
3382 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3383 }
3384
3385 /**
3386 * Replace all invalid characters with -
3387 *
3388 * @param $name Mixed: filename to process
3389 * @return String
3390 */
3391 function wfStripIllegalFilenameChars( $name ) {
3392 global $wgIllegalFileChars;
3393 $name = wfBaseName( $name );
3394 $name = preg_replace(
3395 "/[^" . Title::legalChars() . "]" .
3396 ( $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '' ) .
3397 "/",
3398 '-',
3399 $name
3400 );
3401 return $name;
3402 }
3403
3404 /**
3405 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3406 *
3407 * @return Integer value memory was set to.
3408 */
3409 function wfMemoryLimit() {
3410 global $wgMemoryLimit;
3411 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3412 if( $memlimit != -1 ) {
3413 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3414 if( $conflimit == -1 ) {
3415 wfDebug( "Removing PHP's memory limit\n" );
3416 wfSuppressWarnings();
3417 ini_set( 'memory_limit', $conflimit );
3418 wfRestoreWarnings();
3419 return $conflimit;
3420 } elseif ( $conflimit > $memlimit ) {
3421 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3422 wfSuppressWarnings();
3423 ini_set( 'memory_limit', $conflimit );
3424 wfRestoreWarnings();
3425 return $conflimit;
3426 }
3427 }
3428 return $memlimit;
3429 }
3430
3431 /**
3432 * Converts shorthand byte notation to integer form
3433 *
3434 * @param $string String
3435 * @return Integer
3436 */
3437 function wfShorthandToInteger( $string = '' ) {
3438 $string = trim( $string );
3439 if( $string === '' ) {
3440 return -1;
3441 }
3442 $last = $string[strlen( $string ) - 1];
3443 $val = intval( $string );
3444 switch( $last ) {
3445 case 'g':
3446 case 'G':
3447 $val *= 1024;
3448 // break intentionally missing
3449 case 'm':
3450 case 'M':
3451 $val *= 1024;
3452 // break intentionally missing
3453 case 'k':
3454 case 'K':
3455 $val *= 1024;
3456 }
3457
3458 return $val;
3459 }
3460
3461 /**
3462 * Get the normalised IETF language tag
3463 * See unit test for examples.
3464 *
3465 * @param $code String: The language code.
3466 * @return $langCode String: The language code which complying with BCP 47 standards.
3467 */
3468 function wfBCP47( $code ) {
3469 $codeSegment = explode( '-', $code );
3470 $codeBCP = array();
3471 foreach ( $codeSegment as $segNo => $seg ) {
3472 if ( count( $codeSegment ) > 0 ) {
3473 // when previous segment is x, it is a private segment and should be lc
3474 if( $segNo > 0 && strtolower( $codeSegment[($segNo - 1)] ) == 'x') {
3475 $codeBCP[$segNo] = strtolower( $seg );
3476 // ISO 3166 country code
3477 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3478 $codeBCP[$segNo] = strtoupper( $seg );
3479 // ISO 15924 script code
3480 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3481 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3482 // Use lowercase for other cases
3483 } else {
3484 $codeBCP[$segNo] = strtolower( $seg );
3485 }
3486 } else {
3487 // Use lowercase for single segment
3488 $codeBCP[$segNo] = strtolower( $seg );
3489 }
3490 }
3491 $langCode = implode( '-', $codeBCP );
3492 return $langCode;
3493 }
3494
3495 /**
3496 * Get a cache object.
3497 *
3498 * @param integer $inputType Cache type, one the the CACHE_* constants.
3499 * @return BagOStuff
3500 */
3501 function wfGetCache( $inputType ) {
3502 return ObjectCache::getInstance( $inputType );
3503 }
3504
3505 /**
3506 * Get the main cache object
3507 *
3508 * @return BagOStuff
3509 */
3510 function wfGetMainCache() {
3511 global $wgMainCacheType;
3512 return ObjectCache::getInstance( $wgMainCacheType );
3513 }
3514
3515 /**
3516 * Get the cache object used by the message cache
3517 *
3518 * @return BagOStuff
3519 */
3520 function wfGetMessageCacheStorage() {
3521 global $wgMessageCacheType;
3522 return ObjectCache::getInstance( $wgMessageCacheType );
3523 }
3524
3525 /**
3526 * Get the cache object used by the parser cache
3527 *
3528 * @return BagOStuff
3529 */
3530 function wfGetParserCacheStorage() {
3531 global $wgParserCacheType;
3532 return ObjectCache::getInstance( $wgParserCacheType );
3533 }
3534