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