Add FIXME to wfMergeErrorArrays(), throws E_NOTICEs.
[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 * is correct. Also doesn't handle any type of relative URL except one
1413 * starting with a single "/": this won't work with current-path-relative URLs
1414 * like "subdir/foo.html", protocol-relative URLs like
1415 * "//en.wikipedia.org/wiki/", etc. TODO: improve this!
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, 1 ) == '/' ) {
1422 global $wgServer;
1423 return $wgServer . $url;
1424 } else {
1425 return $url;
1426 }
1427 }
1428
1429 /**
1430 * This is obsolete, use SquidUpdate::purge()
1431 * @deprecated
1432 */
1433 function wfPurgeSquidServers ($urlArr) {
1434 SquidUpdate::purge( $urlArr );
1435 }
1436
1437 /**
1438 * Windows-compatible version of escapeshellarg()
1439 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1440 * function puts single quotes in regardless of OS.
1441 *
1442 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1443 * earlier distro releases of PHP)
1444 */
1445 function wfEscapeShellArg( ) {
1446 wfInitShellLocale();
1447
1448 $args = func_get_args();
1449 $first = true;
1450 $retVal = '';
1451 foreach ( $args as $arg ) {
1452 if ( !$first ) {
1453 $retVal .= ' ';
1454 } else {
1455 $first = false;
1456 }
1457
1458 if ( wfIsWindows() ) {
1459 // Escaping for an MSVC-style command line parser
1460 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1461 // Double the backslashes before any double quotes. Escape the double quotes.
1462 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1463 $arg = '';
1464 $delim = false;
1465 foreach ( $tokens as $token ) {
1466 if ( $delim ) {
1467 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1468 } else {
1469 $arg .= $token;
1470 }
1471 $delim = !$delim;
1472 }
1473
1474 // Double the backslashes before the end of the string, because
1475 // we will soon add a quote
1476 $m = array();
1477 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1478 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1479 }
1480
1481 // The caret is also an special character
1482 $arg = str_replace( "^", "^^", $arg );
1483
1484 // Add surrounding quotes
1485 $retVal .= '"' . $arg . '"';
1486 } else {
1487 $retVal .= escapeshellarg( $arg );
1488 }
1489 }
1490 return $retVal;
1491 }
1492
1493 /**
1494 * wfMerge attempts to merge differences between three texts.
1495 * Returns true for a clean merge and false for failure or a conflict.
1496 */
1497 function wfMerge( $old, $mine, $yours, &$result ){
1498 global $wgDiff3;
1499
1500 # This check may also protect against code injection in
1501 # case of broken installations.
1502 if( !$wgDiff3 || !file_exists( $wgDiff3 ) ) {
1503 wfDebug( "diff3 not found\n" );
1504 return false;
1505 }
1506
1507 # Make temporary files
1508 $td = wfTempDir();
1509 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1510 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1511 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1512
1513 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1514 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1515 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1516
1517 # Check for a conflict
1518 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1519 wfEscapeShellArg( $mytextName ) . ' ' .
1520 wfEscapeShellArg( $oldtextName ) . ' ' .
1521 wfEscapeShellArg( $yourtextName );
1522 $handle = popen( $cmd, 'r' );
1523
1524 if( fgets( $handle, 1024 ) ){
1525 $conflict = true;
1526 } else {
1527 $conflict = false;
1528 }
1529 pclose( $handle );
1530
1531 # Merge differences
1532 $cmd = $wgDiff3 . ' -a -e --merge ' .
1533 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1534 $handle = popen( $cmd, 'r' );
1535 $result = '';
1536 do {
1537 $data = fread( $handle, 8192 );
1538 if ( strlen( $data ) == 0 ) {
1539 break;
1540 }
1541 $result .= $data;
1542 } while ( true );
1543 pclose( $handle );
1544 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1545
1546 if ( $result === '' && $old !== '' && $conflict == false ) {
1547 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1548 $conflict = true;
1549 }
1550 return ! $conflict;
1551 }
1552
1553 /**
1554 * Returns unified plain-text diff of two texts.
1555 * Useful for machine processing of diffs.
1556 * @param $before String: the text before the changes.
1557 * @param $after String: the text after the changes.
1558 * @param $params String: command-line options for the diff command.
1559 * @return String: unified diff of $before and $after
1560 */
1561 function wfDiff( $before, $after, $params = '-u' ) {
1562 if ($before == $after) {
1563 return '';
1564 }
1565
1566 global $wgDiff;
1567
1568 # This check may also protect against code injection in
1569 # case of broken installations.
1570 if( !file_exists( $wgDiff ) ){
1571 wfDebug( "diff executable not found\n" );
1572 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1573 $format = new UnifiedDiffFormatter();
1574 return $format->format( $diffs );
1575 }
1576
1577 # Make temporary files
1578 $td = wfTempDir();
1579 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1580 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1581
1582 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1583 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1584
1585 // Get the diff of the two files
1586 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1587
1588 $h = popen( $cmd, 'r' );
1589
1590 $diff = '';
1591
1592 do {
1593 $data = fread( $h, 8192 );
1594 if ( strlen( $data ) == 0 ) {
1595 break;
1596 }
1597 $diff .= $data;
1598 } while ( true );
1599
1600 // Clean up
1601 pclose( $h );
1602 unlink( $oldtextName );
1603 unlink( $newtextName );
1604
1605 // Kill the --- and +++ lines. They're not useful.
1606 $diff_lines = explode( "\n", $diff );
1607 if (strpos( $diff_lines[0], '---' ) === 0) {
1608 unset($diff_lines[0]);
1609 }
1610 if (strpos( $diff_lines[1], '+++' ) === 0) {
1611 unset($diff_lines[1]);
1612 }
1613
1614 $diff = implode( "\n", $diff_lines );
1615
1616 return $diff;
1617 }
1618
1619 /**
1620 * A wrapper around the PHP function var_export().
1621 * Either print it or add it to the regular output ($wgOut).
1622 *
1623 * @param $var A PHP variable to dump.
1624 */
1625 function wfVarDump( $var ) {
1626 global $wgOut;
1627 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1628 if ( headers_sent() || !@is_object( $wgOut ) ) {
1629 print $s;
1630 } else {
1631 $wgOut->addHTML( $s );
1632 }
1633 }
1634
1635 /**
1636 * Provide a simple HTTP error.
1637 */
1638 function wfHttpError( $code, $label, $desc ) {
1639 global $wgOut;
1640 $wgOut->disable();
1641 header( "HTTP/1.0 $code $label" );
1642 header( "Status: $code $label" );
1643 $wgOut->sendCacheControl();
1644
1645 header( 'Content-type: text/html; charset=utf-8' );
1646 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1647 "<html><head><title>" .
1648 htmlspecialchars( $label ) .
1649 "</title></head><body><h1>" .
1650 htmlspecialchars( $label ) .
1651 "</h1><p>" .
1652 nl2br( htmlspecialchars( $desc ) ) .
1653 "</p></body></html>\n";
1654 }
1655
1656 /**
1657 * Clear away any user-level output buffers, discarding contents.
1658 *
1659 * Suitable for 'starting afresh', for instance when streaming
1660 * relatively large amounts of data without buffering, or wanting to
1661 * output image files without ob_gzhandler's compression.
1662 *
1663 * The optional $resetGzipEncoding parameter controls suppression of
1664 * the Content-Encoding header sent by ob_gzhandler; by default it
1665 * is left. See comments for wfClearOutputBuffers() for why it would
1666 * be used.
1667 *
1668 * Note that some PHP configuration options may add output buffer
1669 * layers which cannot be removed; these are left in place.
1670 *
1671 * @param $resetGzipEncoding Bool
1672 */
1673 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1674 if( $resetGzipEncoding ) {
1675 // Suppress Content-Encoding and Content-Length
1676 // headers from 1.10+s wfOutputHandler
1677 global $wgDisableOutputCompression;
1678 $wgDisableOutputCompression = true;
1679 }
1680 while( $status = ob_get_status() ) {
1681 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1682 // Probably from zlib.output_compression or other
1683 // PHP-internal setting which can't be removed.
1684 //
1685 // Give up, and hope the result doesn't break
1686 // output behavior.
1687 break;
1688 }
1689 if( !ob_end_clean() ) {
1690 // Could not remove output buffer handler; abort now
1691 // to avoid getting in some kind of infinite loop.
1692 break;
1693 }
1694 if( $resetGzipEncoding ) {
1695 if( $status['name'] == 'ob_gzhandler' ) {
1696 // Reset the 'Content-Encoding' field set by this handler
1697 // so we can start fresh.
1698 header( 'Content-Encoding:' );
1699 break;
1700 }
1701 }
1702 }
1703 }
1704
1705 /**
1706 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1707 *
1708 * Clear away output buffers, but keep the Content-Encoding header
1709 * produced by ob_gzhandler, if any.
1710 *
1711 * This should be used for HTTP 304 responses, where you need to
1712 * preserve the Content-Encoding header of the real result, but
1713 * also need to suppress the output of ob_gzhandler to keep to spec
1714 * and avoid breaking Firefox in rare cases where the headers and
1715 * body are broken over two packets.
1716 */
1717 function wfClearOutputBuffers() {
1718 wfResetOutputBuffers( false );
1719 }
1720
1721 /**
1722 * Converts an Accept-* header into an array mapping string values to quality
1723 * factors
1724 */
1725 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1726 # No arg means accept anything (per HTTP spec)
1727 if( !$accept ) {
1728 return array( $def => 1.0 );
1729 }
1730
1731 $prefs = array();
1732
1733 $parts = explode( ',', $accept );
1734
1735 foreach( $parts as $part ) {
1736 # FIXME: doesn't deal with params like 'text/html; level=1'
1737 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1738 $match = array();
1739 if( !isset( $qpart ) ) {
1740 $prefs[$value] = 1.0;
1741 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1742 $prefs[$value] = floatval($match[1]);
1743 }
1744 }
1745
1746 return $prefs;
1747 }
1748
1749 /**
1750 * Checks if a given MIME type matches any of the keys in the given
1751 * array. Basic wildcards are accepted in the array keys.
1752 *
1753 * Returns the matching MIME type (or wildcard) if a match, otherwise
1754 * NULL if no match.
1755 *
1756 * @param $type String
1757 * @param $avail Array
1758 * @return string
1759 * @private
1760 */
1761 function mimeTypeMatch( $type, $avail ) {
1762 if( array_key_exists($type, $avail) ) {
1763 return $type;
1764 } else {
1765 $parts = explode( '/', $type );
1766 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1767 return $parts[0] . '/*';
1768 } elseif( array_key_exists( '*/*', $avail ) ) {
1769 return '*/*';
1770 } else {
1771 return null;
1772 }
1773 }
1774 }
1775
1776 /**
1777 * Returns the 'best' match between a client's requested internet media types
1778 * and the server's list of available types. Each list should be an associative
1779 * array of type to preference (preference is a float between 0.0 and 1.0).
1780 * Wildcards in the types are acceptable.
1781 *
1782 * @param $cprefs Array: client's acceptable type list
1783 * @param $sprefs Array: server's offered types
1784 * @return string
1785 *
1786 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1787 * XXX: generalize to negotiate other stuff
1788 */
1789 function wfNegotiateType( $cprefs, $sprefs ) {
1790 $combine = array();
1791
1792 foreach( array_keys($sprefs) as $type ) {
1793 $parts = explode( '/', $type );
1794 if( $parts[1] != '*' ) {
1795 $ckey = mimeTypeMatch( $type, $cprefs );
1796 if( $ckey ) {
1797 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1798 }
1799 }
1800 }
1801
1802 foreach( array_keys( $cprefs ) as $type ) {
1803 $parts = explode( '/', $type );
1804 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1805 $skey = mimeTypeMatch( $type, $sprefs );
1806 if( $skey ) {
1807 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1808 }
1809 }
1810 }
1811
1812 $bestq = 0;
1813 $besttype = null;
1814
1815 foreach( array_keys( $combine ) as $type ) {
1816 if( $combine[$type] > $bestq ) {
1817 $besttype = $type;
1818 $bestq = $combine[$type];
1819 }
1820 }
1821
1822 return $besttype;
1823 }
1824
1825 /**
1826 * Array lookup
1827 * Returns an array where the values in the first array are replaced by the
1828 * values in the second array with the corresponding keys
1829 *
1830 * @return array
1831 */
1832 function wfArrayLookup( $a, $b ) {
1833 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1834 }
1835
1836 /**
1837 * Convenience function; returns MediaWiki timestamp for the present time.
1838 * @return string
1839 */
1840 function wfTimestampNow() {
1841 # return NOW
1842 return wfTimestamp( TS_MW, time() );
1843 }
1844
1845 /**
1846 * Reference-counted warning suppression
1847 */
1848 function wfSuppressWarnings( $end = false ) {
1849 static $suppressCount = 0;
1850 static $originalLevel = false;
1851
1852 if ( $end ) {
1853 if ( $suppressCount ) {
1854 --$suppressCount;
1855 if ( !$suppressCount ) {
1856 error_reporting( $originalLevel );
1857 }
1858 }
1859 } else {
1860 if ( !$suppressCount ) {
1861 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1862 }
1863 ++$suppressCount;
1864 }
1865 }
1866
1867 /**
1868 * Restore error level to previous value
1869 */
1870 function wfRestoreWarnings() {
1871 wfSuppressWarnings( true );
1872 }
1873
1874 # Autodetect, convert and provide timestamps of various types
1875
1876 /**
1877 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1878 */
1879 define('TS_UNIX', 0);
1880
1881 /**
1882 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1883 */
1884 define('TS_MW', 1);
1885
1886 /**
1887 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1888 */
1889 define('TS_DB', 2);
1890
1891 /**
1892 * RFC 2822 format, for E-mail and HTTP headers
1893 */
1894 define('TS_RFC2822', 3);
1895
1896 /**
1897 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1898 *
1899 * This is used by Special:Export
1900 */
1901 define('TS_ISO_8601', 4);
1902
1903 /**
1904 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1905 *
1906 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1907 * DateTime tag and page 36 for the DateTimeOriginal and
1908 * DateTimeDigitized tags.
1909 */
1910 define('TS_EXIF', 5);
1911
1912 /**
1913 * Oracle format time.
1914 */
1915 define('TS_ORACLE', 6);
1916
1917 /**
1918 * Postgres format time.
1919 */
1920 define('TS_POSTGRES', 7);
1921
1922 /**
1923 * DB2 format time
1924 */
1925 define('TS_DB2', 8);
1926
1927 /**
1928 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
1929 * function will autodetect which format is supplied and act
1930 * accordingly.
1931 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
1932 * @return String: in the format specified in $outputtype
1933 */
1934 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1935 $uts = 0;
1936 $da = array();
1937 if ($ts==0) {
1938 $uts=time();
1939 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1940 # TS_DB
1941 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1942 # TS_EXIF
1943 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1944 # TS_MW
1945 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1946 # TS_UNIX
1947 $uts = $ts;
1948 } elseif (preg_match('/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts)) {
1949 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
1950 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1951 str_replace("+00:00", "UTC", $ts)));
1952 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1953 # TS_ISO_8601
1954 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1955 # TS_POSTGRES
1956 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1957 # TS_POSTGRES
1958 } else {
1959 # Bogus value; fall back to the epoch...
1960 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1961 $uts = 0;
1962 }
1963
1964 if (count( $da ) ) {
1965 // Warning! gmmktime() acts oddly if the month or day is set to 0
1966 // We may want to handle that explicitly at some point
1967 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1968 (int)$da[2],(int)$da[3],(int)$da[1]);
1969 }
1970
1971 switch($outputtype) {
1972 case TS_UNIX:
1973 return $uts;
1974 case TS_MW:
1975 return gmdate( 'YmdHis', $uts );
1976 case TS_DB:
1977 return gmdate( 'Y-m-d H:i:s', $uts );
1978 case TS_ISO_8601:
1979 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1980 // This shouldn't ever be used, but is included for completeness
1981 case TS_EXIF:
1982 return gmdate( 'Y:m:d H:i:s', $uts );
1983 case TS_RFC2822:
1984 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1985 case TS_ORACLE:
1986 return gmdate( 'd-m-Y H:i:s.000000', $uts);
1987 //return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1988 case TS_POSTGRES:
1989 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1990 case TS_DB2:
1991 return gmdate( 'Y-m-d H:i:s', $uts);
1992 default:
1993 throw new MWException( 'wfTimestamp() called with illegal output type.');
1994 }
1995 }
1996
1997 /**
1998 * Return a formatted timestamp, or null if input is null.
1999 * For dealing with nullable timestamp columns in the database.
2000 * @param $outputtype Integer
2001 * @param $ts String
2002 * @return String
2003 */
2004 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2005 if( is_null( $ts ) ) {
2006 return null;
2007 } else {
2008 return wfTimestamp( $outputtype, $ts );
2009 }
2010 }
2011
2012 /**
2013 * Check if the operating system is Windows
2014 *
2015 * @return Bool: true if it's Windows, False otherwise.
2016 */
2017 function wfIsWindows() {
2018 if (substr(php_uname(), 0, 7) == 'Windows') {
2019 return true;
2020 } else {
2021 return false;
2022 }
2023 }
2024
2025 /**
2026 * Swap two variables
2027 */
2028 function swap( &$x, &$y ) {
2029 $z = $x;
2030 $x = $y;
2031 $y = $z;
2032 }
2033
2034 function wfGetCachedNotice( $name ) {
2035 global $wgOut, $wgRenderHashAppend, $parserMemc;
2036 $fname = 'wfGetCachedNotice';
2037 wfProfileIn( $fname );
2038
2039 $needParse = false;
2040
2041 if( $name === 'default' ) {
2042 // special case
2043 global $wgSiteNotice;
2044 $notice = $wgSiteNotice;
2045 if( empty( $notice ) ) {
2046 wfProfileOut( $fname );
2047 return false;
2048 }
2049 } else {
2050 $notice = wfMsgForContentNoTrans( $name );
2051 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
2052 wfProfileOut( $fname );
2053 return( false );
2054 }
2055 }
2056
2057 // Use the extra hash appender to let eg SSL variants separately cache.
2058 $key = wfMemcKey( $name . $wgRenderHashAppend );
2059 $cachedNotice = $parserMemc->get( $key );
2060 if( is_array( $cachedNotice ) ) {
2061 if( md5( $notice ) == $cachedNotice['hash'] ) {
2062 $notice = $cachedNotice['html'];
2063 } else {
2064 $needParse = true;
2065 }
2066 } else {
2067 $needParse = true;
2068 }
2069
2070 if( $needParse ) {
2071 if( is_object( $wgOut ) ) {
2072 $parsed = $wgOut->parse( $notice );
2073 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
2074 $notice = $parsed;
2075 } else {
2076 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
2077 $notice = '';
2078 }
2079 }
2080
2081 wfProfileOut( $fname );
2082 return $notice;
2083 }
2084
2085 function wfGetNamespaceNotice() {
2086 global $wgTitle;
2087
2088 # Paranoia
2089 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
2090 return "";
2091
2092 $fname = 'wfGetNamespaceNotice';
2093 wfProfileIn( $fname );
2094
2095 $key = "namespacenotice-" . $wgTitle->getNsText();
2096 $namespaceNotice = wfGetCachedNotice( $key );
2097 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
2098 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
2099 } else {
2100 $namespaceNotice = "";
2101 }
2102
2103 wfProfileOut( $fname );
2104 return $namespaceNotice;
2105 }
2106
2107 function wfGetSiteNotice() {
2108 global $wgUser, $wgSiteNotice;
2109 $fname = 'wfGetSiteNotice';
2110 wfProfileIn( $fname );
2111 $siteNotice = '';
2112
2113 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
2114 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
2115 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2116 } else {
2117 $anonNotice = wfGetCachedNotice( 'anonnotice' );
2118 if( !$anonNotice ) {
2119 $siteNotice = wfGetCachedNotice( 'sitenotice' );
2120 } else {
2121 $siteNotice = $anonNotice;
2122 }
2123 }
2124 if( !$siteNotice ) {
2125 $siteNotice = wfGetCachedNotice( 'default' );
2126 }
2127 }
2128
2129 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
2130 wfProfileOut( $fname );
2131 return $siteNotice;
2132 }
2133
2134 /**
2135 * BC wrapper for MimeMagic::singleton()
2136 * @deprecated
2137 */
2138 function &wfGetMimeMagic() {
2139 return MimeMagic::singleton();
2140 }
2141
2142 /**
2143 * Tries to get the system directory for temporary files. For PHP >= 5.2.1,
2144 * we'll use sys_get_temp_dir(). The TMPDIR, TMP, and TEMP environment
2145 * variables are then checked in sequence, and if none are set /tmp is
2146 * returned as the generic Unix default.
2147 *
2148 * NOTE: When possible, use the tempfile() function to create temporary
2149 * files to avoid race conditions on file creation, etc.
2150 *
2151 * @return String
2152 */
2153 function wfTempDir() {
2154 if( function_exists( 'sys_get_temp_dir' ) ) {
2155 return sys_get_temp_dir();
2156 }
2157 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2158 $tmp = getenv( $var );
2159 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2160 return $tmp;
2161 }
2162 }
2163 # Hope this is Unix of some kind!
2164 return '/tmp';
2165 }
2166
2167 /**
2168 * Make directory, and make all parent directories if they don't exist
2169 *
2170 * @param $dir String: full path to directory to create
2171 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2172 * @param $caller String: optional caller param for debugging.
2173 * @return bool
2174 */
2175 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2176 global $wgDirectoryMode;
2177
2178 if ( !is_null( $caller ) ) {
2179 wfDebug( "$caller: called wfMkdirParents($dir)" );
2180 }
2181
2182 if( strval( $dir ) === '' || file_exists( $dir ) )
2183 return true;
2184
2185 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2186
2187 if ( is_null( $mode ) )
2188 $mode = $wgDirectoryMode;
2189
2190 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2191 if( !$ok ) {
2192 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2193 trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
2194 }
2195 return $ok;
2196 }
2197
2198 /**
2199 * Increment a statistics counter
2200 */
2201 function wfIncrStats( $key ) {
2202 global $wgStatsMethod;
2203
2204 if( $wgStatsMethod == 'udp' ) {
2205 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
2206 static $socket;
2207 if (!$socket) {
2208 $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
2209 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
2210 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2211 }
2212 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
2213 @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
2214 } elseif( $wgStatsMethod == 'cache' ) {
2215 global $wgMemc;
2216 $key = wfMemcKey( 'stats', $key );
2217 if ( is_null( $wgMemc->incr( $key ) ) ) {
2218 $wgMemc->add( $key, 1 );
2219 }
2220 } else {
2221 // Disabled
2222 }
2223 }
2224
2225 /**
2226 * @param $nr Mixed: the number to format
2227 * @param $acc Integer: the number of digits after the decimal point, default 2
2228 * @param $round Boolean: whether or not to round the value, default true
2229 * @return float
2230 */
2231 function wfPercent( $nr, $acc = 2, $round = true ) {
2232 $ret = sprintf( "%.${acc}f", $nr );
2233 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2234 }
2235
2236 /**
2237 * Encrypt a username/password.
2238 *
2239 * @param $userid Integer: ID of the user
2240 * @param $password String: password of the user
2241 * @return String: hashed password
2242 * @deprecated Use User::crypt() or User::oldCrypt() instead
2243 */
2244 function wfEncryptPassword( $userid, $password ) {
2245 wfDeprecated(__FUNCTION__);
2246 # Just wrap around User::oldCrypt()
2247 return User::oldCrypt($password, $userid);
2248 }
2249
2250 /**
2251 * Appends to second array if $value differs from that in $default
2252 */
2253 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2254 if ( is_null( $changed ) ) {
2255 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2256 }
2257 if ( $default[$key] !== $value ) {
2258 $changed[$key] = $value;
2259 }
2260 }
2261
2262 /**
2263 * Since wfMsg() and co suck, they don't return false if the message key they
2264 * looked up didn't exist but a XHTML string, this function checks for the
2265 * nonexistance of messages by looking at wfMsg() output
2266 *
2267 * @param $msg String: the message key looked up
2268 * @param $wfMsgOut String: the output of wfMsg*()
2269 * @return Boolean
2270 */
2271 function wfEmptyMsg( $msg, $wfMsgOut ) {
2272 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2273 }
2274
2275 /**
2276 * Find out whether or not a mixed variable exists in a string
2277 *
2278 * @param $needle String
2279 * @param $str String
2280 * @return Boolean
2281 */
2282 function in_string( $needle, $str ) {
2283 return strpos( $str, $needle ) !== false;
2284 }
2285
2286 function wfSpecialList( $page, $details ) {
2287 global $wgContLang;
2288 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
2289 return $page . $details;
2290 }
2291
2292 /**
2293 * Returns a regular expression of url protocols
2294 *
2295 * @return String
2296 */
2297 function wfUrlProtocols() {
2298 global $wgUrlProtocols;
2299
2300 static $retval = null;
2301 if ( !is_null( $retval ) )
2302 return $retval;
2303
2304 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2305 // with LocalSettings files from 1.5
2306 if ( is_array( $wgUrlProtocols ) ) {
2307 $protocols = array();
2308 foreach ($wgUrlProtocols as $protocol)
2309 $protocols[] = preg_quote( $protocol, '/' );
2310
2311 $retval = implode( '|', $protocols );
2312 } else {
2313 $retval = $wgUrlProtocols;
2314 }
2315 return $retval;
2316 }
2317
2318 /**
2319 * Safety wrapper around ini_get() for boolean settings.
2320 * The values returned from ini_get() are pre-normalized for settings
2321 * set via php.ini or php_flag/php_admin_flag... but *not*
2322 * for those set via php_value/php_admin_value.
2323 *
2324 * It's fairly common for people to use php_value instead of php_flag,
2325 * which can leave you with an 'off' setting giving a false positive
2326 * for code that just takes the ini_get() return value as a boolean.
2327 *
2328 * To make things extra interesting, setting via php_value accepts
2329 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2330 * Unrecognized values go false... again opposite PHP's own coercion
2331 * from string to bool.
2332 *
2333 * Luckily, 'properly' set settings will always come back as '0' or '1',
2334 * so we only have to worry about them and the 'improper' settings.
2335 *
2336 * I frickin' hate PHP... :P
2337 *
2338 * @param $setting String
2339 * @return Bool
2340 */
2341 function wfIniGetBool( $setting ) {
2342 $val = ini_get( $setting );
2343 // 'on' and 'true' can't have whitespace around them, but '1' can.
2344 return strtolower( $val ) == 'on'
2345 || strtolower( $val ) == 'true'
2346 || strtolower( $val ) == 'yes'
2347 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2348 }
2349
2350 /**
2351 * Execute a shell command, with time and memory limits mirrored from the PHP
2352 * configuration if supported.
2353 * @param $cmd Command line, properly escaped for shell.
2354 * @param &$retval optional, will receive the program's exit code.
2355 * (non-zero is usually failure)
2356 * @return collected stdout as a string (trailing newlines stripped)
2357 */
2358 function wfShellExec( $cmd, &$retval=null ) {
2359 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2360
2361 static $disabled;
2362 if ( is_null( $disabled ) ) {
2363 $disabled = false;
2364 if( wfIniGetBool( 'safe_mode' ) ) {
2365 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2366 $disabled = true;
2367 }
2368 $functions = explode( ',', ini_get( 'disable_functions' ) );
2369 $functions = array_map( 'trim', $functions );
2370 $functions = array_map( 'strtolower', $functions );
2371 if ( in_array( 'passthru', $functions ) ) {
2372 wfDebug( "passthru is in disabled_functions\n" );
2373 $disabled = true;
2374 }
2375 }
2376 if ( $disabled ) {
2377 $retval = 1;
2378 return "Unable to run external programs in safe mode.";
2379 }
2380
2381 wfInitShellLocale();
2382
2383 if ( php_uname( 's' ) == 'Linux' ) {
2384 $time = intval( $wgMaxShellTime );
2385 $mem = intval( $wgMaxShellMemory );
2386 $filesize = intval( $wgMaxShellFileSize );
2387
2388 if ( $time > 0 && $mem > 0 ) {
2389 $script = "$IP/bin/ulimit4.sh";
2390 if ( is_executable( $script ) ) {
2391 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2392 }
2393 }
2394 } elseif ( php_uname( 's' ) == 'Windows NT' &&
2395 version_compare( PHP_VERSION, '5.3.0', '<' ) )
2396 {
2397 # This is a hack to work around PHP's flawed invocation of cmd.exe
2398 # http://news.php.net/php.internals/21796
2399 # Which is fixed in 5.3.0 :)
2400 $cmd = '"' . $cmd . '"';
2401 }
2402 wfDebug( "wfShellExec: $cmd\n" );
2403
2404 $retval = 1; // error by default?
2405 ob_start();
2406 passthru( $cmd, $retval );
2407 $output = ob_get_contents();
2408 ob_end_clean();
2409
2410 if ( $retval == 127 ) {
2411 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2412 }
2413 return $output;
2414 }
2415
2416 /**
2417 * Workaround for http://bugs.php.net/bug.php?id=45132
2418 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2419 */
2420 function wfInitShellLocale() {
2421 static $done = false;
2422 if ( $done ) return;
2423 $done = true;
2424 global $wgShellLocale;
2425 if ( !wfIniGetBool( 'safe_mode' ) ) {
2426 putenv( "LC_CTYPE=$wgShellLocale" );
2427 setlocale( LC_CTYPE, $wgShellLocale );
2428 }
2429 }
2430
2431 /**
2432 * This function works like "use VERSION" in Perl, the program will die with a
2433 * backtrace if the current version of PHP is less than the version provided
2434 *
2435 * This is useful for extensions which due to their nature are not kept in sync
2436 * with releases, and might depend on other versions of PHP than the main code
2437 *
2438 * Note: PHP might die due to parsing errors in some cases before it ever
2439 * manages to call this function, such is life
2440 *
2441 * @see perldoc -f use
2442 *
2443 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2444 * a float
2445 */
2446 function wfUsePHP( $req_ver ) {
2447 $php_ver = PHP_VERSION;
2448
2449 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2450 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2451 }
2452
2453 /**
2454 * This function works like "use VERSION" in Perl except it checks the version
2455 * of MediaWiki, the program will die with a backtrace if the current version
2456 * of MediaWiki is less than the version provided.
2457 *
2458 * This is useful for extensions which due to their nature are not kept in sync
2459 * with releases
2460 *
2461 * @see perldoc -f use
2462 *
2463 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2464 * a float
2465 */
2466 function wfUseMW( $req_ver ) {
2467 global $wgVersion;
2468
2469 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2470 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2471 }
2472
2473 /**
2474 * @deprecated use StringUtils::escapeRegexReplacement
2475 */
2476 function wfRegexReplacement( $string ) {
2477 return StringUtils::escapeRegexReplacement( $string );
2478 }
2479
2480 /**
2481 * Return the final portion of a pathname.
2482 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2483 * http://bugs.php.net/bug.php?id=33898
2484 *
2485 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2486 * We'll consider it so always, as we don't want \s in our Unix paths either.
2487 *
2488 * @param $path String
2489 * @param $suffix String: to remove if present
2490 * @return String
2491 */
2492 function wfBaseName( $path, $suffix='' ) {
2493 $encSuffix = ($suffix == '')
2494 ? ''
2495 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2496 $matches = array();
2497 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2498 return $matches[1];
2499 } else {
2500 return '';
2501 }
2502 }
2503
2504 /**
2505 * Generate a relative path name to the given file.
2506 * May explode on non-matching case-insensitive paths,
2507 * funky symlinks, etc.
2508 *
2509 * @param $path String: absolute destination path including target filename
2510 * @param $from String: Absolute source path, directory only
2511 * @return String
2512 */
2513 function wfRelativePath( $path, $from ) {
2514 // Normalize mixed input on Windows...
2515 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2516 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2517
2518 // Trim trailing slashes -- fix for drive root
2519 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2520 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2521
2522 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2523 $against = explode( DIRECTORY_SEPARATOR, $from );
2524
2525 if( $pieces[0] !== $against[0] ) {
2526 // Non-matching Windows drive letters?
2527 // Return a full path.
2528 return $path;
2529 }
2530
2531 // Trim off common prefix
2532 while( count( $pieces ) && count( $against )
2533 && $pieces[0] == $against[0] ) {
2534 array_shift( $pieces );
2535 array_shift( $against );
2536 }
2537
2538 // relative dots to bump us to the parent
2539 while( count( $against ) ) {
2540 array_unshift( $pieces, '..' );
2541 array_shift( $against );
2542 }
2543
2544 array_push( $pieces, wfBaseName( $path ) );
2545
2546 return implode( DIRECTORY_SEPARATOR, $pieces );
2547 }
2548
2549 /**
2550 * Backwards array plus for people who haven't bothered to read the PHP manual
2551 * XXX: will not darn your socks for you.
2552 *
2553 * @param $array1 Array
2554 * @param [$array2, [...]] Arrays
2555 * @return Array
2556 */
2557 function wfArrayMerge( $array1/* ... */ ) {
2558 $args = func_get_args();
2559 $args = array_reverse( $args, true );
2560 $out = array();
2561 foreach ( $args as $arg ) {
2562 $out += $arg;
2563 }
2564 return $out;
2565 }
2566
2567 /**
2568 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2569 * e.g.
2570 * wfMergeErrorArrays(
2571 * array( array( 'x' ) ),
2572 * array( array( 'x', '2' ) ),
2573 * array( array( 'x' ) ),
2574 * array( array( 'y') )
2575 * );
2576 * returns:
2577 * array(
2578 * array( 'x', '2' ),
2579 * array( 'x' ),
2580 * array( 'y' )
2581 * )
2582 */
2583 function wfMergeErrorArrays( /*...*/ ) {
2584 $args = func_get_args();
2585 $out = array();
2586 foreach ( $args as $errors ) {
2587 foreach ( $errors as $params ) {
2588 # FIXME: sometimes get nested arrays for $params,
2589 # which leads to E_NOTICEs
2590 $spec = implode( "\t", $params );
2591 $out[$spec] = $params;
2592 }
2593 }
2594 return array_values( $out );
2595 }
2596
2597 /**
2598 * parse_url() work-alike, but non-broken. Differences:
2599 *
2600 * 1) Does not raise warnings on bad URLs (just returns false)
2601 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2602 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2603 *
2604 * @param $url String: a URL to parse
2605 * @return Array: bits of the URL in an associative array, per PHP docs
2606 */
2607 function wfParseUrl( $url ) {
2608 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2609 wfSuppressWarnings();
2610 $bits = parse_url( $url );
2611 wfRestoreWarnings();
2612 if ( !$bits ) {
2613 return false;
2614 }
2615
2616 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2617 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2618 $bits['delimiter'] = '://';
2619 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2620 $bits['delimiter'] = ':';
2621 // parse_url detects for news: and mailto: the host part of an url as path
2622 // We have to correct this wrong detection
2623 if ( isset ( $bits['path'] ) ) {
2624 $bits['host'] = $bits['path'];
2625 $bits['path'] = '';
2626 }
2627 } else {
2628 return false;
2629 }
2630
2631 return $bits;
2632 }
2633
2634 /**
2635 * Make a URL index, appropriate for the el_index field of externallinks.
2636 */
2637 function wfMakeUrlIndex( $url ) {
2638 $bits = wfParseUrl( $url );
2639
2640 // Reverse the labels in the hostname, convert to lower case
2641 // For emails reverse domainpart only
2642 if ( $bits['scheme'] == 'mailto' ) {
2643 $mailparts = explode( '@', $bits['host'], 2 );
2644 if ( count($mailparts) === 2 ) {
2645 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2646 } else {
2647 // No domain specified, don't mangle it
2648 $domainpart = '';
2649 }
2650 $reversedHost = $domainpart . '@' . $mailparts[0];
2651 } else {
2652 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2653 }
2654 // Add an extra dot to the end
2655 // Why? Is it in wrong place in mailto links?
2656 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2657 $reversedHost .= '.';
2658 }
2659 // Reconstruct the pseudo-URL
2660 $prot = $bits['scheme'];
2661 $index = $prot . $bits['delimiter'] . $reversedHost;
2662 // Leave out user and password. Add the port, path, query and fragment
2663 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2664 if ( isset( $bits['path'] ) ) {
2665 $index .= $bits['path'];
2666 } else {
2667 $index .= '/';
2668 }
2669 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2670 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2671 return $index;
2672 }
2673
2674 /**
2675 * Do any deferred updates and clear the list
2676 * TODO: This could be in Wiki.php if that class made any sense at all
2677 */
2678 function wfDoUpdates()
2679 {
2680 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2681 foreach ( $wgDeferredUpdateList as $update ) {
2682 $update->doUpdate();
2683 }
2684 foreach ( $wgPostCommitUpdateList as $update ) {
2685 $update->doUpdate();
2686 }
2687 $wgDeferredUpdateList = array();
2688 $wgPostCommitUpdateList = array();
2689 }
2690
2691 /**
2692 * @deprecated use StringUtils::explodeMarkup
2693 */
2694 function wfExplodeMarkup( $separator, $text ) {
2695 return StringUtils::explodeMarkup( $separator, $text );
2696 }
2697
2698 /**
2699 * Convert an arbitrarily-long digit string from one numeric base
2700 * to another, optionally zero-padding to a minimum column width.
2701 *
2702 * Supports base 2 through 36; digit values 10-36 are represented
2703 * as lowercase letters a-z. Input is case-insensitive.
2704 *
2705 * @param $input String: of digits
2706 * @param $sourceBase Integer: 2-36
2707 * @param $destBase Integer: 2-36
2708 * @param $pad Integer: 1 or greater
2709 * @param $lowercase Boolean
2710 * @return String or false on invalid input
2711 */
2712 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2713 $input = strval( $input );
2714 if( $sourceBase < 2 ||
2715 $sourceBase > 36 ||
2716 $destBase < 2 ||
2717 $destBase > 36 ||
2718 $pad < 1 ||
2719 $sourceBase != intval( $sourceBase ) ||
2720 $destBase != intval( $destBase ) ||
2721 $pad != intval( $pad ) ||
2722 !is_string( $input ) ||
2723 $input == '' ) {
2724 return false;
2725 }
2726 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2727 $inDigits = array();
2728 $outChars = '';
2729
2730 // Decode and validate input string
2731 $input = strtolower( $input );
2732 for( $i = 0; $i < strlen( $input ); $i++ ) {
2733 $n = strpos( $digitChars, $input{$i} );
2734 if( $n === false || $n > $sourceBase ) {
2735 return false;
2736 }
2737 $inDigits[] = $n;
2738 }
2739
2740 // Iterate over the input, modulo-ing out an output digit
2741 // at a time until input is gone.
2742 while( count( $inDigits ) ) {
2743 $work = 0;
2744 $workDigits = array();
2745
2746 // Long division...
2747 foreach( $inDigits as $digit ) {
2748 $work *= $sourceBase;
2749 $work += $digit;
2750
2751 if( $work < $destBase ) {
2752 // Gonna need to pull another digit.
2753 if( count( $workDigits ) ) {
2754 // Avoid zero-padding; this lets us find
2755 // the end of the input very easily when
2756 // length drops to zero.
2757 $workDigits[] = 0;
2758 }
2759 } else {
2760 // Finally! Actual division!
2761 $workDigits[] = intval( $work / $destBase );
2762
2763 // Isn't it annoying that most programming languages
2764 // don't have a single divide-and-remainder operator,
2765 // even though the CPU implements it that way?
2766 $work = $work % $destBase;
2767 }
2768 }
2769
2770 // All that division leaves us with a remainder,
2771 // which is conveniently our next output digit.
2772 $outChars .= $digitChars[$work];
2773
2774 // And we continue!
2775 $inDigits = $workDigits;
2776 }
2777
2778 while( strlen( $outChars ) < $pad ) {
2779 $outChars .= '0';
2780 }
2781
2782 return strrev( $outChars );
2783 }
2784
2785 /**
2786 * Create an object with a given name and an array of construct parameters
2787 * @param $name String
2788 * @param $p Array: parameters
2789 */
2790 function wfCreateObject( $name, $p ){
2791 $p = array_values( $p );
2792 switch ( count( $p ) ) {
2793 case 0:
2794 return new $name;
2795 case 1:
2796 return new $name( $p[0] );
2797 case 2:
2798 return new $name( $p[0], $p[1] );
2799 case 3:
2800 return new $name( $p[0], $p[1], $p[2] );
2801 case 4:
2802 return new $name( $p[0], $p[1], $p[2], $p[3] );
2803 case 5:
2804 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2805 case 6:
2806 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2807 default:
2808 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2809 }
2810 }
2811
2812 /**
2813 * Alias for modularized function
2814 * @deprecated Use Http::isLocalURL() instead
2815 */
2816 function wfIsLocalURL( $url ) {
2817 wfDeprecated(__FUNCTION__);
2818 return Http::isLocalURL( $url );
2819 }
2820
2821 function wfHttpOnlySafe() {
2822 global $wgHttpOnlyBlacklist;
2823 if( !version_compare("5.2", PHP_VERSION, "<") )
2824 return false;
2825
2826 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2827 foreach( $wgHttpOnlyBlacklist as $regex ) {
2828 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2829 return false;
2830 }
2831 }
2832 }
2833
2834 return true;
2835 }
2836
2837 /**
2838 * Initialise php session
2839 */
2840 function wfSetupSession() {
2841 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
2842 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
2843 if( $wgSessionsInMemcached ) {
2844 require_once( 'MemcachedSessions.php' );
2845 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
2846 # Only set this if $wgSessionHandler isn't null and session.save_handler
2847 # hasn't already been set to the desired value (that causes errors)
2848 ini_set ( 'session.save_handler', $wgSessionHandler );
2849 }
2850 $httpOnlySafe = wfHttpOnlySafe();
2851 wfDebugLog( 'cookie',
2852 'session_set_cookie_params: "' . implode( '", "',
2853 array(
2854 0,
2855 $wgCookiePath,
2856 $wgCookieDomain,
2857 $wgCookieSecure,
2858 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2859 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2860 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2861 } else {
2862 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2863 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2864 }
2865 session_cache_limiter( 'private, must-revalidate' );
2866 wfSuppressWarnings();
2867 session_start();
2868 wfRestoreWarnings();
2869 }
2870
2871 /**
2872 * Get an object from the precompiled serialized directory
2873 *
2874 * @return Mixed: the variable on success, false on failure
2875 */
2876 function wfGetPrecompiledData( $name ) {
2877 global $IP;
2878
2879 $file = "$IP/serialized/$name";
2880 if ( file_exists( $file ) ) {
2881 $blob = file_get_contents( $file );
2882 if ( $blob ) {
2883 return unserialize( $blob );
2884 }
2885 }
2886 return false;
2887 }
2888
2889 function wfGetCaller( $level = 2 ) {
2890 $backtrace = wfDebugBacktrace();
2891 if ( isset( $backtrace[$level] ) ) {
2892 return wfFormatStackFrame($backtrace[$level]);
2893 } else {
2894 $caller = 'unknown';
2895 }
2896 return $caller;
2897 }
2898
2899 /**
2900 * Return a string consisting all callers in stack, somewhat useful sometimes
2901 * for profiling specific points
2902 */
2903 function wfGetAllCallers() {
2904 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2905 }
2906
2907 /**
2908 * Return a string representation of frame
2909 */
2910 function wfFormatStackFrame($frame) {
2911 return isset( $frame["class"] )?
2912 $frame["class"]."::".$frame["function"]:
2913 $frame["function"];
2914 }
2915
2916 /**
2917 * Get a cache key
2918 */
2919 function wfMemcKey( /*... */ ) {
2920 $args = func_get_args();
2921 $key = wfWikiID() . ':' . implode( ':', $args );
2922 $key = str_replace( ' ', '_', $key );
2923 return $key;
2924 }
2925
2926 /**
2927 * Get a cache key for a foreign DB
2928 */
2929 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2930 $args = array_slice( func_get_args(), 2 );
2931 if ( $prefix ) {
2932 $key = "$db-$prefix:" . implode( ':', $args );
2933 } else {
2934 $key = $db . ':' . implode( ':', $args );
2935 }
2936 return $key;
2937 }
2938
2939 /**
2940 * Get an ASCII string identifying this wiki
2941 * This is used as a prefix in memcached keys
2942 */
2943 function wfWikiID() {
2944 global $wgDBprefix, $wgDBname;
2945 if ( $wgDBprefix ) {
2946 return "$wgDBname-$wgDBprefix";
2947 } else {
2948 return $wgDBname;
2949 }
2950 }
2951
2952 /**
2953 * Split a wiki ID into DB name and table prefix
2954 */
2955 function wfSplitWikiID( $wiki ) {
2956 $bits = explode( '-', $wiki, 2 );
2957 if ( count( $bits ) < 2 ) {
2958 $bits[] = '';
2959 }
2960 return $bits;
2961 }
2962
2963 /*
2964 * Get a Database object.
2965 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
2966 * master (for write queries), DB_SLAVE for potentially lagged read
2967 * queries, or an integer >= 0 for a particular server.
2968 *
2969 * @param $groups Mixed: query groups. An array of group names that this query
2970 * belongs to. May contain a single string if the query is only
2971 * in one group.
2972 *
2973 * @param $wiki String: the wiki ID, or false for the current wiki
2974 *
2975 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2976 * will always return the same object, unless the underlying connection or load
2977 * balancer is manually destroyed.
2978 */
2979 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2980 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2981 }
2982
2983 /**
2984 * Get a load balancer object.
2985 *
2986 * @param $wiki String: wiki ID, or false for the current wiki
2987 * @return LoadBalancer
2988 */
2989 function wfGetLB( $wiki = false ) {
2990 return wfGetLBFactory()->getMainLB( $wiki );
2991 }
2992
2993 /**
2994 * Get the load balancer factory object
2995 */
2996 function &wfGetLBFactory() {
2997 return LBFactory::singleton();
2998 }
2999
3000 /**
3001 * Find a file.
3002 * Shortcut for RepoGroup::singleton()->findFile()
3003 * @param $title Either a string or Title object
3004 * @param $options Associative array of options:
3005 * time: requested time for an archived image, or false for the
3006 * current version. An image object will be returned which was
3007 * created at the specified time.
3008 *
3009 * ignoreRedirect: If true, do not follow file redirects
3010 *
3011 * private: If true, return restricted (deleted) files if the current
3012 * user is allowed to view them. Otherwise, such files will not
3013 * be found.
3014 *
3015 * bypassCache: If true, do not use the process-local cache of File objects
3016 *
3017 * @return File, or false if the file does not exist
3018 */
3019 function wfFindFile( $title, $options = array() ) {
3020 return RepoGroup::singleton()->findFile( $title, $options );
3021 }
3022
3023 /**
3024 * Get an object referring to a locally registered file.
3025 * Returns a valid placeholder object if the file does not exist.
3026 * @param $title Either a string or Title object
3027 * @return File, or null if passed an invalid Title
3028 */
3029 function wfLocalFile( $title ) {
3030 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3031 }
3032
3033 /**
3034 * Should low-performance queries be disabled?
3035 *
3036 * @return Boolean
3037 */
3038 function wfQueriesMustScale() {
3039 global $wgMiserMode;
3040 return $wgMiserMode
3041 || ( SiteStats::pages() > 100000
3042 && SiteStats::edits() > 1000000
3043 && SiteStats::users() > 10000 );
3044 }
3045
3046 /**
3047 * Get the path to a specified script file, respecting file
3048 * extensions; this is a wrapper around $wgScriptExtension etc.
3049 *
3050 * @param $script String: script filename, sans extension
3051 * @return String
3052 */
3053 function wfScript( $script = 'index' ) {
3054 global $wgScriptPath, $wgScriptExtension;
3055 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3056 }
3057 /**
3058 * Get the script url.
3059 *
3060 * @return script url
3061 */
3062 function wfGetScriptUrl(){
3063 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3064 #
3065 # as it was called, minus the query string.
3066 #
3067 # Some sites use Apache rewrite rules to handle subdomains,
3068 # and have PHP set up in a weird way that causes PHP_SELF
3069 # to contain the rewritten URL instead of the one that the
3070 # outside world sees.
3071 #
3072 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3073 # provides containing the "before" URL.
3074 return $_SERVER['SCRIPT_NAME'];
3075 } else {
3076 return $_SERVER['URL'];
3077 }
3078 }
3079
3080 /**
3081 * Convenience function converts boolean values into "true"
3082 * or "false" (string) values
3083 *
3084 * @param $value Boolean
3085 * @return String
3086 */
3087 function wfBoolToStr( $value ) {
3088 return $value ? 'true' : 'false';
3089 }
3090
3091 /**
3092 * Load an extension messages file
3093 * @deprecated in 1.16 (warnings in 1.18, removed in ?)
3094 */
3095 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
3096 }
3097
3098 /**
3099 * Get a platform-independent path to the null file, e.g.
3100 * /dev/null
3101 *
3102 * @return string
3103 */
3104 function wfGetNull() {
3105 return wfIsWindows()
3106 ? 'NUL'
3107 : '/dev/null';
3108 }
3109
3110 /**
3111 * Displays a maxlag error
3112 *
3113 * @param $host String: server that lags the most
3114 * @param $lag Integer: maxlag (actual)
3115 * @param $maxLag Integer: maxlag (requested)
3116 */
3117 function wfMaxlagError( $host, $lag, $maxLag ) {
3118 global $wgShowHostnames;
3119 header( 'HTTP/1.1 503 Service Unavailable' );
3120 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
3121 header( 'X-Database-Lag: ' . intval( $lag ) );
3122 header( 'Content-Type: text/plain' );
3123 if( $wgShowHostnames ) {
3124 echo "Waiting for $host: $lag seconds lagged\n";
3125 } else {
3126 echo "Waiting for a database server: $lag seconds lagged\n";
3127 }
3128 }
3129
3130 /**
3131 * Throws a warning that $function is deprecated
3132 * @param $function String
3133 * @return null
3134 */
3135 function wfDeprecated( $function ) {
3136 static $functionsWarned = array();
3137 if ( !isset( $functionsWarned[$function] ) ) {
3138 $functionsWarned[$function] = true;
3139 wfWarn( "Use of $function is deprecated.", 2 );
3140 }
3141 }
3142
3143 /**
3144 * Send a warning either to the debug log or in a PHP error depending on
3145 * $wgDevelopmentWarnings
3146 *
3147 * @param $msg String: message to send
3148 * @param $callerOffset Integer: number of itmes to go back in the backtrace to
3149 * find the correct caller (1 = function calling wfWarn, ...)
3150 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3151 * is true
3152 */
3153 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
3154 $callers = wfDebugBacktrace();
3155 if( isset( $callers[$callerOffset+1] ) ){
3156 $callerfunc = $callers[$callerOffset+1];
3157 $callerfile = $callers[$callerOffset];
3158 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
3159 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3160 } else {
3161 $file = '(internal function)';
3162 }
3163 $func = '';
3164 if( isset( $callerfunc['class'] ) )
3165 $func .= $callerfunc['class'] . '::';
3166 $func .= @$callerfunc['function'];
3167 $msg .= " [Called from $func in $file]";
3168 }
3169
3170 global $wgDevelopmentWarnings;
3171 if ( $wgDevelopmentWarnings ) {
3172 trigger_error( $msg, $level );
3173 } else {
3174 wfDebug( "$msg\n" );
3175 }
3176 }
3177
3178 /**
3179 * Sleep until the worst slave's replication lag is less than or equal to
3180 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
3181 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3182 * a no-op if there are no slaves.
3183 *
3184 * Every time the function has to wait for a slave, it will print a message to
3185 * that effect (and then sleep for a little while), so it's probably not best
3186 * to use this outside maintenance scripts in its present form.
3187 *
3188 * @param $maxLag Integer
3189 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3190 * @return null
3191 */
3192 function wfWaitForSlaves( $maxLag, $wiki = false ) {
3193 if( $maxLag ) {
3194 $lb = wfGetLB( $wiki );
3195 list( $host, $lag ) = $lb->getMaxLag( $wiki );
3196 while( $lag > $maxLag ) {
3197 $name = @gethostbyaddr( $host );
3198 if( $name !== false ) {
3199 $host = $name;
3200 }
3201 print "Waiting for $host (lagged $lag seconds)...\n";
3202 sleep($maxLag);
3203 list( $host, $lag ) = $lb->getMaxLag();
3204 }
3205 }
3206 }
3207
3208 /**
3209 * Output some plain text in command-line mode or in the installer (updaters.inc).
3210 * Do not use it in any other context, its behaviour is subject to change.
3211 */
3212 function wfOut( $s ) {
3213 static $lineStarted = false;
3214 global $wgCommandLineMode;
3215 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
3216 echo $s;
3217 } else {
3218 echo htmlspecialchars( $s );
3219 }
3220 flush();
3221 }
3222
3223 /**
3224 * Count down from $n to zero on the terminal, with a one-second pause
3225 * between showing each number. For use in command-line scripts.
3226 */
3227 function wfCountDown( $n ) {
3228 for ( $i = $n; $i >= 0; $i-- ) {
3229 if ( $i != $n ) {
3230 echo str_repeat( "\x08", strlen( $i + 1 ) );
3231 }
3232 echo $i;
3233 flush();
3234 if ( $i ) {
3235 sleep( 1 );
3236 }
3237 }
3238 echo "\n";
3239 }
3240
3241 /** Generate a random 32-character hexadecimal token.
3242 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3243 * characters before hashing.
3244 */
3245 function wfGenerateToken( $salt = '' ) {
3246 $salt = serialize($salt);
3247
3248 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3249 }
3250
3251 /**
3252 * Replace all invalid characters with -
3253 * @param $name Mixed: filename to process
3254 */
3255 function wfStripIllegalFilenameChars( $name ) {
3256 global $wgIllegalFileChars;
3257 $name = wfBaseName( $name );
3258 $name = preg_replace("/[^".Title::legalChars()."]".($wgIllegalFileChars ? "|[".$wgIllegalFileChars."]":"")."/",'-',$name);
3259 return $name;
3260 }
3261
3262 /**
3263 * Insert array into another array after the specified *KEY*
3264 * @param $array Array: The array.
3265 * @param $insert Array: The array to insert.
3266 * @param $after Mixed: The key to insert after
3267 */
3268 function wfArrayInsertAfter( $array, $insert, $after ) {
3269 // Find the offset of the element to insert after.
3270 $keys = array_keys($array);
3271 $offsetByKey = array_flip( $keys );
3272
3273 $offset = $offsetByKey[$after];
3274
3275 // Insert at the specified offset
3276 $before = array_slice( $array, 0, $offset + 1, true );
3277 $after = array_slice( $array, $offset + 1, count($array)-$offset, true );
3278
3279 $output = $before + $insert + $after;
3280
3281 return $output;
3282 }
3283
3284 /* Recursively converts the parameter (an object) to an array with the same data */
3285 function wfObjectToArray( $object, $recursive = true ) {
3286 $array = array();
3287 foreach ( get_object_vars($object) as $key => $value ) {
3288 if ( is_object($value) && $recursive ) {
3289 $value = wfObjectToArray( $value );
3290 }
3291
3292 $array[$key] = $value;
3293 }
3294
3295 return $array;
3296 }
3297
3298 /**
3299 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3300 * @return Integer value memory was set to.
3301 */
3302
3303 function wfMemoryLimit () {
3304 global $wgMemoryLimit;
3305 $memlimit = wfShorthandToInteger( ini_get( "memory_limit" ) );
3306 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3307 if( $memlimit != -1 ) {
3308 if( $conflimit == -1 ) {
3309 wfDebug( "Removing PHP's memory limit\n" );
3310 wfSuppressWarnings();
3311 ini_set( "memory_limit", $conflimit );
3312 wfRestoreWarnings();
3313 return $conflimit;
3314 } elseif ( $conflimit > $memlimit ) {
3315 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3316 wfSuppressWarnings();
3317 ini_set( "memory_limit", $conflimit );
3318 wfRestoreWarnings();
3319 return $conflimit;
3320 }
3321 }
3322 return $memlimit;
3323 }
3324
3325 /**
3326 * Converts shorthand byte notation to integer form
3327 * @param $string String
3328 * @return Integer
3329 */
3330 function wfShorthandToInteger ( $string = '' ) {
3331 $string = trim($string);
3332 if( empty($string) ) { return -1; }
3333 $last = strtolower($string[strlen($string)-1]);
3334 $val = intval($string);
3335 switch($last) {
3336 case 'g':
3337 $val *= 1024;
3338 case 'm':
3339 $val *= 1024;
3340 case 'k':
3341 $val *= 1024;
3342 }
3343
3344 return $val;
3345 }
3346
3347 /* Get the normalised IETF language tag
3348 * @param $code String: The language code.
3349 * @return $langCode String: The language code which complying with BCP 47 standards.
3350 */
3351 function wfBCP47( $code ) {
3352 $codeSegment = explode( '-', $code );
3353 foreach ( $codeSegment as $segNo => $seg ) {
3354 if ( count( $codeSegment ) > 0 ) {
3355 // ISO 3166 country code
3356 if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) )
3357 $codeBCP[$segNo] = strtoupper( $seg );
3358 // ISO 15924 script code
3359 else if ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) )
3360 $codeBCP[$segNo] = ucfirst( $seg );
3361 // Use lowercase for other cases
3362 else
3363 $codeBCP[$segNo] = strtolower( $seg );
3364 } else {
3365 // Use lowercase for single segment
3366 $codeBCP[$segNo] = strtolower( $seg );
3367 }
3368 }
3369 $langCode = implode ( '-' , $codeBCP );
3370 return $langCode;
3371 }