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" );
114 return array_udiff( $a, $b,
'wfArrayDiff2_cmp' );
123 if ( is_string( $a ) && is_string( $b ) ) {
124 return strcmp( $a, $b );
125 } elseif ( count( $a ) !== count( $b ) ) {
126 return count( $a ) <=> count( $b );
130 while ( key( $a ) !==
null && key( $b ) !==
null ) {
131 $valueA = current( $a );
132 $valueB = current( $b );
133 $cmp = strcmp( $valueA, $valueB );
165 foreach (
$args as $errors ) {
166 foreach ( $errors as $params ) {
167 $originalParams = $params;
170 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
172 # @todo FIXME: Sometimes get nested arrays for $params,
173 # which leads to E_NOTICEs
174 $spec = implode(
"\t", $params );
175 $out[$spec] = $originalParams;
178 return array_values( $out );
191 $keys = array_keys( $array );
192 $offsetByKey = array_flip(
$keys );
194 $offset = $offsetByKey[$after];
197 $before = array_slice( $array, 0, $offset + 1,
true );
198 $after = array_slice( $array, $offset + 1, count( $array ) - $offset,
true );
200 $output = $before + $insert + $after;
215 if ( is_object( $objOrArray ) ) {
216 $objOrArray = get_object_vars( $objOrArray );
218 foreach ( $objOrArray as $key => $value ) {
219 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
223 $array[$key] = $value;
242 $max = mt_getrandmax() + 1;
243 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12,
'.',
'' );
259 for ( $n = 0; $n < $length; $n += 7 ) {
260 $str .= sprintf(
'%07x', mt_rand() & 0xfffffff );
262 return substr( $str, 0, $length );
301 if ( $needle ===
null ) {
302 $needle = [
'%3B',
'%40',
'%24',
'%21',
'%2A',
'%28',
'%29',
'%2C',
'%2F',
'%7E' ];
303 if ( !isset( $_SERVER[
'SERVER_SOFTWARE'] ) ||
304 ( strpos( $_SERVER[
'SERVER_SOFTWARE'],
'Microsoft-IIS/7' ) ===
false )
310 $s = urlencode(
$s );
313 [
';',
'@',
'$',
'!',
'*',
'(',
')',
',',
'/',
'~',
':' ],
331 if ( $array2 !==
null ) {
336 foreach ( $array1 as $key => $value ) {
337 if ( $value !==
null && $value !==
false ) {
341 if ( $prefix !==
'' ) {
342 $key = $prefix .
"[$key]";
344 if ( is_array( $value ) ) {
346 foreach ( $value as $k => $v ) {
347 $cgi .= $firstTime ?
'' :
'&';
348 if ( is_array( $v ) ) {
351 $cgi .= urlencode( $key .
"[$k]" ) .
'=' . urlencode( $v );
356 if ( is_object( $value ) ) {
357 $value = $value->__toString();
359 $cgi .= urlencode( $key ) .
'=' . urlencode( $value );
376 if ( isset( $query[0] ) && $query[0] ==
'?' ) {
377 $query = substr( $query, 1 );
379 $bits = explode(
'&', $query );
381 foreach ( $bits as $bit ) {
385 if ( strpos( $bit,
'=' ) ===
false ) {
390 list( $key, $value ) = explode(
'=', $bit );
392 $key = urldecode( $key );
393 $value = urldecode( $value );
394 if ( strpos( $key,
'[' ) !==
false ) {
395 $keys = array_reverse( explode(
'[', $key ) );
396 $key = array_pop(
$keys );
398 foreach (
$keys as $k ) {
399 $k = substr( $k, 0, -1 );
400 $temp = [ $k => $temp ];
402 if ( isset( $ret[$key] ) ) {
403 $ret[$key] = array_merge( $ret[$key], $temp );
423 if ( is_array( $query ) ) {
426 if ( $query !=
'' ) {
429 $hashPos = strpos( $url,
'#' );
430 if ( $hashPos !==
false ) {
431 $fragment = substr( $url, $hashPos );
432 $url = substr( $url, 0, $hashPos );
436 if ( strpos( $url,
'?' ) ===
false ) {
444 if ( $fragment !==
false ) {
485 $defaultProto =
$wgRequest->getProtocol() .
'://';
491 $serverHasProto = $bits && $bits[
'scheme'] !=
'';
494 if ( $serverHasProto ) {
495 $defaultProto = $bits[
'scheme'] .
'://';
504 $defaultProtoWithoutSlashes = $defaultProto !==
null ? substr( $defaultProto, 0, -2 ) :
'';
506 if ( substr( $url, 0, 2 ) ==
'//' ) {
507 $url = $defaultProtoWithoutSlashes . $url;
508 } elseif ( substr( $url, 0, 1 ) ==
'/' ) {
511 if ( $serverHasProto ) {
512 $url = $serverUrl . $url;
517 if ( isset( $bits[
'port'] ) ) {
518 throw new Exception(
'A protocol-relative $wgServer may not contain a port number' );
520 $url = $defaultProtoWithoutSlashes . $serverUrl .
':' .
$wgHttpsPort . $url;
522 $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
529 if ( $bits && isset( $bits[
'path'] ) ) {
535 } elseif ( substr( $url, 0, 1 ) !=
'/' ) {
536 # URL is a relative path
540 # Expanded URL is not valid.
554 return substr( $url, 0, -1 );
573 if ( isset( $urlParts[
'delimiter'] ) ) {
574 if ( isset( $urlParts[
'scheme'] ) ) {
575 $result .= $urlParts[
'scheme'];
578 $result .= $urlParts[
'delimiter'];
581 if ( isset( $urlParts[
'host'] ) ) {
582 if ( isset( $urlParts[
'user'] ) ) {
583 $result .= $urlParts[
'user'];
584 if ( isset( $urlParts[
'pass'] ) ) {
585 $result .=
':' . $urlParts[
'pass'];
590 $result .= $urlParts[
'host'];
592 if ( isset( $urlParts[
'port'] ) ) {
593 $result .=
':' . $urlParts[
'port'];
597 if ( isset( $urlParts[
'path'] ) ) {
598 $result .= $urlParts[
'path'];
601 if ( isset( $urlParts[
'query'] ) && $urlParts[
'query'] !==
'' ) {
602 $result .=
'?' . $urlParts[
'query'];
605 if ( isset( $urlParts[
'fragment'] ) ) {
606 $result .=
'#' . $urlParts[
'fragment'];
627 $inputLength = strlen( $urlPath );
629 while ( $inputOffset < $inputLength ) {
630 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
631 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
632 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
633 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
636 if ( $prefixLengthTwo ==
'./' ) {
637 # Step A, remove leading "./"
639 } elseif ( $prefixLengthThree ==
'../' ) {
640 # Step A, remove leading "../"
642 } elseif ( ( $prefixLengthTwo ==
'/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
643 # Step B, replace leading "/.$" with "/"
645 $urlPath[$inputOffset] =
'/';
646 } elseif ( $prefixLengthThree ==
'/./' ) {
647 # Step B, replace leading "/./" with "/"
649 } elseif ( $prefixLengthThree ==
'/..' && ( $inputOffset + 3 == $inputLength ) ) {
650 # Step C, replace leading "/..$" with "/" and
651 # remove last path component in output
653 $urlPath[$inputOffset] =
'/';
655 } elseif ( $prefixLengthFour ==
'/../' ) {
656 # Step C, replace leading "/../" with "/" and
657 # remove last path component in output
660 } elseif ( ( $prefixLengthOne ==
'.' ) && ( $inputOffset + 1 == $inputLength ) ) {
661 # Step D, remove "^.$"
663 } elseif ( ( $prefixLengthTwo ==
'..' ) && ( $inputOffset + 2 == $inputLength ) ) {
664 # Step D, remove "^..$"
667 # Step E, move leading path segment to output
668 if ( $prefixLengthOne ==
'/' ) {
669 $slashPos = strpos( $urlPath,
'/', $inputOffset + 1 );
671 $slashPos = strpos( $urlPath,
'/', $inputOffset );
673 if ( $slashPos ===
false ) {
674 $output .= substr( $urlPath, $inputOffset );
675 $inputOffset = $inputLength;
677 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
678 $inputOffset += $slashPos - $inputOffset;
683 $slashPos = strrpos( $output,
'/' );
684 if ( $slashPos ===
false ) {
687 $output = substr( $output, 0, $slashPos );
706 static $withProtRel =
null, $withoutProtRel =
null;
707 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
708 if ( $cachedValue !==
null ) {
718 if ( $includeProtocolRelative || $protocol !==
'//' ) {
719 $protocols[] = preg_quote( $protocol,
'/' );
723 $retval = implode(
'|', $protocols );
733 if ( $includeProtocolRelative ) {
734 $withProtRel = $retval;
736 $withoutProtRel = $retval;
782 $wasRelative = substr( $url, 0, 2 ) ==
'//';
783 if ( $wasRelative ) {
786 $bits = parse_url( $url );
789 if ( !$bits || !isset( $bits[
'scheme'] ) ) {
794 $bits[
'scheme'] = strtolower( $bits[
'scheme'] );
798 $bits[
'delimiter'] =
'://';
800 $bits[
'delimiter'] =
':';
803 if ( isset( $bits[
'path'] ) ) {
804 $bits[
'host'] = $bits[
'path'];
812 if ( !isset( $bits[
'host'] ) ) {
816 if ( isset( $bits[
'path'] ) ) {
818 if ( substr( $bits[
'path'], 0, 1 ) !==
'/' ) {
819 $bits[
'path'] =
'/' . $bits[
'path'];
827 if ( $wasRelative ) {
828 $bits[
'scheme'] =
'';
829 $bits[
'delimiter'] =
'//';
845 return preg_replace_callback(
846 '/((?:%[89A-F][0-9A-F])+)/i',
847 static function ( array
$matches ) {
862 if ( is_array( $bits ) && isset( $bits[
'host'] ) ) {
863 $host =
'.' . $bits[
'host'];
864 foreach ( (array)$domains as $domain ) {
865 $domain =
'.' . $domain;
866 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
894function wfDebug( $text, $dest =
'all', array $context = [] ) {
901 $text = trim( $text );
906 $context[
'private'] = ( $dest ===
false || $dest ===
'private' );
908 $logger = LoggerFactory::getInstance(
'wfDebug' );
909 $logger->debug( $text, $context );
923 if ( ( isset( $_GET[
'action'] ) && $_GET[
'action'] ==
'raw' )
959 $logGroup, $text, $dest =
'all', array $context = []
961 $text = trim( $text );
963 $logger = LoggerFactory::getInstance( $logGroup );
964 $context[
'private'] = ( $dest ===
false || $dest ===
'private' );
965 $logger->info( $text, $context );
977 $logger = LoggerFactory::getInstance(
'wfLogDBError' );
978 $logger->error( trim( $text ), $context );
997function wfDeprecated( $function, $version =
false, $component =
false, $callerOffset = 2 ) {
998 if ( !is_string( $version ) && $version !==
false ) {
999 throw new InvalidArgumentException(
1000 "MediaWiki version must either be a string or false. " .
1001 "Example valid version: '1.33'"
1005 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1028function wfDeprecatedMsg( $msg, $version =
false, $component =
false, $callerOffset = 2 ) {
1029 MWDebug::deprecatedMsg( $msg, $version, $component,
1030 $callerOffset ===
false ?
false : $callerOffset + 1 );
1043function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1044 MWDebug::warning( $msg, $callerOffset + 1, $level,
'auto' );
1057 MWDebug::warning( $msg, $callerOffset + 1, $level,
'production' );
1065 $context = RequestContext::getMain();
1067 $profiler = Profiler::instance();
1068 $profiler->setContext( $context );
1069 $profiler->logData();
1072 MediaWiki::emitBufferedStatsdData(
1073 MediaWikiServices::getInstance()->getStatsdDataFactory(),
1074 $context->getConfig()
1090 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1091 $stats->updateCount( $key, $count );
1100 return MediaWikiServices::getInstance()->getReadOnlyMode()
1113 return MediaWikiServices::getInstance()->getReadOnlyMode()
1133 # Identify which language to get or create a language object for.
1134 # Using is_object here due to Stub objects.
1135 if ( is_object( $langcode ) ) {
1136 # Great, we already have the object (hopefully)!
1141 $services = MediaWikiServices::getInstance();
1143 # $langcode is the language code of the wikis content language object.
1144 # or it is a boolean and value is true
1145 return $services->getContentLanguage();
1149 if ( $langcode ===
false || $langcode ===
$wgLang->getCode() ) {
1150 # $langcode is the language code of user language object.
1151 # or it was a boolean and value is false
1155 $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1156 if ( in_array( $langcode, $validCodes ) ) {
1157 # $langcode corresponds to a valid language.
1158 return $services->getLanguageFactory()->getLanguage( $langcode );
1161 # $langcode is a string, but not a valid language code; use content language.
1162 wfDebug(
"Invalid language code passed to wfGetLangObj, falling back to content language." );
1163 return $services->getContentLanguage();
1183 $message =
new Message( $key );
1187 $message->params( ...$params );
1218 # Fix windows line-endings
1219 # Some messages are split with explode("\n", $msg)
1220 $message = str_replace(
"\r",
'', $message );
1224 if ( is_array(
$args[0] ) ) {
1227 $replacementKeys = [];
1228 foreach (
$args as $n => $param ) {
1229 $replacementKeys[
'$' . ( $n + 1 )] = $param;
1231 $message = strtr( $message, $replacementKeys );
1252 return php_uname(
'n' ) ?:
'unknown';
1268 $elapsed = ( microtime(
true ) - $_SERVER[
'REQUEST_TIME_FLOAT'] );
1270 $responseTime = round( $elapsed * 1000 );
1271 $reportVars = [
'wgBackendResponseTime' => $responseTime ];
1295 static $disabled =
null;
1297 if ( $disabled ===
null ) {
1298 $disabled = !function_exists(
'debug_backtrace' );
1300 wfDebug(
"debug_backtrace() is disabled" );
1308 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1310 return array_slice( debug_backtrace(), 1 );
1325 if ( $raw ===
null ) {
1330 $frameFormat =
"%s line %s calls %s()\n";
1331 $traceFormat =
"%s";
1333 $frameFormat =
"<li>%s line %s calls %s()</li>\n";
1334 $traceFormat =
"<ul>\n%s</ul>\n";
1337 $frames = array_map(
static function ( $frame ) use ( $frameFormat ) {
1338 $file = !empty( $frame[
'file'] ) ? basename( $frame[
'file'] ) :
'-';
1339 $line = $frame[
'line'] ??
'-';
1340 $call = $frame[
'function'];
1341 if ( !empty( $frame[
'class'] ) ) {
1342 $call = $frame[
'class'] . $frame[
'type'] . $call;
1344 return sprintf( $frameFormat,
$file,
$line, $call );
1347 return sprintf( $traceFormat, implode(
'', $frames ) );
1361 if ( isset( $backtrace[$level] ) ) {
1377 if ( !$limit || $limit > count( $trace ) - 1 ) {
1378 $limit = count( $trace ) - 1;
1380 $trace = array_slice( $trace, -$limit - 1, $limit );
1381 return implode(
'/', array_map(
'wfFormatStackFrame', $trace ) );
1391 if ( !isset( $frame[
'function'] ) ) {
1392 return 'NO_FUNCTION_GIVEN';
1394 return isset( $frame[
'class'] ) && isset( $frame[
'type'] ) ?
1395 $frame[
'class'] . $frame[
'type'] . $frame[
'function'] :
1409 return wfMessage(
'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1422 static $result =
null;
1423 if ( $result ===
null || $force ) {
1425 if ( isset( $_SERVER[
'HTTP_ACCEPT_ENCODING'] ) ) {
1426 # @todo FIXME: We may want to disallow some broken browsers
1429 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1430 $_SERVER[
'HTTP_ACCEPT_ENCODING'],
1434 if ( isset( $m[2] ) && ( $m[1] ==
'q' ) && ( $m[2] == 0 ) ) {
1437 wfDebug(
"wfClientAcceptsGzip: client accepts gzip." );
1457 static $repl =
null, $repl2 =
null;
1458 if ( $repl ===
null || defined(
'MW_PARSER_TEST' ) || defined(
'MW_PHPUNIT_TEST' ) ) {
1462 '"' =>
'"',
'&' =>
'&',
"'" =>
''',
'<' =>
'<',
1463 '=' =>
'=',
'>' =>
'>',
'[' =>
'[',
']' =>
']',
1464 '{' =>
'{',
'|' =>
'|',
'}' =>
'}',
';' =>
';',
1465 "\n#" =>
"\n#",
"\r#" =>
"\r#",
1466 "\n*" =>
"\n*",
"\r*" =>
"\r*",
1467 "\n:" =>
"\n:",
"\r:" =>
"\r:",
1468 "\n " =>
"\n ",
"\r " =>
"\r ",
1469 "\n\n" =>
"\n ",
"\r\n" =>
" \n",
1470 "\n\r" =>
"\n ",
"\r\r" =>
"\r ",
1471 "\n\t" =>
"\n	",
"\r\t" =>
"\r	",
1472 "\n----" =>
"\n----",
"\r----" =>
"\r----",
1473 '__' =>
'__',
'://' =>
'://',
1478 foreach ( $magicLinks as $magic ) {
1479 $repl[
"$magic "] =
"$magic ";
1480 $repl[
"$magic\t"] =
"$magic	";
1481 $repl[
"$magic\r"] =
"$magic ";
1482 $repl[
"$magic\n"] =
"$magic ";
1483 $repl[
"$magic\f"] =
"$magic";
1490 if ( substr( $prot, -1 ) ===
':' ) {
1491 $repl2[] = preg_quote( substr( $prot, 0, -1 ),
'/' );
1494 $repl2 = $repl2 ?
'/\b(' . implode(
'|', $repl2 ) .
'):/i' :
'/^(?!)/';
1496 $text = substr( strtr(
"\n$text", $repl ), 1 );
1497 $text = preg_replace( $repl2,
'$1:', $text );
1513 if (
$source !==
null || $force ) {
1529 $temp = (bool)( $dest & $bit );
1530 if ( $state !==
null ) {
1548 $s = str_replace(
"\n",
"<br />\n", var_export( $var,
true ) .
"\n" );
1549 if ( headers_sent() || !isset(
$wgOut ) || !is_object(
$wgOut ) ) {
1565 HttpStatus::header( $code );
1568 $wgOut->sendCacheControl();
1571 MediaWiki\HeaderCallback::warnIfHeadersSent();
1572 header(
'Content-type: text/html; charset=utf-8' );
1574 print '<!DOCTYPE html>' .
1575 '<html><head><title>' .
1576 htmlspecialchars( $label ) .
1577 '</title></head><body><h1>' .
1578 htmlspecialchars( $label ) .
1580 nl2br( htmlspecialchars( $desc ) ) .
1581 "</p></body></html>\n";
1582 header(
'Content-Length: ' . ob_get_length() );
1604 while ( $status = ob_get_status() ) {
1605 if ( isset( $status[
'flags'] ) ) {
1606 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1607 $deleteable = ( $status[
'flags'] & $flags ) === $flags;
1608 } elseif ( isset( $status[
'del'] ) ) {
1609 $deleteable = $status[
'del'];
1612 $deleteable = $status[
'type'] !== 0;
1614 if ( !$deleteable ) {
1619 if ( $status[
'name'] ===
'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1623 if ( !ob_end_clean() ) {
1628 if ( $resetGzipEncoding && $status[
'name'] ==
'ob_gzhandler' ) {
1631 header_remove(
'Content-Encoding' );
1669 if ( array_key_exists(
$type, $avail ) ) {
1672 $mainType = explode(
'/',
$type )[0];
1673 if ( array_key_exists(
"$mainType/*", $avail ) ) {
1674 return "$mainType/*";
1675 } elseif ( array_key_exists(
'*/*', $avail ) ) {
1692 $ret = MWTimestamp::convert( $outputtype, $ts );
1693 if ( $ret ===
false ) {
1694 wfDebug(
"wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1708 if ( $ts ===
null ) {
1721 return MWTimestamp::now( TS_MW );
1730 return PHP_OS_FAMILY ===
'Windows';
1740 return PHP_SAPI ===
'cli' || PHP_SAPI ===
'phpdbg';
1761 return TempFSFile::getUsableTempDirectory();
1777 throw new MWException( __FUNCTION__ .
" given storage path '$dir'." );
1780 if ( $caller !==
null ) {
1781 wfDebug(
"$caller: called wfMkdirParents($dir)" );
1784 if ( strval( $dir ) ===
'' || is_dir( $dir ) ) {
1788 $dir = str_replace( [
'\\',
'/' ], DIRECTORY_SEPARATOR, $dir );
1790 if ( $mode ===
null ) {
1795 AtEase::suppressWarnings();
1796 $ok = mkdir( $dir, $mode,
true );
1797 AtEase::restoreWarnings();
1801 if ( is_dir( $dir ) ) {
1806 wfLogWarning( sprintf(
"failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1817 wfDebug( __FUNCTION__ .
"( $dir )" );
1819 if ( is_dir( $dir ) ) {
1820 $objects = scandir( $dir );
1821 foreach ( $objects as $object ) {
1822 if ( $object !=
"." && $object !=
".." ) {
1823 if ( filetype( $dir .
'/' . $object ) ==
"dir" ) {
1826 unlink( $dir .
'/' . $object );
1841function wfPercent( $nr,
int $acc = 2,
bool $round =
true ) {
1842 $accForFormat = $acc >= 0 ? $acc : 0;
1843 $ret = sprintf(
"%.{$accForFormat}f", $nr );
1844 return $round ? round( (
float)$ret, $acc ) .
'%' :
"$ret%";
1887 $val = strtolower( $val );
1892 || preg_match(
"/^\s*[+-]?0*[1-9]/", $val );
1908 return Shell::escape( ...
$args );
1936 $limits = [], $options = []
1938 if ( Shell::isDisabled() ) {
1941 return 'Unable to run external programs, proc_open() is disabled.';
1944 if ( is_array( $cmd ) ) {
1945 $cmd = Shell::escape( $cmd );
1948 $includeStderr = isset( $options[
'duplicateStderr'] ) && $options[
'duplicateStderr'];
1949 $profileMethod = $options[
'profileMethod'] ??
wfGetCaller();
1952 $result = Shell::command( [] )
1953 ->unsafeParams( (array)$cmd )
1954 ->environment( $environ )
1956 ->includeStderr( $includeStderr )
1957 ->profileMethod( $profileMethod )
1959 ->restrict( Shell::RESTRICT_NONE )
1966 $retval = $result->getExitCode();
1968 return $result->getStdout();
1989 return wfShellExec( $cmd, $retval, $environ, $limits,
1990 [
'duplicateStderr' =>
true,
'profileMethod' =>
wfGetCaller() ] );
2012 Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
2013 $cmd = [ $options[
'php'] ??
$wgPhpCli ];
2014 if ( isset( $options[
'wrapper'] ) ) {
2015 $cmd[] = $options[
'wrapper'];
2019 return Shell::escape( array_merge( $cmd, $parameters ) );
2033function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult =
null ) {
2036 # This check may also protect against code injection in
2037 # case of broken installations.
2038 AtEase::suppressWarnings();
2040 AtEase::restoreWarnings();
2042 if ( !$haveDiff3 ) {
2047 # Make temporary files
2049 $oldtextFile = fopen( $oldtextName = tempnam( $td,
'merge-old-' ),
'w' );
2050 $mytextFile = fopen( $mytextName = tempnam( $td,
'merge-mine-' ),
'w' );
2051 $yourtextFile = fopen( $yourtextName = tempnam( $td,
'merge-your-' ),
'w' );
2053 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2054 # a newline character. To avoid this, we normalize the trailing whitespace before
2055 # creating the diff.
2057 fwrite( $oldtextFile, rtrim( $old ) .
"\n" );
2058 fclose( $oldtextFile );
2059 fwrite( $mytextFile, rtrim( $mine ) .
"\n" );
2060 fclose( $mytextFile );
2061 fwrite( $yourtextFile, rtrim( $yours ) .
"\n" );
2062 fclose( $yourtextFile );
2064 # Check for a conflict
2065 $cmd = Shell::escape(
$wgDiff3,
'-a',
'--overlap-only', $mytextName,
2066 $oldtextName, $yourtextName );
2067 $handle = popen( $cmd,
'r' );
2069 $mergeAttemptResult =
'';
2071 $data = fread( $handle, 8192 );
2072 if ( strlen( $data ) == 0 ) {
2075 $mergeAttemptResult .= $data;
2079 $conflict = $mergeAttemptResult !==
'';
2082 $cmd = Shell::escape(
$wgDiff3,
'-a',
'-e',
'--merge', $mytextName,
2083 $oldtextName, $yourtextName );
2084 $handle = popen( $cmd,
'r' );
2087 $data = fread( $handle, 8192 );
2088 if ( strlen( $data ) == 0 ) {
2094 unlink( $mytextName );
2095 unlink( $oldtextName );
2096 unlink( $yourtextName );
2098 if ( $result ===
'' && $old !==
'' && !$conflict ) {
2099 wfDebug(
"Unexpected null result from diff3. Command: $cmd" );
2118 if ( $suffix ==
'' ) {
2121 $encSuffix =
'(?:' . preg_quote( $suffix,
'#' ) .
')?';
2125 if ( preg_match(
"#([^/\\\\]*?){$encSuffix}[/\\\\]*$#",
$path,
$matches ) ) {
2143 $path = str_replace(
'/', DIRECTORY_SEPARATOR,
$path );
2144 $from = str_replace(
'/', DIRECTORY_SEPARATOR, $from );
2148 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2150 $pieces = explode( DIRECTORY_SEPARATOR, dirname(
$path ) );
2151 $against = explode( DIRECTORY_SEPARATOR, $from );
2153 if ( $pieces[0] !== $against[0] ) {
2160 while ( count( $pieces ) && count( $against )
2161 && $pieces[0] == $against[0] ) {
2162 array_shift( $pieces );
2163 array_shift( $against );
2167 while ( count( $against ) ) {
2168 array_unshift( $pieces,
'..' );
2169 array_shift( $against );
2174 return implode( DIRECTORY_SEPARATOR, $pieces );
2188 return "$wgDBname-$wgDBprefix";
2225function wfGetDB( $db, $groups = [], $wiki =
false ) {
2226 if ( $wiki ===
false ) {
2227 return MediaWikiServices::getInstance()
2228 ->getDBLoadBalancer()
2229 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2231 return MediaWikiServices::getInstance()
2232 ->getDBLoadBalancerFactory()
2233 ->getMainLB( $wiki )
2234 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2250 if ( $wiki ===
false ) {
2252 return MediaWikiServices::getInstance()->getDBLoadBalancer();
2254 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2256 return $factory->getMainLB( $wiki );
2269 return MediaWikiServices::getInstance()->getRepoGroup()->findFile(
$title, $options );
2282 return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile(
$title );
2309 if ( $script ===
'index' ) {
2311 } elseif ( $script ===
'load' ) {
2314 return "{$wgScriptPath}/{$script}.php";
2326 if ( isset( $_SERVER[
'SCRIPT_NAME'] ) ) {
2337 return $_SERVER[
'SCRIPT_NAME'];
2339 return $_SERVER[
'URL'];
2351 return $value ?
'true' :
'false';
2374 $name = preg_replace(
2375 "/[^" . Title::legalChars() .
"]" . $illegalFileChars .
"/",
2393 if ( $oldLimit != -1 ) {
2395 if ( $newLimit == -1 ) {
2396 wfDebug(
"Removing PHP's memory limit" );
2397 Wikimedia\suppressWarnings();
2398 ini_set(
'memory_limit', $newLimit );
2399 Wikimedia\restoreWarnings();
2400 } elseif ( $newLimit > $oldLimit ) {
2401 wfDebug(
"Raising PHP's memory limit to $newLimit bytes" );
2402 Wikimedia\suppressWarnings();
2403 ini_set(
'memory_limit', $newLimit );
2404 Wikimedia\restoreWarnings();
2418 $timeout = RequestTimeout::singleton();
2419 $timeLimit = $timeout->getWallTimeLimit();
2420 if ( $timeLimit !== INF ) {
2427 $timeLimit = (int)ini_get(
'max_execution_time' );
2433 ignore_user_abort(
true );
2446 $string = trim( $string ??
'' );
2447 if ( $string ===
'' ) {
2450 $last = $string[strlen( $string ) - 1];
2451 $val = intval( $string );
2477 return ObjectCache::getInstance( $cacheType );
2487 return ObjectCache::getLocalClusterInstance();
2505 if ( $length !==
false ) {
2506 $realLen = strlen( $data );
2507 if ( $realLen < $length ) {
2508 throw new MWException(
"Tried to use wfUnpack on a "
2509 .
"string of length $realLen, but needed one "
2510 .
"of at least length $length."
2515 Wikimedia\suppressWarnings();
2516 $result = unpack( $format, $data );
2517 Wikimedia\restoreWarnings();
2519 if ( $result ===
false ) {
2521 throw new MWException(
"unpack could not unpack binary data" );
2549 return in_array( $str, ExpiryDef::INFINITY_VALS );
2569 $multipliers = [ 1 ];
2573 $multipliers[] = 1.5;
2577 $handler =
$file->getHandler();
2578 if ( !$handler || !isset( $params[
'width'] ) ) {
2583 if ( isset( $params[
'page'] ) ) {
2584 $basicParams[
'page'] = $params[
'page'];
2590 foreach ( $multipliers as $multiplier ) {
2591 $thumbLimits = array_merge( $thumbLimits, array_map(
2592 static function ( $width ) use ( $multiplier ) {
2593 return round( $width * $multiplier );
2596 $imageLimits = array_merge( $imageLimits, array_map(
2597 static function ( $pair ) use ( $multiplier ) {
2599 round( $pair[0] * $multiplier ),
2600 round( $pair[1] * $multiplier ),
2607 if ( in_array( $params[
'width'], $thumbLimits ) ) {
2608 $normalParams = $basicParams + [
'width' => $params[
'width'] ];
2610 $handler->normaliseParams(
$file, $normalParams );
2614 foreach ( $imageLimits as $pair ) {
2615 $normalParams = $basicParams + [
'width' => $pair[0],
'height' => $pair[1] ];
2618 $handler->normaliseParams(
$file, $normalParams );
2620 if ( $normalParams[
'width'] == $params[
'width'] ) {
2631 foreach ( $params as $key => $value ) {
2632 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2654 foreach ( $baseArray as $name => &$groupVal ) {
2655 if ( isset( $newValues[$name] ) ) {
2656 $groupVal += $newValues[$name];
2660 $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)
Version of escapeshellarg() that works better on Windows.
wfIncrStats( $key, $count=1)
Increment a statistics counter.
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.
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...
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
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...
wfArrayDiff2_cmp( $a, $b)
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?
mimeTypeMatch( $type, $avail)
Checks if a given MIME type matches any of the keys in the given array.
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 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.
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...
The Message class deals with fetching and processing of interface message into a variety of formats.
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
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