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