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