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