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