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