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