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