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