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