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