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