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