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