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