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