Moved wfGetCaller(), wfGetAllCallers() and wfFormatStackFrame() near other related...
[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 * Get the name of the function which called this function
1169 *
1170 * @param $level Int
1171 * @return Bool|string
1172 */
1173 function wfGetCaller( $level = 2 ) {
1174 $backtrace = wfDebugBacktrace();
1175 if ( isset( $backtrace[$level] ) ) {
1176 return wfFormatStackFrame( $backtrace[$level] );
1177 } else {
1178 $caller = 'unknown';
1179 }
1180 return $caller;
1181 }
1182
1183 /**
1184 * Return a string consisting of callers in the stack. Useful sometimes
1185 * for profiling specific points.
1186 *
1187 * @param $limit The maximum depth of the stack frame to return, or false for
1188 * the entire stack.
1189 * @return String
1190 */
1191 function wfGetAllCallers( $limit = 3 ) {
1192 $trace = array_reverse( wfDebugBacktrace() );
1193 if ( !$limit || $limit > count( $trace ) - 1 ) {
1194 $limit = count( $trace ) - 1;
1195 }
1196 $trace = array_slice( $trace, -$limit - 1, $limit );
1197 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1198 }
1199
1200 /**
1201 * Return a string representation of frame
1202 *
1203 * @param $frame Array
1204 * @return Bool
1205 */
1206 function wfFormatStackFrame( $frame ) {
1207 return isset( $frame['class'] ) ?
1208 $frame['class'] . '::' . $frame['function'] :
1209 $frame['function'];
1210 }
1211
1212
1213 /* Some generic result counters, pulled out of SearchEngine */
1214
1215
1216 /**
1217 * @todo document
1218 *
1219 * @param $offset Int
1220 * @param $limit Int
1221 * @return String
1222 */
1223 function wfShowingResults( $offset, $limit ) {
1224 global $wgLang;
1225 return wfMsgExt(
1226 'showingresults',
1227 array( 'parseinline' ),
1228 $wgLang->formatNum( $limit ),
1229 $wgLang->formatNum( $offset + 1 )
1230 );
1231 }
1232
1233 /**
1234 * @todo document
1235 *
1236 * @param $offset Int
1237 * @param $limit Int
1238 * @param $num Int
1239 * @return String
1240 */
1241 function wfShowingResultsNum( $offset, $limit, $num ) {
1242 global $wgLang;
1243 return wfMsgExt(
1244 'showingresultsnum',
1245 array( 'parseinline' ),
1246 $wgLang->formatNum( $limit ),
1247 $wgLang->formatNum( $offset + 1 ),
1248 $wgLang->formatNum( $num )
1249 );
1250 }
1251
1252 /**
1253 * Generate (prev x| next x) (20|50|100...) type links for paging
1254 *
1255 * @param $offset String
1256 * @param $limit Integer
1257 * @param $link String
1258 * @param $query String: optional URL query parameter string
1259 * @param $atend Bool: optional param for specified if this is the last page
1260 * @return String
1261 */
1262 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1263 global $wgLang;
1264 $fmtLimit = $wgLang->formatNum( $limit );
1265 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
1266 # Get prev/next link display text
1267 $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
1268 $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
1269 # Get prev/next link title text
1270 $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1271 $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
1272 # Fetch the title object
1273 if( is_object( $link ) ) {
1274 $title =& $link;
1275 } else {
1276 $title = Title::newFromText( $link );
1277 if( is_null( $title ) ) {
1278 return false;
1279 }
1280 }
1281 # Make 'previous' link
1282 if( 0 != $offset ) {
1283 $po = $offset - $limit;
1284 $po = max( $po, 0 );
1285 $q = "limit={$limit}&offset={$po}";
1286 if( $query != '' ) {
1287 $q .= '&' . $query;
1288 }
1289 $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
1290 } else {
1291 $plink = $prev;
1292 }
1293 # Make 'next' link
1294 $no = $offset + $limit;
1295 $q = "limit={$limit}&offset={$no}";
1296 if( $query != '' ) {
1297 $q .= '&' . $query;
1298 }
1299 if( $atend ) {
1300 $nlink = $next;
1301 } else {
1302 $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
1303 }
1304 # Make links to set number of items per page
1305 $nums = $wgLang->pipeList( array(
1306 wfNumLink( $offset, 20, $title, $query ),
1307 wfNumLink( $offset, 50, $title, $query ),
1308 wfNumLink( $offset, 100, $title, $query ),
1309 wfNumLink( $offset, 250, $title, $query ),
1310 wfNumLink( $offset, 500, $title, $query )
1311 ) );
1312 return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
1313 }
1314
1315 /**
1316 * Generate links for (20|50|100...) items-per-page links
1317 *
1318 * @param $offset String
1319 * @param $limit Integer
1320 * @param $title Title
1321 * @param $query String: optional URL query parameter string
1322 */
1323 function wfNumLink( $offset, $limit, $title, $query = '' ) {
1324 global $wgLang;
1325 if( $query == '' ) {
1326 $q = '';
1327 } else {
1328 $q = $query.'&';
1329 }
1330 $q .= "limit={$limit}&offset={$offset}";
1331 $fmtLimit = $wgLang->formatNum( $limit );
1332 $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
1333 $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
1334 return $s;
1335 }
1336
1337 /**
1338 * @todo document
1339 * @todo FIXME: We may want to blacklist some broken browsers
1340 *
1341 * @param $force Bool
1342 * @return bool Whereas client accept gzip compression
1343 */
1344 function wfClientAcceptsGzip( $force = false ) {
1345 static $result = null;
1346 if ( $result === null || $force ) {
1347 $result = false;
1348 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1349 # @todo FIXME: We may want to blacklist some broken browsers
1350 $m = array();
1351 if( preg_match(
1352 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1353 $_SERVER['HTTP_ACCEPT_ENCODING'],
1354 $m )
1355 )
1356 {
1357 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1358 $result = false;
1359 return $result;
1360 }
1361 wfDebug( " accepts gzip\n" );
1362 $result = true;
1363 }
1364 }
1365 }
1366 return $result;
1367 }
1368
1369 /**
1370 * Obtain the offset and limit values from the request string;
1371 * used in special pages
1372 *
1373 * @param $deflimit Int default limit if none supplied
1374 * @param $optionname String Name of a user preference to check against
1375 * @return array
1376 *
1377 */
1378 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1379 global $wgRequest;
1380 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1381 }
1382
1383 /**
1384 * Escapes the given text so that it may be output using addWikiText()
1385 * without any linking, formatting, etc. making its way through. This
1386 * is achieved by substituting certain characters with HTML entities.
1387 * As required by the callers, <nowiki> is not used.
1388 *
1389 * @param $text String: text to be escaped
1390 * @return String
1391 */
1392 function wfEscapeWikiText( $text ) {
1393 $text = strtr( "\n$text", array(
1394 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1395 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1396 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1397 "\n#" => "\n&#35;", "\n*" => "\n&#42;",
1398 "\n:" => "\n&#58;", "\n;" => "\n&#59;",
1399 '://' => '&#58;//', 'ISBN ' => 'ISBN&#32;', 'RFC ' => 'RFC&#32;',
1400 ) );
1401 return substr( $text, 1 );
1402 }
1403
1404 /**
1405 * Get the current unix timetstamp with microseconds. Useful for profiling
1406 * @return Float
1407 */
1408 function wfTime() {
1409 return microtime( true );
1410 }
1411
1412 /**
1413 * Sets dest to source and returns the original value of dest
1414 * If source is NULL, it just returns the value, it doesn't set the variable
1415 * If force is true, it will set the value even if source is NULL
1416 *
1417 * @param $dest Mixed
1418 * @param $source Mixed
1419 * @param $force Bool
1420 * @return Mixed
1421 */
1422 function wfSetVar( &$dest, $source, $force = false ) {
1423 $temp = $dest;
1424 if ( !is_null( $source ) || $force ) {
1425 $dest = $source;
1426 }
1427 return $temp;
1428 }
1429
1430 /**
1431 * As for wfSetVar except setting a bit
1432 *
1433 * @param $dest Int
1434 * @param $bit Int
1435 * @param $state Bool
1436 */
1437 function wfSetBit( &$dest, $bit, $state = true ) {
1438 $temp = (bool)( $dest & $bit );
1439 if ( !is_null( $state ) ) {
1440 if ( $state ) {
1441 $dest |= $bit;
1442 } else {
1443 $dest &= ~$bit;
1444 }
1445 }
1446 return $temp;
1447 }
1448
1449 /**
1450 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1451 * "days=7&limit=100". Options in the first array override options in the second.
1452 * Options set to "" will not be output.
1453 *
1454 * @param $array1 Array( String|Array )
1455 * @param $array2 Array( String|Array )
1456 * @return String
1457 */
1458 function wfArrayToCGI( $array1, $array2 = null ) {
1459 if ( !is_null( $array2 ) ) {
1460 $array1 = $array1 + $array2;
1461 }
1462
1463 $cgi = '';
1464 foreach ( $array1 as $key => $value ) {
1465 if ( $value !== '' ) {
1466 if ( $cgi != '' ) {
1467 $cgi .= '&';
1468 }
1469 if ( is_array( $value ) ) {
1470 $firstTime = true;
1471 foreach ( $value as $v ) {
1472 $cgi .= ( $firstTime ? '' : '&') .
1473 urlencode( $key . '[]' ) . '=' .
1474 urlencode( $v );
1475 $firstTime = false;
1476 }
1477 } else {
1478 if ( is_object( $value ) ) {
1479 $value = $value->__toString();
1480 }
1481 $cgi .= urlencode( $key ) . '=' .
1482 urlencode( $value );
1483 }
1484 }
1485 }
1486 return $cgi;
1487 }
1488
1489 /**
1490 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1491 * its argument and returns the same string in array form. This allows compa-
1492 * tibility with legacy functions that accept raw query strings instead of nice
1493 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1494 * valid query strings, or it will explode.
1495 *
1496 * @param $query String: query string
1497 * @return array Array version of input
1498 */
1499 function wfCgiToArray( $query ) {
1500 if( isset( $query[0] ) && $query[0] == '?' ) {
1501 $query = substr( $query, 1 );
1502 }
1503 $bits = explode( '&', $query );
1504 $ret = array();
1505 foreach( $bits as $bit ) {
1506 if( $bit === '' ) {
1507 continue;
1508 }
1509 list( $key, $value ) = explode( '=', $bit );
1510 $key = urldecode( $key );
1511 $value = urldecode( $value );
1512 $ret[$key] = $value;
1513 }
1514 return $ret;
1515 }
1516
1517 /**
1518 * Append a query string to an existing URL, which may or may not already
1519 * have query string parameters already. If so, they will be combined.
1520 *
1521 * @param $url String
1522 * @param $query Mixed: string or associative array
1523 * @return string
1524 */
1525 function wfAppendQuery( $url, $query ) {
1526 if ( is_array( $query ) ) {
1527 $query = wfArrayToCGI( $query );
1528 }
1529 if( $query != '' ) {
1530 if( false === strpos( $url, '?' ) ) {
1531 $url .= '?';
1532 } else {
1533 $url .= '&';
1534 }
1535 $url .= $query;
1536 }
1537 return $url;
1538 }
1539
1540 /**
1541 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
1542 * and $wgProto are correct.
1543 *
1544 * @todo this won't work with current-path-relative URLs
1545 * like "subdir/foo.html", etc.
1546 *
1547 * @param $url String: either fully-qualified or a local path + query
1548 * @return string Fully-qualified URL
1549 */
1550 function wfExpandUrl( $url ) {
1551 if( substr( $url, 0, 2 ) == '//' ) {
1552 global $wgProto;
1553 return $wgProto . ':' . $url;
1554 } elseif( substr( $url, 0, 1 ) == '/' ) {
1555 global $wgServer;
1556 return $wgServer . $url;
1557 } else {
1558 return $url;
1559 }
1560 }
1561
1562 /**
1563 * Windows-compatible version of escapeshellarg()
1564 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1565 * function puts single quotes in regardless of OS.
1566 *
1567 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1568 * earlier distro releases of PHP)
1569 *
1570 * @param varargs
1571 * @return String
1572 */
1573 function wfEscapeShellArg( ) {
1574 wfInitShellLocale();
1575
1576 $args = func_get_args();
1577 $first = true;
1578 $retVal = '';
1579 foreach ( $args as $arg ) {
1580 if ( !$first ) {
1581 $retVal .= ' ';
1582 } else {
1583 $first = false;
1584 }
1585
1586 if ( wfIsWindows() ) {
1587 // Escaping for an MSVC-style command line parser and CMD.EXE
1588 // Refs:
1589 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1590 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
1591 // * Bug #13518
1592 // * CR r63214
1593 // Double the backslashes before any double quotes. Escape the double quotes.
1594 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1595 $arg = '';
1596 $iteration = 0;
1597 foreach ( $tokens as $token ) {
1598 if ( $iteration % 2 == 1 ) {
1599 // Delimiter, a double quote preceded by zero or more slashes
1600 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1601 } elseif ( $iteration % 4 == 2 ) {
1602 // ^ in $token will be outside quotes, need to be escaped
1603 $arg .= str_replace( '^', '^^', $token );
1604 } else { // $iteration % 4 == 0
1605 // ^ in $token will appear inside double quotes, so leave as is
1606 $arg .= $token;
1607 }
1608 $iteration++;
1609 }
1610 // Double the backslashes before the end of the string, because
1611 // we will soon add a quote
1612 $m = array();
1613 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1614 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1615 }
1616
1617 // Add surrounding quotes
1618 $retVal .= '"' . $arg . '"';
1619 } else {
1620 $retVal .= escapeshellarg( $arg );
1621 }
1622 }
1623 return $retVal;
1624 }
1625
1626 /**
1627 * wfMerge attempts to merge differences between three texts.
1628 * Returns true for a clean merge and false for failure or a conflict.
1629 *
1630 * @param $old String
1631 * @param $mine String
1632 * @param $yours String
1633 * @param $result String
1634 * @return Bool
1635 */
1636 function wfMerge( $old, $mine, $yours, &$result ) {
1637 global $wgDiff3;
1638
1639 # This check may also protect against code injection in
1640 # case of broken installations.
1641 wfSuppressWarnings();
1642 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1643 wfRestoreWarnings();
1644
1645 if( !$haveDiff3 ) {
1646 wfDebug( "diff3 not found\n" );
1647 return false;
1648 }
1649
1650 # Make temporary files
1651 $td = wfTempDir();
1652 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1653 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1654 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1655
1656 fwrite( $oldtextFile, $old );
1657 fclose( $oldtextFile );
1658 fwrite( $mytextFile, $mine );
1659 fclose( $mytextFile );
1660 fwrite( $yourtextFile, $yours );
1661 fclose( $yourtextFile );
1662
1663 # Check for a conflict
1664 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1665 wfEscapeShellArg( $mytextName ) . ' ' .
1666 wfEscapeShellArg( $oldtextName ) . ' ' .
1667 wfEscapeShellArg( $yourtextName );
1668 $handle = popen( $cmd, 'r' );
1669
1670 if( fgets( $handle, 1024 ) ) {
1671 $conflict = true;
1672 } else {
1673 $conflict = false;
1674 }
1675 pclose( $handle );
1676
1677 # Merge differences
1678 $cmd = $wgDiff3 . ' -a -e --merge ' .
1679 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1680 $handle = popen( $cmd, 'r' );
1681 $result = '';
1682 do {
1683 $data = fread( $handle, 8192 );
1684 if ( strlen( $data ) == 0 ) {
1685 break;
1686 }
1687 $result .= $data;
1688 } while ( true );
1689 pclose( $handle );
1690 unlink( $mytextName );
1691 unlink( $oldtextName );
1692 unlink( $yourtextName );
1693
1694 if ( $result === '' && $old !== '' && !$conflict ) {
1695 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1696 $conflict = true;
1697 }
1698 return !$conflict;
1699 }
1700
1701 /**
1702 * Returns unified plain-text diff of two texts.
1703 * Useful for machine processing of diffs.
1704 *
1705 * @param $before String: the text before the changes.
1706 * @param $after String: the text after the changes.
1707 * @param $params String: command-line options for the diff command.
1708 * @return String: unified diff of $before and $after
1709 */
1710 function wfDiff( $before, $after, $params = '-u' ) {
1711 if ( $before == $after ) {
1712 return '';
1713 }
1714
1715 global $wgDiff;
1716 wfSuppressWarnings();
1717 $haveDiff = $wgDiff && file_exists( $wgDiff );
1718 wfRestoreWarnings();
1719
1720 # This check may also protect against code injection in
1721 # case of broken installations.
1722 if( !$haveDiff ) {
1723 wfDebug( "diff executable not found\n" );
1724 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1725 $format = new UnifiedDiffFormatter();
1726 return $format->format( $diffs );
1727 }
1728
1729 # Make temporary files
1730 $td = wfTempDir();
1731 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1732 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1733
1734 fwrite( $oldtextFile, $before );
1735 fclose( $oldtextFile );
1736 fwrite( $newtextFile, $after );
1737 fclose( $newtextFile );
1738
1739 // Get the diff of the two files
1740 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
1741
1742 $h = popen( $cmd, 'r' );
1743
1744 $diff = '';
1745
1746 do {
1747 $data = fread( $h, 8192 );
1748 if ( strlen( $data ) == 0 ) {
1749 break;
1750 }
1751 $diff .= $data;
1752 } while ( true );
1753
1754 // Clean up
1755 pclose( $h );
1756 unlink( $oldtextName );
1757 unlink( $newtextName );
1758
1759 // Kill the --- and +++ lines. They're not useful.
1760 $diff_lines = explode( "\n", $diff );
1761 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
1762 unset( $diff_lines[0] );
1763 }
1764 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
1765 unset( $diff_lines[1] );
1766 }
1767
1768 $diff = implode( "\n", $diff_lines );
1769
1770 return $diff;
1771 }
1772
1773 /**
1774 * A wrapper around the PHP function var_export().
1775 * Either print it or add it to the regular output ($wgOut).
1776 *
1777 * @param $var A PHP variable to dump.
1778 */
1779 function wfVarDump( $var ) {
1780 global $wgOut;
1781 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1782 if ( headers_sent() || !@is_object( $wgOut ) ) {
1783 print $s;
1784 } else {
1785 $wgOut->addHTML( $s );
1786 }
1787 }
1788
1789 /**
1790 * Provide a simple HTTP error.
1791 *
1792 * @param $code Int|String
1793 * @param $label String
1794 * @param $desc String
1795 */
1796 function wfHttpError( $code, $label, $desc ) {
1797 global $wgOut;
1798 $wgOut->disable();
1799 header( "HTTP/1.0 $code $label" );
1800 header( "Status: $code $label" );
1801 $wgOut->sendCacheControl();
1802
1803 header( 'Content-type: text/html; charset=utf-8' );
1804 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1805 '<html><head><title>' .
1806 htmlspecialchars( $label ) .
1807 '</title></head><body><h1>' .
1808 htmlspecialchars( $label ) .
1809 '</h1><p>' .
1810 nl2br( htmlspecialchars( $desc ) ) .
1811 "</p></body></html>\n";
1812 }
1813
1814 /**
1815 * Clear away any user-level output buffers, discarding contents.
1816 *
1817 * Suitable for 'starting afresh', for instance when streaming
1818 * relatively large amounts of data without buffering, or wanting to
1819 * output image files without ob_gzhandler's compression.
1820 *
1821 * The optional $resetGzipEncoding parameter controls suppression of
1822 * the Content-Encoding header sent by ob_gzhandler; by default it
1823 * is left. See comments for wfClearOutputBuffers() for why it would
1824 * be used.
1825 *
1826 * Note that some PHP configuration options may add output buffer
1827 * layers which cannot be removed; these are left in place.
1828 *
1829 * @param $resetGzipEncoding Bool
1830 */
1831 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1832 if( $resetGzipEncoding ) {
1833 // Suppress Content-Encoding and Content-Length
1834 // headers from 1.10+s wfOutputHandler
1835 global $wgDisableOutputCompression;
1836 $wgDisableOutputCompression = true;
1837 }
1838 while( $status = ob_get_status() ) {
1839 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1840 // Probably from zlib.output_compression or other
1841 // PHP-internal setting which can't be removed.
1842 //
1843 // Give up, and hope the result doesn't break
1844 // output behavior.
1845 break;
1846 }
1847 if( !ob_end_clean() ) {
1848 // Could not remove output buffer handler; abort now
1849 // to avoid getting in some kind of infinite loop.
1850 break;
1851 }
1852 if( $resetGzipEncoding ) {
1853 if( $status['name'] == 'ob_gzhandler' ) {
1854 // Reset the 'Content-Encoding' field set by this handler
1855 // so we can start fresh.
1856 if ( function_exists( 'header_remove' ) ) {
1857 // Available since PHP 5.3.0
1858 header_remove( 'Content-Encoding' );
1859 } else {
1860 // We need to provide a valid content-coding. See bug 28069
1861 header( 'Content-Encoding: identity' );
1862 }
1863 break;
1864 }
1865 }
1866 }
1867 }
1868
1869 /**
1870 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1871 *
1872 * Clear away output buffers, but keep the Content-Encoding header
1873 * produced by ob_gzhandler, if any.
1874 *
1875 * This should be used for HTTP 304 responses, where you need to
1876 * preserve the Content-Encoding header of the real result, but
1877 * also need to suppress the output of ob_gzhandler to keep to spec
1878 * and avoid breaking Firefox in rare cases where the headers and
1879 * body are broken over two packets.
1880 */
1881 function wfClearOutputBuffers() {
1882 wfResetOutputBuffers( false );
1883 }
1884
1885 /**
1886 * Converts an Accept-* header into an array mapping string values to quality
1887 * factors
1888 *
1889 * @param $accept String
1890 * @param $def String default
1891 * @return Array
1892 */
1893 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1894 # No arg means accept anything (per HTTP spec)
1895 if( !$accept ) {
1896 return array( $def => 1.0 );
1897 }
1898
1899 $prefs = array();
1900
1901 $parts = explode( ',', $accept );
1902
1903 foreach( $parts as $part ) {
1904 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1905 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1906 $match = array();
1907 if( !isset( $qpart ) ) {
1908 $prefs[$value] = 1.0;
1909 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1910 $prefs[$value] = floatval( $match[1] );
1911 }
1912 }
1913
1914 return $prefs;
1915 }
1916
1917 /**
1918 * Checks if a given MIME type matches any of the keys in the given
1919 * array. Basic wildcards are accepted in the array keys.
1920 *
1921 * Returns the matching MIME type (or wildcard) if a match, otherwise
1922 * NULL if no match.
1923 *
1924 * @param $type String
1925 * @param $avail Array
1926 * @return string
1927 * @private
1928 */
1929 function mimeTypeMatch( $type, $avail ) {
1930 if( array_key_exists( $type, $avail ) ) {
1931 return $type;
1932 } else {
1933 $parts = explode( '/', $type );
1934 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1935 return $parts[0] . '/*';
1936 } elseif( array_key_exists( '*/*', $avail ) ) {
1937 return '*/*';
1938 } else {
1939 return null;
1940 }
1941 }
1942 }
1943
1944 /**
1945 * Returns the 'best' match between a client's requested internet media types
1946 * and the server's list of available types. Each list should be an associative
1947 * array of type to preference (preference is a float between 0.0 and 1.0).
1948 * Wildcards in the types are acceptable.
1949 *
1950 * @param $cprefs Array: client's acceptable type list
1951 * @param $sprefs Array: server's offered types
1952 * @return string
1953 *
1954 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
1955 * XXX: generalize to negotiate other stuff
1956 */
1957 function wfNegotiateType( $cprefs, $sprefs ) {
1958 $combine = array();
1959
1960 foreach( array_keys($sprefs) as $type ) {
1961 $parts = explode( '/', $type );
1962 if( $parts[1] != '*' ) {
1963 $ckey = mimeTypeMatch( $type, $cprefs );
1964 if( $ckey ) {
1965 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1966 }
1967 }
1968 }
1969
1970 foreach( array_keys( $cprefs ) as $type ) {
1971 $parts = explode( '/', $type );
1972 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1973 $skey = mimeTypeMatch( $type, $sprefs );
1974 if( $skey ) {
1975 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1976 }
1977 }
1978 }
1979
1980 $bestq = 0;
1981 $besttype = null;
1982
1983 foreach( array_keys( $combine ) as $type ) {
1984 if( $combine[$type] > $bestq ) {
1985 $besttype = $type;
1986 $bestq = $combine[$type];
1987 }
1988 }
1989
1990 return $besttype;
1991 }
1992
1993 /**
1994 * Reference-counted warning suppression
1995 *
1996 * @param $end Bool
1997 */
1998 function wfSuppressWarnings( $end = false ) {
1999 static $suppressCount = 0;
2000 static $originalLevel = false;
2001
2002 if ( $end ) {
2003 if ( $suppressCount ) {
2004 --$suppressCount;
2005 if ( !$suppressCount ) {
2006 error_reporting( $originalLevel );
2007 }
2008 }
2009 } else {
2010 if ( !$suppressCount ) {
2011 // E_DEPRECATED is undefined in PHP 5.2
2012 if( !defined( 'E_DEPRECATED' ) ){
2013 define( 'E_DEPRECATED', 8192 );
2014 }
2015 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED ) );
2016 }
2017 ++$suppressCount;
2018 }
2019 }
2020
2021 /**
2022 * Restore error level to previous value
2023 */
2024 function wfRestoreWarnings() {
2025 wfSuppressWarnings( true );
2026 }
2027
2028 # Autodetect, convert and provide timestamps of various types
2029
2030 /**
2031 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2032 */
2033 define( 'TS_UNIX', 0 );
2034
2035 /**
2036 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2037 */
2038 define( 'TS_MW', 1 );
2039
2040 /**
2041 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2042 */
2043 define( 'TS_DB', 2 );
2044
2045 /**
2046 * RFC 2822 format, for E-mail and HTTP headers
2047 */
2048 define( 'TS_RFC2822', 3 );
2049
2050 /**
2051 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2052 *
2053 * This is used by Special:Export
2054 */
2055 define( 'TS_ISO_8601', 4 );
2056
2057 /**
2058 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2059 *
2060 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2061 * DateTime tag and page 36 for the DateTimeOriginal and
2062 * DateTimeDigitized tags.
2063 */
2064 define( 'TS_EXIF', 5 );
2065
2066 /**
2067 * Oracle format time.
2068 */
2069 define( 'TS_ORACLE', 6 );
2070
2071 /**
2072 * Postgres format time.
2073 */
2074 define( 'TS_POSTGRES', 7 );
2075
2076 /**
2077 * DB2 format time
2078 */
2079 define( 'TS_DB2', 8 );
2080
2081 /**
2082 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2083 */
2084 define( 'TS_ISO_8601_BASIC', 9 );
2085
2086 /**
2087 * Get a timestamp string in one of various formats
2088 *
2089 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
2090 * function will autodetect which format is supplied and act
2091 * accordingly.
2092 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
2093 * @return Mixed: String / false The same date in the format specified in $outputtype or false
2094 */
2095 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
2096 $uts = 0;
2097 $da = array();
2098 $strtime = '';
2099
2100 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
2101 $uts = time();
2102 $strtime = "@$uts";
2103 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2104 # TS_DB
2105 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2106 # TS_EXIF
2107 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
2108 # TS_MW
2109 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
2110 # TS_UNIX
2111 $uts = $ts;
2112 $strtime = "@$ts"; // Undocumented?
2113 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
2114 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
2115 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
2116 str_replace( '+00:00', 'UTC', $ts ) );
2117 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2118 # TS_ISO_8601
2119 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2120 #TS_ISO_8601_BASIC
2121 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2122 # TS_POSTGRES
2123 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2124 # TS_POSTGRES
2125 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
2126 # TS_DB2
2127 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
2128 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
2129 '[ \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
2130 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
2131 # The regex is a superset of rfc2822 for readability
2132 $strtime = strtok( $ts, ';' );
2133 } 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 ) ) {
2134 # TS_RFC850
2135 $strtime = $ts;
2136 } 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 ) ) {
2137 # asctime
2138 $strtime = $ts;
2139 } else {
2140 # Bogus value...
2141 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
2142
2143 return false;
2144 }
2145
2146
2147
2148 static $formats = array(
2149 TS_UNIX => 'U',
2150 TS_MW => 'YmdHis',
2151 TS_DB => 'Y-m-d H:i:s',
2152 TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
2153 TS_ISO_8601_BASIC => 'Ymd\THis\Z',
2154 TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2155 TS_RFC2822 => 'D, d M Y H:i:s',
2156 TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2157 TS_POSTGRES => 'Y-m-d H:i:s',
2158 TS_DB2 => 'Y-m-d H:i:s',
2159 );
2160
2161 if ( !isset( $formats[$outputtype] ) ) {
2162 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2163 }
2164
2165 if ( function_exists( "date_create" ) ) {
2166 if ( count( $da ) ) {
2167 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2168 (int)$da[1], (int)$da[2], (int)$da[3],
2169 (int)$da[4], (int)$da[5], (int)$da[6]);
2170
2171 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2172 } elseif ( $strtime ) {
2173 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2174 } else {
2175 return false;
2176 }
2177
2178 if ( !$d ) {
2179 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2180 return false;
2181 }
2182
2183 $output = $d->format( $formats[$outputtype] );
2184 } else {
2185 if ( count( $da ) ) {
2186 // Warning! gmmktime() acts oddly if the month or day is set to 0
2187 // We may want to handle that explicitly at some point
2188 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2189 (int)$da[2], (int)$da[3], (int)$da[1] );
2190 } elseif ( $strtime ) {
2191 $uts = strtotime( $strtime );
2192 }
2193
2194 if ( $uts === false ) {
2195 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2196 return false;
2197 }
2198
2199 if ( TS_UNIX == $outputtype ) {
2200 return $uts;
2201 }
2202 $output = gmdate( $formats[$outputtype], $uts );
2203 }
2204
2205 if ( ( $outputtype == TS_RFC2822 ) || ( $outputtype == TS_POSTGRES ) ) {
2206 $output .= ' GMT';
2207 }
2208
2209 return $output;
2210 }
2211
2212 /**
2213 * Return a formatted timestamp, or null if input is null.
2214 * For dealing with nullable timestamp columns in the database.
2215 *
2216 * @param $outputtype Integer
2217 * @param $ts String
2218 * @return String
2219 */
2220 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2221 if( is_null( $ts ) ) {
2222 return null;
2223 } else {
2224 return wfTimestamp( $outputtype, $ts );
2225 }
2226 }
2227
2228 /**
2229 * Convenience function; returns MediaWiki timestamp for the present time.
2230 *
2231 * @return string
2232 */
2233 function wfTimestampNow() {
2234 # return NOW
2235 return wfTimestamp( TS_MW, time() );
2236 }
2237
2238 /**
2239 * Check if the operating system is Windows
2240 *
2241 * @return Bool: true if it's Windows, False otherwise.
2242 */
2243 function wfIsWindows() {
2244 static $isWindows = null;
2245 if ( $isWindows === null ) {
2246 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2247 }
2248 return $isWindows;
2249 }
2250
2251 /**
2252 * Check if we are running under HipHop
2253 *
2254 * @return Bool
2255 */
2256 function wfIsHipHop() {
2257 return function_exists( 'hphp_thread_set_warmup_enabled' );
2258 }
2259
2260 /**
2261 * Swap two variables
2262 *
2263 * @param $x Mixed
2264 * @param $y Mixed
2265 */
2266 function swap( &$x, &$y ) {
2267 $z = $x;
2268 $x = $y;
2269 $y = $z;
2270 }
2271
2272 /**
2273 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2274 * TEMP environment variables are then checked in sequence, and if none are set
2275 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2276 * or C:\Windows\Temp for Windows and hope for the best.
2277 * It is common to call it with tempnam().
2278 *
2279 * NOTE: When possible, use instead the tmpfile() function to create
2280 * temporary files to avoid race conditions on file creation, etc.
2281 *
2282 * @return String
2283 */
2284 function wfTempDir() {
2285 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2286 $tmp = getenv( $var );
2287 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2288 return $tmp;
2289 }
2290 }
2291 if( function_exists( 'sys_get_temp_dir' ) ) {
2292 return sys_get_temp_dir();
2293 }
2294 # Usual defaults
2295 return wfIsWindows() ? 'C:\Windows\Temp' : '/tmp';
2296 }
2297
2298 /**
2299 * Make directory, and make all parent directories if they don't exist
2300 *
2301 * @param $dir String: full path to directory to create
2302 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2303 * @param $caller String: optional caller param for debugging.
2304 * @return bool
2305 */
2306 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2307 global $wgDirectoryMode;
2308
2309 if ( !is_null( $caller ) ) {
2310 wfDebug( "$caller: called wfMkdirParents($dir)" );
2311 }
2312
2313 if( strval( $dir ) === '' || file_exists( $dir ) ) {
2314 return true;
2315 }
2316
2317 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2318
2319 if ( is_null( $mode ) ) {
2320 $mode = $wgDirectoryMode;
2321 }
2322
2323 // Turn off the normal warning, we're doing our own below
2324 wfSuppressWarnings();
2325 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2326 wfRestoreWarnings();
2327
2328 if( !$ok ) {
2329 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2330 trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
2331 }
2332 return $ok;
2333 }
2334
2335 /**
2336 * Increment a statistics counter
2337 *
2338 * @param $key String
2339 * @param $count Int
2340 */
2341 function wfIncrStats( $key, $count = 1 ) {
2342 global $wgStatsMethod;
2343
2344 $count = intval( $count );
2345
2346 if( $wgStatsMethod == 'udp' ) {
2347 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname, $wgAggregateStatsID;
2348 static $socket;
2349
2350 $id = $wgAggregateStatsID !== false ? $wgAggregateStatsID : $wgDBname;
2351
2352 if ( !$socket ) {
2353 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
2354 $statline = "stats/{$id} - {$count} 1 1 1 1 -total\n";
2355 socket_sendto(
2356 $socket,
2357 $statline,
2358 strlen( $statline ),
2359 0,
2360 $wgUDPProfilerHost,
2361 $wgUDPProfilerPort
2362 );
2363 }
2364 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n";
2365 wfSuppressWarnings();
2366 socket_sendto(
2367 $socket,
2368 $statline,
2369 strlen( $statline ),
2370 0,
2371 $wgUDPProfilerHost,
2372 $wgUDPProfilerPort
2373 );
2374 wfRestoreWarnings();
2375 } elseif( $wgStatsMethod == 'cache' ) {
2376 global $wgMemc;
2377 $key = wfMemcKey( 'stats', $key );
2378 if ( is_null( $wgMemc->incr( $key, $count ) ) ) {
2379 $wgMemc->add( $key, $count );
2380 }
2381 } else {
2382 // Disabled
2383 }
2384 }
2385
2386 /**
2387 * @param $nr Mixed: the number to format
2388 * @param $acc Integer: the number of digits after the decimal point, default 2
2389 * @param $round Boolean: whether or not to round the value, default true
2390 * @return float
2391 */
2392 function wfPercent( $nr, $acc = 2, $round = true ) {
2393 $ret = sprintf( "%.${acc}f", $nr );
2394 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2395 }
2396
2397 /**
2398 * Find out whether or not a mixed variable exists in a string
2399 *
2400 * @param $needle String
2401 * @param $str String
2402 * @param $insensitive Boolean
2403 * @return Boolean
2404 */
2405 function in_string( $needle, $str, $insensitive = false ) {
2406 $func = 'strpos';
2407 if( $insensitive ) $func = 'stripos';
2408
2409 return $func( $str, $needle ) !== false;
2410 }
2411
2412 function wfSpecialList( $page, $details ) {
2413 global $wgContLang;
2414 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : '';
2415 return $page . $details;
2416 }
2417
2418 /**
2419 * Returns a regular expression of url protocols
2420 *
2421 * @return String
2422 */
2423 function wfUrlProtocols() {
2424 global $wgUrlProtocols;
2425
2426 static $retval = null;
2427 if ( !is_null( $retval ) ) {
2428 return $retval;
2429 }
2430
2431 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2432 // with LocalSettings files from 1.5
2433 if ( is_array( $wgUrlProtocols ) ) {
2434 $protocols = array();
2435 foreach ( $wgUrlProtocols as $protocol ) {
2436 $protocols[] = preg_quote( $protocol, '/' );
2437 }
2438
2439 $retval = implode( '|', $protocols );
2440 } else {
2441 $retval = $wgUrlProtocols;
2442 }
2443 return $retval;
2444 }
2445
2446 /**
2447 * Safety wrapper around ini_get() for boolean settings.
2448 * The values returned from ini_get() are pre-normalized for settings
2449 * set via php.ini or php_flag/php_admin_flag... but *not*
2450 * for those set via php_value/php_admin_value.
2451 *
2452 * It's fairly common for people to use php_value instead of php_flag,
2453 * which can leave you with an 'off' setting giving a false positive
2454 * for code that just takes the ini_get() return value as a boolean.
2455 *
2456 * To make things extra interesting, setting via php_value accepts
2457 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2458 * Unrecognized values go false... again opposite PHP's own coercion
2459 * from string to bool.
2460 *
2461 * Luckily, 'properly' set settings will always come back as '0' or '1',
2462 * so we only have to worry about them and the 'improper' settings.
2463 *
2464 * I frickin' hate PHP... :P
2465 *
2466 * @param $setting String
2467 * @return Bool
2468 */
2469 function wfIniGetBool( $setting ) {
2470 $val = ini_get( $setting );
2471 // 'on' and 'true' can't have whitespace around them, but '1' can.
2472 return strtolower( $val ) == 'on'
2473 || strtolower( $val ) == 'true'
2474 || strtolower( $val ) == 'yes'
2475 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2476 }
2477
2478 /**
2479 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2480 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2481 *
2482 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2483 * should be omitted
2484 * @param $fileName String Name of the library, if not $extension.suffix
2485 * @return Bool - Whether or not the extension is loaded
2486 */
2487 function wfDl( $extension, $fileName = null ) {
2488 if( extension_loaded( $extension ) ) {
2489 return true;
2490 }
2491
2492 $canDl = false;
2493 $sapi = php_sapi_name();
2494 if( version_compare( PHP_VERSION, '5.3.0', '<' ) ||
2495 $sapi == 'cli' || $sapi == 'cgi' || $sapi == 'embed' )
2496 {
2497 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2498 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2499 }
2500
2501 if( $canDl ) {
2502 $fileName = $fileName ? $fileName : $extension;
2503 if( wfIsWindows() ) {
2504 $fileName = 'php_' . $fileName;
2505 }
2506 wfSuppressWarnings();
2507 dl( $fileName . '.' . PHP_SHLIB_SUFFIX );
2508 wfRestoreWarnings();
2509 }
2510 return extension_loaded( $extension );
2511 }
2512
2513 /**
2514 * Execute a shell command, with time and memory limits mirrored from the PHP
2515 * configuration if supported.
2516 * @param $cmd String Command line, properly escaped for shell.
2517 * @param &$retval optional, will receive the program's exit code.
2518 * (non-zero is usually failure)
2519 * @param $environ Array optional environment variables which should be
2520 * added to the executed command environment.
2521 * @return collected stdout as a string (trailing newlines stripped)
2522 */
2523 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2524 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2525
2526 static $disabled;
2527 if ( is_null( $disabled ) ) {
2528 $disabled = false;
2529 if( wfIniGetBool( 'safe_mode' ) ) {
2530 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2531 $disabled = 'safemode';
2532 } else {
2533 $functions = explode( ',', ini_get( 'disable_functions' ) );
2534 $functions = array_map( 'trim', $functions );
2535 $functions = array_map( 'strtolower', $functions );
2536 if ( in_array( 'passthru', $functions ) ) {
2537 wfDebug( "passthru is in disabled_functions\n" );
2538 $disabled = 'passthru';
2539 }
2540 }
2541 }
2542 if ( $disabled ) {
2543 $retval = 1;
2544 return $disabled == 'safemode' ?
2545 'Unable to run external programs in safe mode.' :
2546 'Unable to run external programs, passthru() is disabled.';
2547 }
2548
2549 wfInitShellLocale();
2550
2551 $envcmd = '';
2552 foreach( $environ as $k => $v ) {
2553 if ( wfIsWindows() ) {
2554 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2555 * appear in the environment variable, so we must use carat escaping as documented in
2556 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2557 * Note however that the quote isn't listed there, but is needed, and the parentheses
2558 * are listed there but doesn't appear to need it.
2559 */
2560 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2561 } else {
2562 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2563 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2564 */
2565 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2566 }
2567 }
2568 $cmd = $envcmd . $cmd;
2569
2570 if ( wfIsWindows() ) {
2571 if ( version_compare( PHP_VERSION, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2572 ( version_compare( PHP_VERSION, '5.2.1', '>=' ) || php_uname( 's' ) == 'Windows NT' ) )
2573 {
2574 # Hack to work around PHP's flawed invocation of cmd.exe
2575 # http://news.php.net/php.internals/21796
2576 # Windows 9x doesn't accept any kind of quotes
2577 $cmd = '"' . $cmd . '"';
2578 }
2579 } elseif ( php_uname( 's' ) == 'Linux' ) {
2580 $time = intval( $wgMaxShellTime );
2581 $mem = intval( $wgMaxShellMemory );
2582 $filesize = intval( $wgMaxShellFileSize );
2583
2584 if ( $time > 0 && $mem > 0 ) {
2585 $script = "$IP/bin/ulimit4.sh";
2586 if ( is_executable( $script ) ) {
2587 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2588 }
2589 }
2590 }
2591 wfDebug( "wfShellExec: $cmd\n" );
2592
2593 $retval = 1; // error by default?
2594 ob_start();
2595 passthru( $cmd, $retval );
2596 $output = ob_get_contents();
2597 ob_end_clean();
2598
2599 if ( $retval == 127 ) {
2600 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2601 }
2602 return $output;
2603 }
2604
2605 /**
2606 * Workaround for http://bugs.php.net/bug.php?id=45132
2607 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2608 */
2609 function wfInitShellLocale() {
2610 static $done = false;
2611 if ( $done ) {
2612 return;
2613 }
2614 $done = true;
2615 global $wgShellLocale;
2616 if ( !wfIniGetBool( 'safe_mode' ) ) {
2617 putenv( "LC_CTYPE=$wgShellLocale" );
2618 setlocale( LC_CTYPE, $wgShellLocale );
2619 }
2620 }
2621
2622 /**
2623 * This function works like "use VERSION" in Perl, the program will die with a
2624 * backtrace if the current version of PHP is less than the version provided
2625 *
2626 * This is useful for extensions which due to their nature are not kept in sync
2627 * with releases, and might depend on other versions of PHP than the main code
2628 *
2629 * Note: PHP might die due to parsing errors in some cases before it ever
2630 * manages to call this function, such is life
2631 *
2632 * @see perldoc -f use
2633 *
2634 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2635 * a float
2636 */
2637 function wfUsePHP( $req_ver ) {
2638 $php_ver = PHP_VERSION;
2639
2640 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2641 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2642 }
2643 }
2644
2645 /**
2646 * This function works like "use VERSION" in Perl except it checks the version
2647 * of MediaWiki, the program will die with a backtrace if the current version
2648 * of MediaWiki is less than the version provided.
2649 *
2650 * This is useful for extensions which due to their nature are not kept in sync
2651 * with releases
2652 *
2653 * @see perldoc -f use
2654 *
2655 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2656 * a float
2657 */
2658 function wfUseMW( $req_ver ) {
2659 global $wgVersion;
2660
2661 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2662 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2663 }
2664 }
2665
2666 /**
2667 * Return the final portion of a pathname.
2668 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2669 * http://bugs.php.net/bug.php?id=33898
2670 *
2671 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2672 * We'll consider it so always, as we don't want \s in our Unix paths either.
2673 *
2674 * @param $path String
2675 * @param $suffix String: to remove if present
2676 * @return String
2677 */
2678 function wfBaseName( $path, $suffix = '' ) {
2679 $encSuffix = ( $suffix == '' )
2680 ? ''
2681 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2682 $matches = array();
2683 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2684 return $matches[1];
2685 } else {
2686 return '';
2687 }
2688 }
2689
2690 /**
2691 * Generate a relative path name to the given file.
2692 * May explode on non-matching case-insensitive paths,
2693 * funky symlinks, etc.
2694 *
2695 * @param $path String: absolute destination path including target filename
2696 * @param $from String: Absolute source path, directory only
2697 * @return String
2698 */
2699 function wfRelativePath( $path, $from ) {
2700 // Normalize mixed input on Windows...
2701 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2702 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2703
2704 // Trim trailing slashes -- fix for drive root
2705 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2706 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2707
2708 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2709 $against = explode( DIRECTORY_SEPARATOR, $from );
2710
2711 if( $pieces[0] !== $against[0] ) {
2712 // Non-matching Windows drive letters?
2713 // Return a full path.
2714 return $path;
2715 }
2716
2717 // Trim off common prefix
2718 while( count( $pieces ) && count( $against )
2719 && $pieces[0] == $against[0] ) {
2720 array_shift( $pieces );
2721 array_shift( $against );
2722 }
2723
2724 // relative dots to bump us to the parent
2725 while( count( $against ) ) {
2726 array_unshift( $pieces, '..' );
2727 array_shift( $against );
2728 }
2729
2730 array_push( $pieces, wfBaseName( $path ) );
2731
2732 return implode( DIRECTORY_SEPARATOR, $pieces );
2733 }
2734
2735 /**
2736 * parse_url() work-alike, but non-broken. Differences:
2737 *
2738 * 1) Does not raise warnings on bad URLs (just returns false)
2739 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2740 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2741 *
2742 * @param $url String: a URL to parse
2743 * @return Array: bits of the URL in an associative array, per PHP docs
2744 */
2745 function wfParseUrl( $url ) {
2746 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2747 wfSuppressWarnings();
2748 $bits = parse_url( $url );
2749 wfRestoreWarnings();
2750 if ( !$bits ) {
2751 return false;
2752 }
2753
2754 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2755 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2756 $bits['delimiter'] = '://';
2757 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2758 $bits['delimiter'] = ':';
2759 // parse_url detects for news: and mailto: the host part of an url as path
2760 // We have to correct this wrong detection
2761 if ( isset( $bits['path'] ) ) {
2762 $bits['host'] = $bits['path'];
2763 $bits['path'] = '';
2764 }
2765 } else {
2766 return false;
2767 }
2768
2769 return $bits;
2770 }
2771
2772 /**
2773 * Make a URL index, appropriate for the el_index field of externallinks.
2774 *
2775 * @param $url String
2776 * @return String
2777 */
2778 function wfMakeUrlIndex( $url ) {
2779 $bits = wfParseUrl( $url );
2780
2781 // Reverse the labels in the hostname, convert to lower case
2782 // For emails reverse domainpart only
2783 if ( $bits['scheme'] == 'mailto' ) {
2784 $mailparts = explode( '@', $bits['host'], 2 );
2785 if ( count( $mailparts ) === 2 ) {
2786 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2787 } else {
2788 // No domain specified, don't mangle it
2789 $domainpart = '';
2790 }
2791 $reversedHost = $domainpart . '@' . $mailparts[0];
2792 } else if ( isset( $bits['host'] ) ) {
2793 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2794 } else {
2795 // In file: URIs for instance it's common to have an empty host,
2796 // which turns up as not getting a 'host' member from parse_url.
2797 $reversedHost = '.';
2798 }
2799 // Add an extra dot to the end
2800 // Why? Is it in wrong place in mailto links?
2801 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2802 $reversedHost .= '.';
2803 }
2804 // Reconstruct the pseudo-URL
2805 $prot = $bits['scheme'];
2806 $index = $prot . $bits['delimiter'] . $reversedHost;
2807 // Leave out user and password. Add the port, path, query and fragment
2808 if ( isset( $bits['port'] ) ) {
2809 $index .= ':' . $bits['port'];
2810 }
2811 if ( isset( $bits['path'] ) ) {
2812 // parse_url() removes the initial '/' from the path
2813 // for file: URLs with Windows-style paths, such as
2814 // file:///c:/windows/stuff. We need to add it back
2815 // to keep our division between host and path properly.
2816 if ( strlen( $bits['path'] ) > 0 && substr( $bits['path'], 0, 1 ) !== '/' ) {
2817 $index .= '/';
2818 }
2819 $index .= $bits['path'];
2820 } else {
2821 $index .= '/';
2822 }
2823 if ( isset( $bits['query'] ) ) {
2824 $index .= '?' . $bits['query'];
2825 }
2826 if ( isset( $bits['fragment'] ) ) {
2827 $index .= '#' . $bits['fragment'];
2828 }
2829 return $index;
2830 }
2831
2832 /**
2833 * Do any deferred updates and clear the list
2834 *
2835 * @param $commit String: set to 'commit' to commit after every update to
2836 * prevent lock contention
2837 */
2838 function wfDoUpdates( $commit = '' ) {
2839 global $wgDeferredUpdateList;
2840
2841 wfProfileIn( __METHOD__ );
2842
2843 // No need to get master connections in case of empty updates array
2844 if ( !count( $wgDeferredUpdateList ) ) {
2845 wfProfileOut( __METHOD__ );
2846 return;
2847 }
2848
2849 $doCommit = $commit == 'commit';
2850 if ( $doCommit ) {
2851 $dbw = wfGetDB( DB_MASTER );
2852 }
2853
2854 foreach ( $wgDeferredUpdateList as $update ) {
2855 $update->doUpdate();
2856
2857 if ( $doCommit && $dbw->trxLevel() ) {
2858 $dbw->commit();
2859 }
2860 }
2861
2862 $wgDeferredUpdateList = array();
2863 wfProfileOut( __METHOD__ );
2864 }
2865
2866 /**
2867 * Convert an arbitrarily-long digit string from one numeric base
2868 * to another, optionally zero-padding to a minimum column width.
2869 *
2870 * Supports base 2 through 36; digit values 10-36 are represented
2871 * as lowercase letters a-z. Input is case-insensitive.
2872 *
2873 * @param $input String: of digits
2874 * @param $sourceBase Integer: 2-36
2875 * @param $destBase Integer: 2-36
2876 * @param $pad Integer: 1 or greater
2877 * @param $lowercase Boolean
2878 * @return String or false on invalid input
2879 */
2880 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2881 $input = strval( $input );
2882 if( $sourceBase < 2 ||
2883 $sourceBase > 36 ||
2884 $destBase < 2 ||
2885 $destBase > 36 ||
2886 $pad < 1 ||
2887 $sourceBase != intval( $sourceBase ) ||
2888 $destBase != intval( $destBase ) ||
2889 $pad != intval( $pad ) ||
2890 !is_string( $input ) ||
2891 $input == '' ) {
2892 return false;
2893 }
2894 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2895 $inDigits = array();
2896 $outChars = '';
2897
2898 // Decode and validate input string
2899 $input = strtolower( $input );
2900 for( $i = 0; $i < strlen( $input ); $i++ ) {
2901 $n = strpos( $digitChars, $input[$i] );
2902 if( $n === false || $n > $sourceBase ) {
2903 return false;
2904 }
2905 $inDigits[] = $n;
2906 }
2907
2908 // Iterate over the input, modulo-ing out an output digit
2909 // at a time until input is gone.
2910 while( count( $inDigits ) ) {
2911 $work = 0;
2912 $workDigits = array();
2913
2914 // Long division...
2915 foreach( $inDigits as $digit ) {
2916 $work *= $sourceBase;
2917 $work += $digit;
2918
2919 if( $work < $destBase ) {
2920 // Gonna need to pull another digit.
2921 if( count( $workDigits ) ) {
2922 // Avoid zero-padding; this lets us find
2923 // the end of the input very easily when
2924 // length drops to zero.
2925 $workDigits[] = 0;
2926 }
2927 } else {
2928 // Finally! Actual division!
2929 $workDigits[] = intval( $work / $destBase );
2930
2931 // Isn't it annoying that most programming languages
2932 // don't have a single divide-and-remainder operator,
2933 // even though the CPU implements it that way?
2934 $work = $work % $destBase;
2935 }
2936 }
2937
2938 // All that division leaves us with a remainder,
2939 // which is conveniently our next output digit.
2940 $outChars .= $digitChars[$work];
2941
2942 // And we continue!
2943 $inDigits = $workDigits;
2944 }
2945
2946 while( strlen( $outChars ) < $pad ) {
2947 $outChars .= '0';
2948 }
2949
2950 return strrev( $outChars );
2951 }
2952
2953 /**
2954 * Create an object with a given name and an array of construct parameters
2955 *
2956 * @param $name String
2957 * @param $p Array: parameters
2958 * @deprecated since 1.18, warnings in 1.19, removal in 1.20
2959 */
2960 function wfCreateObject( $name, $p ) {
2961 wfDeprecated( __FUNCTION__ );
2962 return MWFunction::newObj( $name, $p );
2963 }
2964
2965 function wfHttpOnlySafe() {
2966 global $wgHttpOnlyBlacklist;
2967
2968 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2969 foreach( $wgHttpOnlyBlacklist as $regex ) {
2970 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2971 return false;
2972 }
2973 }
2974 }
2975
2976 return true;
2977 }
2978
2979 /**
2980 * Initialise php session
2981 *
2982 * @param $sessionId Bool
2983 */
2984 function wfSetupSession( $sessionId = false ) {
2985 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2986 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2987 if( $wgSessionsInMemcached ) {
2988 if ( !defined( 'MW_COMPILED' ) ) {
2989 global $IP;
2990 require_once( "$IP/includes/cache/MemcachedSessions.php" );
2991 }
2992 session_set_save_handler( 'memsess_open', 'memsess_close', 'memsess_read',
2993 'memsess_write', 'memsess_destroy', 'memsess_gc' );
2994
2995 // It's necessary to register a shutdown function to call session_write_close(),
2996 // because by the time the request shutdown function for the session module is
2997 // called, $wgMemc has already been destroyed. Shutdown functions registered
2998 // this way are called before object destruction.
2999 register_shutdown_function( 'memsess_write_close' );
3000 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3001 # Only set this if $wgSessionHandler isn't null and session.save_handler
3002 # hasn't already been set to the desired value (that causes errors)
3003 ini_set( 'session.save_handler', $wgSessionHandler );
3004 }
3005 $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
3006 wfDebugLog( 'cookie',
3007 'session_set_cookie_params: "' . implode( '", "',
3008 array(
3009 0,
3010 $wgCookiePath,
3011 $wgCookieDomain,
3012 $wgCookieSecure,
3013 $httpOnlySafe ) ) . '"' );
3014 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
3015 session_cache_limiter( 'private, must-revalidate' );
3016 if ( $sessionId ) {
3017 session_id( $sessionId );
3018 }
3019 wfSuppressWarnings();
3020 session_start();
3021 wfRestoreWarnings();
3022 }
3023
3024 /**
3025 * Get an object from the precompiled serialized directory
3026 *
3027 * @param $name String
3028 * @return Mixed: the variable on success, false on failure
3029 */
3030 function wfGetPrecompiledData( $name ) {
3031 global $IP;
3032
3033 $file = "$IP/serialized/$name";
3034 if ( file_exists( $file ) ) {
3035 $blob = file_get_contents( $file );
3036 if ( $blob ) {
3037 return unserialize( $blob );
3038 }
3039 }
3040 return false;
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