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