23if ( !defined(
'MEDIAWIKI' ) ) {
24 die(
"This file is part of MediaWiki, it is not a valid entry point" );
32use Wikimedia\AtEase\AtEase;
34use Wikimedia\RequestTimeout\RequestTimeout;
35use Wikimedia\WrappedString;
50 $path =
"$wgExtensionDirectory/$ext/extension.json";
52 ExtensionRegistry::getInstance()->queue(
$path );
70 $registry = ExtensionRegistry::getInstance();
71 foreach ( $exts as
$ext ) {
72 $registry->queue(
"$wgExtensionDirectory/$ext/extension.json" );
87 $path =
"$wgStyleDirectory/$skin/skin.json";
89 ExtensionRegistry::getInstance()->queue(
$path );
101 $registry = ExtensionRegistry::getInstance();
102 foreach ( $skins as $skin ) {
103 $registry->queue(
"$wgStyleDirectory/$skin/skin.json" );
118 $comparator =
static function ( $a, $b ):
int {
119 if ( is_string( $a ) && is_string( $b ) ) {
120 return strcmp( $a, $b );
122 if ( !is_array( $a ) && !is_array( $b ) ) {
123 throw new InvalidArgumentException(
124 'This function assumes that array elements are all strings or all arrays'
127 if ( count( $a ) !== count( $b ) ) {
128 return count( $a ) <=> count( $b );
132 while ( key( $a ) !==
null && key( $b ) !==
null ) {
133 $valueA = current( $a );
134 $valueB = current( $b );
135 $cmp = strcmp( $valueA, $valueB );
145 return array_udiff( $arr1, $arr2, $comparator );
169 foreach (
$args as $errors ) {
170 foreach ( $errors as $params ) {
171 $originalParams = $params;
174 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
176 # @todo FIXME: Sometimes get nested arrays for $params,
177 # which leads to E_NOTICEs
178 $spec = implode(
"\t", $params );
179 $out[$spec] = $originalParams;
182 return array_values( $out );
196 $keys = array_keys( $array );
197 $offsetByKey = array_flip(
$keys );
199 if ( !\array_key_exists( $after, $offsetByKey ) ) {
202 $offset = $offsetByKey[$after];
205 $before = array_slice( $array, 0, $offset + 1,
true );
206 $after = array_slice( $array, $offset + 1, count( $array ) - $offset,
true );
208 $output = $before + $insert + $after;
223 if ( is_object( $objOrArray ) ) {
224 $objOrArray = get_object_vars( $objOrArray );
226 foreach ( $objOrArray as $key => $value ) {
227 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
231 $array[$key] = $value;
250 $max = mt_getrandmax() + 1;
251 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12,
'.',
'' );
267 for ( $n = 0; $n < $length; $n += 7 ) {
268 $str .= sprintf(
'%07x', mt_rand() & 0xfffffff );
270 return substr( $str, 0, $length );
309 if ( $needle ===
null ) {
310 $needle = [
'%3B',
'%40',
'%24',
'%21',
'%2A',
'%28',
'%29',
'%2C',
'%2F',
'%7E' ];
311 if ( !isset( $_SERVER[
'SERVER_SOFTWARE'] ) ||
312 ( strpos( $_SERVER[
'SERVER_SOFTWARE'],
'Microsoft-IIS/7' ) ===
false )
318 $s = urlencode(
$s );
321 [
';',
'@',
'$',
'!',
'*',
'(',
')',
',',
'/',
'~',
':' ],
339 if ( $array2 !==
null ) {
344 foreach ( $array1 as $key => $value ) {
345 if ( $value !==
null && $value !==
false ) {
349 if ( $prefix !==
'' ) {
350 $key = $prefix .
"[$key]";
352 if ( is_array( $value ) ) {
354 foreach ( $value as $k => $v ) {
355 $cgi .= $firstTime ?
'' :
'&';
356 if ( is_array( $v ) ) {
359 $cgi .= urlencode( $key .
"[$k]" ) .
'=' . urlencode( $v );
364 if ( is_object( $value ) ) {
365 $value = $value->__toString();
367 $cgi .= urlencode( $key ) .
'=' . urlencode( $value );
384 if ( isset( $query[0] ) && $query[0] ==
'?' ) {
385 $query = substr( $query, 1 );
387 $bits = explode(
'&', $query );
389 foreach ( $bits as $bit ) {
393 if ( strpos( $bit,
'=' ) ===
false ) {
398 list( $key, $value ) = explode(
'=', $bit );
400 $key = urldecode( $key );
401 $value = urldecode( $value );
402 if ( strpos( $key,
'[' ) !==
false ) {
403 $keys = array_reverse( explode(
'[', $key ) );
404 $key = array_pop(
$keys );
406 foreach (
$keys as $k ) {
407 $k = substr( $k, 0, -1 );
408 $temp = [ $k => $temp ];
410 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
411 $ret[$key] = array_merge( $ret[$key], $temp );
431 if ( is_array( $query ) ) {
434 if ( $query !=
'' ) {
437 $hashPos = strpos( $url,
'#' );
438 if ( $hashPos !==
false ) {
439 $fragment = substr( $url, $hashPos );
440 $url = substr( $url, 0, $hashPos );
444 if ( strpos( $url,
'?' ) ===
false ) {
452 if ( $fragment !==
false ) {
493 $defaultProto =
$wgRequest->getProtocol() .
'://';
499 $serverHasProto = $bits && $bits[
'scheme'] !=
'';
502 if ( $serverHasProto ) {
503 $defaultProto = $bits[
'scheme'] .
'://';
512 $defaultProtoWithoutSlashes = $defaultProto !==
null ? substr( $defaultProto, 0, -2 ) :
'';
514 if ( substr( $url, 0, 2 ) ==
'//' ) {
515 $url = $defaultProtoWithoutSlashes . $url;
516 } elseif ( substr( $url, 0, 1 ) ==
'/' ) {
519 if ( $serverHasProto ) {
520 $url = $serverUrl . $url;
525 if ( isset( $bits[
'port'] ) ) {
526 throw new Exception(
'A protocol-relative $wgServer may not contain a port number' );
528 $url = $defaultProtoWithoutSlashes . $serverUrl .
':' .
$wgHttpsPort . $url;
530 $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
537 if ( $bits && isset( $bits[
'path'] ) ) {
543 } elseif ( substr( $url, 0, 1 ) !=
'/' ) {
544 # URL is a relative path
548 # Expanded URL is not valid.
562 return substr( $url, 0, -1 );
581 if ( isset( $urlParts[
'delimiter'] ) ) {
582 if ( isset( $urlParts[
'scheme'] ) ) {
583 $result .= $urlParts[
'scheme'];
586 $result .= $urlParts[
'delimiter'];
589 if ( isset( $urlParts[
'host'] ) ) {
590 if ( isset( $urlParts[
'user'] ) ) {
591 $result .= $urlParts[
'user'];
592 if ( isset( $urlParts[
'pass'] ) ) {
593 $result .=
':' . $urlParts[
'pass'];
598 $result .= $urlParts[
'host'];
600 if ( isset( $urlParts[
'port'] ) ) {
601 $result .=
':' . $urlParts[
'port'];
605 if ( isset( $urlParts[
'path'] ) ) {
606 $result .= $urlParts[
'path'];
609 if ( isset( $urlParts[
'query'] ) && $urlParts[
'query'] !==
'' ) {
610 $result .=
'?' . $urlParts[
'query'];
613 if ( isset( $urlParts[
'fragment'] ) ) {
614 $result .=
'#' . $urlParts[
'fragment'];
635 $inputLength = strlen( $urlPath );
637 while ( $inputOffset < $inputLength ) {
638 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
639 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
640 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
641 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
644 if ( $prefixLengthTwo ==
'./' ) {
645 # Step A, remove leading "./"
647 } elseif ( $prefixLengthThree ==
'../' ) {
648 # Step A, remove leading "../"
650 } elseif ( ( $prefixLengthTwo ==
'/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
651 # Step B, replace leading "/.$" with "/"
653 $urlPath[$inputOffset] =
'/';
654 } elseif ( $prefixLengthThree ==
'/./' ) {
655 # Step B, replace leading "/./" with "/"
657 } elseif ( $prefixLengthThree ==
'/..' && ( $inputOffset + 3 == $inputLength ) ) {
658 # Step C, replace leading "/..$" with "/" and
659 # remove last path component in output
661 $urlPath[$inputOffset] =
'/';
663 } elseif ( $prefixLengthFour ==
'/../' ) {
664 # Step C, replace leading "/../" with "/" and
665 # remove last path component in output
668 } elseif ( ( $prefixLengthOne ==
'.' ) && ( $inputOffset + 1 == $inputLength ) ) {
669 # Step D, remove "^.$"
671 } elseif ( ( $prefixLengthTwo ==
'..' ) && ( $inputOffset + 2 == $inputLength ) ) {
672 # Step D, remove "^..$"
675 # Step E, move leading path segment to output
676 if ( $prefixLengthOne ==
'/' ) {
677 $slashPos = strpos( $urlPath,
'/', $inputOffset + 1 );
679 $slashPos = strpos( $urlPath,
'/', $inputOffset );
681 if ( $slashPos ===
false ) {
682 $output .= substr( $urlPath, $inputOffset );
683 $inputOffset = $inputLength;
685 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
686 $inputOffset += $slashPos - $inputOffset;
691 $slashPos = strrpos( $output,
'/' );
692 if ( $slashPos ===
false ) {
695 $output = substr( $output, 0, $slashPos );
714 static $withProtRel =
null, $withoutProtRel =
null;
715 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
716 if ( $cachedValue !==
null ) {
726 if ( $includeProtocolRelative || $protocol !==
'//' ) {
727 $protocols[] = preg_quote( $protocol,
'/' );
731 $retval = implode(
'|', $protocols );
741 if ( $includeProtocolRelative ) {
742 $withProtRel = $retval;
744 $withoutProtRel = $retval;
790 $wasRelative = substr( $url, 0, 2 ) ==
'//';
791 if ( $wasRelative ) {
794 $bits = parse_url( $url );
797 if ( !$bits || !isset( $bits[
'scheme'] ) ) {
802 $bits[
'scheme'] = strtolower( $bits[
'scheme'] );
806 $bits[
'delimiter'] =
'://';
808 $bits[
'delimiter'] =
':';
811 if ( isset( $bits[
'path'] ) ) {
812 $bits[
'host'] = $bits[
'path'];
820 if ( !isset( $bits[
'host'] ) ) {
824 if ( isset( $bits[
'path'] ) ) {
826 if ( substr( $bits[
'path'], 0, 1 ) !==
'/' ) {
827 $bits[
'path'] =
'/' . $bits[
'path'];
835 if ( $wasRelative ) {
836 $bits[
'scheme'] =
'';
837 $bits[
'delimiter'] =
'//';
853 return preg_replace_callback(
854 '/((?:%[89A-F][0-9A-F])+)/i',
855 static function ( array
$matches ) {
870 if ( is_array( $bits ) && isset( $bits[
'host'] ) ) {
871 $host =
'.' . $bits[
'host'];
872 foreach ( (array)$domains as $domain ) {
873 $domain =
'.' . $domain;
874 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
902function wfDebug( $text, $dest =
'all', array $context = [] ) {
909 $text = trim( $text );
914 $context[
'private'] = ( $dest ===
false || $dest ===
'private' );
916 $logger = LoggerFactory::getInstance(
'wfDebug' );
917 $logger->debug( $text, $context );
931 if ( ( isset( $_GET[
'action'] ) && $_GET[
'action'] ==
'raw' )
967 $logGroup, $text, $dest =
'all', array $context = []
969 $text = trim( $text );
971 $logger = LoggerFactory::getInstance( $logGroup );
972 $context[
'private'] = ( $dest ===
false || $dest ===
'private' );
973 $logger->info( $text, $context );
985 $logger = LoggerFactory::getInstance(
'wfLogDBError' );
986 $logger->error( trim( $text ), $context );
1005function wfDeprecated( $function, $version =
false, $component =
false, $callerOffset = 2 ) {
1006 if ( !is_string( $version ) && $version !==
false ) {
1007 throw new InvalidArgumentException(
1008 "MediaWiki version must either be a string or false. " .
1009 "Example valid version: '1.33'"
1013 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1036function wfDeprecatedMsg( $msg, $version =
false, $component =
false, $callerOffset = 2 ) {
1037 MWDebug::deprecatedMsg( $msg, $version, $component,
1038 $callerOffset ===
false ?
false : $callerOffset + 1 );
1051function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1052 MWDebug::warning( $msg, $callerOffset + 1, $level,
'auto' );
1065 MWDebug::warning( $msg, $callerOffset + 1, $level,
'production' );
1073 $profiler = Profiler::instance();
1074 $profiler->logData();
1077 MediaWiki::emitBufferedStatsdData(
1078 MediaWikiServices::getInstance()->getStatsdDataFactory(),
1079 MediaWikiServices::getInstance()->getMainConfig()
1091 return MediaWikiServices::getInstance()->getReadOnlyMode()
1106 return MediaWikiServices::getInstance()->getReadOnlyMode()
1126 # Identify which language to get or create a language object for.
1127 # Using is_object here due to Stub objects.
1128 if ( is_object( $langcode ) ) {
1129 # Great, we already have the object (hopefully)!
1134 $services = MediaWikiServices::getInstance();
1136 # $langcode is the language code of the wikis content language object.
1137 # or it is a boolean and value is true
1138 return $services->getContentLanguage();
1142 if ( $langcode ===
false || $langcode ===
$wgLang->getCode() ) {
1143 # $langcode is the language code of user language object.
1144 # or it was a boolean and value is false
1148 $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1149 if ( in_array( $langcode, $validCodes ) ) {
1150 # $langcode corresponds to a valid language.
1151 return $services->getLanguageFactory()->getLanguage( $langcode );
1154 # $langcode is a string, but not a valid language code; use content language.
1155 wfDebug(
"Invalid language code passed to wfGetLangObj, falling back to content language." );
1156 return $services->getContentLanguage();
1181 if ( is_array( $key ) ) {
1190 $message->params( ...$params );
1221 # Fix windows line-endings
1222 # Some messages are split with explode("\n", $msg)
1223 $message = str_replace(
"\r",
'', $message );
1227 if ( is_array(
$args[0] ) ) {
1230 $replacementKeys = [];
1231 foreach (
$args as $n => $param ) {
1232 $replacementKeys[
'$' . ( $n + 1 )] = $param;
1234 $message = strtr( $message, $replacementKeys );
1255 return php_uname(
'n' ) ?:
'unknown';
1271 $elapsed = ( microtime(
true ) - $_SERVER[
'REQUEST_TIME_FLOAT'] );
1273 $responseTime = round( $elapsed * 1000 );
1274 $reportVars = [
'wgBackendResponseTime' => $responseTime ];
1298 static $disabled =
null;
1300 if ( $disabled ===
null ) {
1301 $disabled = !function_exists(
'debug_backtrace' );
1303 wfDebug(
"debug_backtrace() is disabled" );
1311 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1313 return array_slice( debug_backtrace(), 1 );
1328 if ( $raw ===
null ) {
1333 $frameFormat =
"%s line %s calls %s()\n";
1334 $traceFormat =
"%s";
1336 $frameFormat =
"<li>%s line %s calls %s()</li>\n";
1337 $traceFormat =
"<ul>\n%s</ul>\n";
1340 $frames = array_map(
static function ( $frame ) use ( $frameFormat ) {
1341 $file = !empty( $frame[
'file'] ) ? basename( $frame[
'file'] ) :
'-';
1342 $line = $frame[
'line'] ??
'-';
1343 $call = $frame[
'function'];
1344 if ( !empty( $frame[
'class'] ) ) {
1345 $call = $frame[
'class'] . $frame[
'type'] . $call;
1347 return sprintf( $frameFormat,
$file,
$line, $call );
1350 return sprintf( $traceFormat, implode(
'', $frames ) );
1364 if ( isset( $backtrace[$level] ) ) {
1380 if ( !$limit || $limit > count( $trace ) - 1 ) {
1381 $limit = count( $trace ) - 1;
1383 $trace = array_slice( $trace, -$limit - 1, $limit );
1384 return implode(
'/', array_map(
'wfFormatStackFrame', $trace ) );
1394 if ( !isset( $frame[
'function'] ) ) {
1395 return 'NO_FUNCTION_GIVEN';
1397 return isset( $frame[
'class'] ) && isset( $frame[
'type'] ) ?
1398 $frame[
'class'] . $frame[
'type'] . $frame[
'function'] :
1412 return wfMessage(
'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1425 static $result =
null;
1426 if ( $result ===
null || $force ) {
1428 if ( isset( $_SERVER[
'HTTP_ACCEPT_ENCODING'] ) ) {
1429 # @todo FIXME: We may want to disallow some broken browsers
1432 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1433 $_SERVER[
'HTTP_ACCEPT_ENCODING'],
1437 if ( isset( $m[2] ) && ( $m[1] ==
'q' ) && ( $m[2] == 0 ) ) {
1440 wfDebug(
"wfClientAcceptsGzip: client accepts gzip." );
1460 static $repl =
null, $repl2 =
null;
1461 if ( $repl ===
null || defined(
'MW_PARSER_TEST' ) || defined(
'MW_PHPUNIT_TEST' ) ) {
1465 '"' =>
'"',
'&' =>
'&',
"'" =>
''',
'<' =>
'<',
1466 '=' =>
'=',
'>' =>
'>',
'[' =>
'[',
']' =>
']',
1467 '{' =>
'{',
'|' =>
'|',
'}' =>
'}',
';' =>
';',
1468 "\n#" =>
"\n#",
"\r#" =>
"\r#",
1469 "\n*" =>
"\n*",
"\r*" =>
"\r*",
1470 "\n:" =>
"\n:",
"\r:" =>
"\r:",
1471 "\n " =>
"\n ",
"\r " =>
"\r ",
1472 "\n\n" =>
"\n ",
"\r\n" =>
" \n",
1473 "\n\r" =>
"\n ",
"\r\r" =>
"\r ",
1474 "\n\t" =>
"\n	",
"\r\t" =>
"\r	",
1475 "\n----" =>
"\n----",
"\r----" =>
"\r----",
1476 '__' =>
'__',
'://' =>
'://',
1481 foreach ( $magicLinks as $magic ) {
1482 $repl[
"$magic "] =
"$magic ";
1483 $repl[
"$magic\t"] =
"$magic	";
1484 $repl[
"$magic\r"] =
"$magic ";
1485 $repl[
"$magic\n"] =
"$magic ";
1486 $repl[
"$magic\f"] =
"$magic";
1493 if ( substr( $prot, -1 ) ===
':' ) {
1494 $repl2[] = preg_quote( substr( $prot, 0, -1 ),
'/' );
1497 $repl2 = $repl2 ?
'/\b(' . implode(
'|', $repl2 ) .
'):/i' :
'/^(?!)/';
1499 $text = substr( strtr(
"\n$text", $repl ), 1 );
1500 $text = preg_replace( $repl2,
'$1:', $text );
1516 if (
$source !==
null || $force ) {
1532 $temp = (bool)( $dest & $bit );
1533 if ( $state !==
null ) {
1551 $s = str_replace(
"\n",
"<br />\n", var_export( $var,
true ) .
"\n" );
1552 if ( headers_sent() || !isset(
$wgOut ) || !is_object(
$wgOut ) ) {
1568 HttpStatus::header( $code );
1571 $wgOut->sendCacheControl();
1574 MediaWiki\HeaderCallback::warnIfHeadersSent();
1575 header(
'Content-type: text/html; charset=utf-8' );
1577 print '<!DOCTYPE html>' .
1578 '<html><head><title>' .
1579 htmlspecialchars( $label ) .
1580 '</title></head><body><h1>' .
1581 htmlspecialchars( $label ) .
1583 nl2br( htmlspecialchars( $desc ) ) .
1584 "</p></body></html>\n";
1585 header(
'Content-Length: ' . ob_get_length() );
1607 while ( $status = ob_get_status() ) {
1608 if ( isset( $status[
'flags'] ) ) {
1609 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1610 $deleteable = ( $status[
'flags'] & $flags ) === $flags;
1611 } elseif ( isset( $status[
'del'] ) ) {
1612 $deleteable = $status[
'del'];
1615 $deleteable = $status[
'type'] !== 0;
1617 if ( !$deleteable ) {
1622 if ( $status[
'name'] ===
'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1626 if ( !ob_end_clean() ) {
1631 if ( $resetGzipEncoding && $status[
'name'] ==
'ob_gzhandler' ) {
1634 header_remove(
'Content-Encoding' );
1668 $ret = MWTimestamp::convert( $outputtype, $ts );
1669 if ( $ret ===
false ) {
1670 wfDebug(
"wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1684 if ( $ts ===
null ) {
1697 return MWTimestamp::now( TS_MW );
1706 return PHP_OS_FAMILY ===
'Windows';
1716 return PHP_SAPI ===
'cli' || PHP_SAPI ===
'phpdbg';
1737 return TempFSFile::getUsableTempDirectory();
1753 throw new MWException( __FUNCTION__ .
" given storage path '$dir'." );
1756 if ( $caller !==
null ) {
1757 wfDebug(
"$caller: called wfMkdirParents($dir)" );
1760 if ( strval( $dir ) ===
'' || is_dir( $dir ) ) {
1764 $dir = str_replace( [
'\\',
'/' ], DIRECTORY_SEPARATOR, $dir );
1766 if ( $mode ===
null ) {
1771 AtEase::suppressWarnings();
1772 $ok = mkdir( $dir, $mode,
true );
1773 AtEase::restoreWarnings();
1777 if ( is_dir( $dir ) ) {
1782 wfLogWarning( sprintf(
"failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1793 wfDebug( __FUNCTION__ .
"( $dir )" );
1795 if ( is_dir( $dir ) ) {
1796 $objects = scandir( $dir );
1797 foreach ( $objects as $object ) {
1798 if ( $object !=
"." && $object !=
".." ) {
1799 if ( filetype( $dir .
'/' . $object ) ==
"dir" ) {
1802 unlink( $dir .
'/' . $object );
1817function wfPercent( $nr,
int $acc = 2,
bool $round =
true ) {
1818 $accForFormat = $acc >= 0 ? $acc : 0;
1819 $ret = sprintf(
"%.{$accForFormat}f", $nr );
1820 return $round ? round( (
float)$ret, $acc ) .
'%' :
"$ret%";
1863 $val = strtolower( $val );
1868 || preg_match(
"/^\s*[+-]?0*[1-9]/", $val );
1885 return Shell::escape( ...
$args );
1913 $limits = [], $options = []
1915 if ( Shell::isDisabled() ) {
1918 return 'Unable to run external programs, proc_open() is disabled.';
1921 if ( is_array( $cmd ) ) {
1922 $cmd = Shell::escape( $cmd );
1925 $includeStderr = isset( $options[
'duplicateStderr'] ) && $options[
'duplicateStderr'];
1926 $profileMethod = $options[
'profileMethod'] ??
wfGetCaller();
1929 $result = Shell::command( [] )
1930 ->unsafeParams( (array)$cmd )
1931 ->environment( $environ )
1933 ->includeStderr( $includeStderr )
1934 ->profileMethod( $profileMethod )
1936 ->restrict( Shell::RESTRICT_NONE )
1943 $retval = $result->getExitCode();
1945 return $result->getStdout();
1966 return wfShellExec( $cmd, $retval, $environ, $limits,
1967 [
'duplicateStderr' =>
true,
'profileMethod' =>
wfGetCaller() ] );
1989 Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
1990 $cmd = [ $options[
'php'] ??
$wgPhpCli ];
1991 if ( isset( $options[
'wrapper'] ) ) {
1992 $cmd[] = $options[
'wrapper'];
1996 return Shell::escape( array_merge( $cmd, $parameters ) );
2010function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult =
null ) {
2013 # This check may also protect against code injection in
2014 # case of broken installations.
2015 AtEase::suppressWarnings();
2017 AtEase::restoreWarnings();
2019 if ( !$haveDiff3 ) {
2024 # Make temporary files
2026 $oldtextFile = fopen( $oldtextName = tempnam( $td,
'merge-old-' ),
'w' );
2027 $mytextFile = fopen( $mytextName = tempnam( $td,
'merge-mine-' ),
'w' );
2028 $yourtextFile = fopen( $yourtextName = tempnam( $td,
'merge-your-' ),
'w' );
2030 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2031 # a newline character. To avoid this, we normalize the trailing whitespace before
2032 # creating the diff.
2034 fwrite( $oldtextFile, rtrim( $old ) .
"\n" );
2035 fclose( $oldtextFile );
2036 fwrite( $mytextFile, rtrim( $mine ) .
"\n" );
2037 fclose( $mytextFile );
2038 fwrite( $yourtextFile, rtrim( $yours ) .
"\n" );
2039 fclose( $yourtextFile );
2041 # Check for a conflict
2042 $cmd = Shell::escape(
$wgDiff3,
'-a',
'--overlap-only', $mytextName,
2043 $oldtextName, $yourtextName );
2044 $handle = popen( $cmd,
'r' );
2046 $mergeAttemptResult =
'';
2048 $data = fread( $handle, 8192 );
2049 if ( strlen( $data ) == 0 ) {
2052 $mergeAttemptResult .= $data;
2056 $conflict = $mergeAttemptResult !==
'';
2059 $cmd = Shell::escape(
$wgDiff3,
'-a',
'-e',
'--merge', $mytextName,
2060 $oldtextName, $yourtextName );
2061 $handle = popen( $cmd,
'r' );
2064 $data = fread( $handle, 8192 );
2065 if ( strlen( $data ) == 0 ) {
2071 unlink( $mytextName );
2072 unlink( $oldtextName );
2073 unlink( $yourtextName );
2075 if ( $result ===
'' && $old !==
'' && !$conflict ) {
2076 wfDebug(
"Unexpected null result from diff3. Command: $cmd" );
2095 if ( $suffix ==
'' ) {
2098 $encSuffix =
'(?:' . preg_quote( $suffix,
'#' ) .
')?';
2102 if ( preg_match(
"#([^/\\\\]*?){$encSuffix}[/\\\\]*$#",
$path,
$matches ) ) {
2120 $path = str_replace(
'/', DIRECTORY_SEPARATOR,
$path );
2121 $from = str_replace(
'/', DIRECTORY_SEPARATOR, $from );
2125 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2127 $pieces = explode( DIRECTORY_SEPARATOR, dirname(
$path ) );
2128 $against = explode( DIRECTORY_SEPARATOR, $from );
2130 if ( $pieces[0] !== $against[0] ) {
2137 while ( count( $pieces ) && count( $against )
2138 && $pieces[0] == $against[0] ) {
2139 array_shift( $pieces );
2140 array_shift( $against );
2144 while ( count( $against ) ) {
2145 array_unshift( $pieces,
'..' );
2146 array_shift( $against );
2151 return implode( DIRECTORY_SEPARATOR, $pieces );
2167 return "$wgDBname-$wgDBprefix";
2204function wfGetDB( $db, $groups = [], $wiki =
false ) {
2205 if ( $wiki ===
false ) {
2206 return MediaWikiServices::getInstance()
2207 ->getDBLoadBalancer()
2208 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2210 return MediaWikiServices::getInstance()
2211 ->getDBLoadBalancerFactory()
2212 ->getMainLB( $wiki )
2213 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2229 if ( $wiki ===
false ) {
2231 return MediaWikiServices::getInstance()->getDBLoadBalancer();
2233 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2235 return $factory->getMainLB( $wiki );
2248 return MediaWikiServices::getInstance()->getRepoGroup()->findFile(
$title, $options );
2261 return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile(
$title );
2288 if ( $script ===
'index' ) {
2290 } elseif ( $script ===
'load' ) {
2293 return "{$wgScriptPath}/{$script}.php";
2305 if ( isset( $_SERVER[
'SCRIPT_NAME'] ) ) {
2316 return $_SERVER[
'SCRIPT_NAME'];
2318 return $_SERVER[
'URL'];
2330 return $value ?
'true' :
'false';
2353 $name = preg_replace(
2354 "/[^" . Title::legalChars() .
"]" . $illegalFileChars .
"/",
2372 if ( $oldLimit != -1 ) {
2374 if ( $newLimit == -1 ) {
2375 wfDebug(
"Removing PHP's memory limit" );
2376 AtEase::suppressWarnings();
2377 ini_set(
'memory_limit', $newLimit );
2378 AtEase::restoreWarnings();
2379 } elseif ( $newLimit > $oldLimit ) {
2380 wfDebug(
"Raising PHP's memory limit to $newLimit bytes" );
2381 AtEase::suppressWarnings();
2382 ini_set(
'memory_limit', $newLimit );
2383 AtEase::restoreWarnings();
2397 $timeout = RequestTimeout::singleton();
2398 $timeLimit = $timeout->getWallTimeLimit();
2399 if ( $timeLimit !== INF ) {
2406 $timeLimit = (int)ini_get(
'max_execution_time' );
2412 ignore_user_abort(
true );
2425 $string = trim( $string ??
'' );
2426 if ( $string ===
'' ) {
2429 $last = $string[strlen( $string ) - 1];
2430 $val = intval( $string );
2459 return ObjectCache::getInstance( $cacheType );
2472 return ObjectCache::getLocalClusterInstance();
2490 if ( $length !==
false ) {
2491 $realLen = strlen( $data );
2492 if ( $realLen < $length ) {
2493 throw new MWException(
"Tried to use wfUnpack on a "
2494 .
"string of length $realLen, but needed one "
2495 .
"of at least length $length."
2500 AtEase::suppressWarnings();
2501 $result = unpack( $format, $data );
2502 AtEase::restoreWarnings();
2504 if ( $result ===
false ) {
2506 throw new MWException(
"unpack could not unpack binary data" );
2534 return in_array( $str, ExpiryDef::INFINITY_VALS );
2554 $multipliers = [ 1 ];
2558 $multipliers[] = 1.5;
2562 $handler =
$file->getHandler();
2563 if ( !$handler || !isset( $params[
'width'] ) ) {
2568 if ( isset( $params[
'page'] ) ) {
2569 $basicParams[
'page'] = $params[
'page'];
2575 foreach ( $multipliers as $multiplier ) {
2576 $thumbLimits = array_merge( $thumbLimits, array_map(
2577 static function ( $width ) use ( $multiplier ) {
2578 return round( $width * $multiplier );
2581 $imageLimits = array_merge( $imageLimits, array_map(
2582 static function ( $pair ) use ( $multiplier ) {
2584 round( $pair[0] * $multiplier ),
2585 round( $pair[1] * $multiplier ),
2592 if ( in_array( $params[
'width'], $thumbLimits ) ) {
2593 $normalParams = $basicParams + [
'width' => $params[
'width'] ];
2595 $handler->normaliseParams(
$file, $normalParams );
2599 foreach ( $imageLimits as $pair ) {
2600 $normalParams = $basicParams + [
'width' => $pair[0],
'height' => $pair[1] ];
2603 $handler->normaliseParams(
$file, $normalParams );
2605 if ( $normalParams[
'width'] == $params[
'width'] ) {
2616 foreach ( $params as $key => $value ) {
2617 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2639 foreach ( $baseArray as $name => &$groupVal ) {
2640 if ( isset( $newValues[$name] ) ) {
2641 $groupVal += $newValues[$name];
2645 $baseArray += $newValues;
$wgLanguageCode
Site language code.
$wgDBprefix
Current wiki database table name prefix.
$wgScript
The URL path to index.php.
$wgInternalServer
Internal server name as known to CDN, if different.
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
$wgDebugLogPrefix
Prefix for debug log lines.
$wgPhpCli
Executable path of the PHP cli binary.
$wgOverrideHostname
Override server hostname detection with a hardcoded value.
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
$wgTmpDirectory
The local filesystem path to a temporary directory.
$wgStyleDirectory
Filesystem stylesheets directory.
$wgTransactionalTimeLimit
The request time limit for "slow" write requests that should not be interrupted due to the risk of da...
$wgDBname
Current wiki database name.
$wgIllegalFileChars
Additional characters that are not allowed in filenames.
$wgDirectoryMode
Default value for chmoding of new directories.
$wgDiff3
Path to the GNU diff3 utility.
$wgUrlProtocols
URL schemes that should be recognized as valid by wfParseUrl().
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
$wgDebugRawPage
If true, log debugging data from action=raw and load.php.
$wgEnableMagicLinks
Enable the magic links feature of automatically turning ISBN xxx, PMID xxx, RFC xxx into links.
$wgScriptPath
The path we should point to.
$wgExtensionDirectory
Filesystem extensions directory.
$wgLoadScript
The URL path to load.php.
$wgCanonicalServer
Canonical URL of the server, to use in IRC feeds and notification e-mails.
$wgMiserMode
Disable database-intensive features.
$wgServer
URL of the server.
$wgHttpsPort
For installations where the canonical server is HTTP but HTTPS is optionally supported,...
global $wgCommandLineMode
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
wfVarDump( $var)
A wrapper around the PHP function var_export().
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
wfTempDir()
Tries to get the system directory for temporary files.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
wfEscapeShellArg(... $args)
Locale-independent version of escapeshellarg()
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
wfGetLB( $wiki=false)
Get a load balancer object.
wfUrlProtocolsWithoutProtRel()
Like wfUrlProtocols(), but excludes '//' from the protocol list.
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
wfLoadExtension( $ext, $path=null)
Load an extension.
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
wfReadOnly()
Check whether the wiki is in read-only mode.
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfShorthandToInteger(?string $string='', int $default=-1)
Converts shorthand byte notation to integer form.
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
wfArrayDiff2( $arr1, $arr2)
Like array_diff( $arr1, $arr2 ) except that it works with two-dimensional arrays.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfLocalFile( $title)
Get an object referring to a locally registered file.
wfExpandIRI( $url)
Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode cha...
wfMergeErrorArrays(... $args)
Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e....
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfGetMainCache()
Get the main cache object.
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
wfPercent( $nr, int $acc=2, bool $round=true)
wfFindFile( $title, $options=[])
Find a file.
wfReportTime( $nonce=null)
Returns a script tag that stores the amount of time it took MediaWiki to handle the request in millis...
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
wfGetNull()
Get a platform-independent path to the null file, e.g.
wfRelativePath( $path, $from)
Generate a relative path name to the given file.
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
wfShowingResults( $offset, $limit)
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfTransactionalTimeLimit()
Raise the request time limit to $wgTransactionalTimeLimit.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
wfGetScriptUrl()
Get the script URL.
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
wfLoadSkin( $skin, $path=null)
Load a skin.
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
wfGetCache( $cacheType)
Get a specific cache object.
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
wfFormatStackFrame( $frame)
Return a string representation of frame.
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
wfIsWindows()
Check if the operating system is Windows.
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfQueriesMustScale()
Should low-performance queries be disabled?
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfLoadExtensions(array $exts)
Load multiple extensions at once.
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
wfArrayInsertAfter(array $array, array $insert, $after)
Insert an array into another array after the specified key.
wfAssembleUrl( $urlParts)
This function will reassemble a URL parsed with wfParseURL.
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
wfIsCLI()
Check if we are running from the commandline.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgOut
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Implements some public methods and some protected utility functions which are required by multiple ch...
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
static makeInlineScript( $script, $nonce=null)
Make an HTML script that runs given JS code after startup and base modules.
static makeConfigSetScript(array $configuration)
Return JS code which will set the MediaWiki configuration array to the given value.
while(( $__line=Maintenance::readconsole()) !==false) print
foreach( $mmfl['setupFiles'] as $fileName) if($queue) if(empty( $mmfl['quiet'])) $s
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!is_readable( $file)) $ext