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