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