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