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