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