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