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