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