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