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