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