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