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