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