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