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