31use Wikimedia\AtEase\AtEase;
33use Wikimedia\RequestTimeout\RequestTimeout;
34use Wikimedia\WrappedString;
49 $path =
"$wgExtensionDirectory/$ext/extension.json";
51 ExtensionRegistry::getInstance()->queue(
$path );
69 $registry = ExtensionRegistry::getInstance();
70 foreach ( $exts as
$ext ) {
71 $registry->queue(
"$wgExtensionDirectory/$ext/extension.json" );
86 $path =
"$wgStyleDirectory/$skin/skin.json";
88 ExtensionRegistry::getInstance()->queue(
$path );
100 $registry = ExtensionRegistry::getInstance();
101 foreach ( $skins as $skin ) {
102 $registry->queue(
"$wgStyleDirectory/$skin/skin.json" );
117 $comparator =
static function ( $a, $b ):
int {
118 if ( is_string( $a ) && is_string( $b ) ) {
119 return strcmp( $a, $b );
121 if ( !is_array( $a ) && !is_array( $b ) ) {
122 throw new InvalidArgumentException(
123 'This function assumes that array elements are all strings or all arrays'
126 if ( count( $a ) !== count( $b ) ) {
127 return count( $a ) <=> count( $b );
131 while ( key( $a ) !==
null && key( $b ) !==
null ) {
132 $valueA = current( $a );
133 $valueB = current( $b );
134 $cmp = strcmp( $valueA, $valueB );
144 return array_udiff( $arr1, $arr2, $comparator );
168 foreach ( $args as $errors ) {
169 foreach ( $errors as $params ) {
170 $originalParams = $params;
173 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
175 # @todo FIXME: Sometimes get nested arrays for $params,
176 # which leads to E_NOTICEs
177 $spec = implode(
"\t", $params );
178 $out[$spec] = $originalParams;
181 return array_values( $out );
195 $keys = array_keys( $array );
196 $offsetByKey = array_flip(
$keys );
198 if ( !\array_key_exists( $after, $offsetByKey ) ) {
201 $offset = $offsetByKey[$after];
204 $before = array_slice( $array, 0, $offset + 1,
true );
205 $after = array_slice( $array, $offset + 1, count( $array ) - $offset,
true );
207 $output = $before + $insert + $after;
222 if ( is_object( $objOrArray ) ) {
223 $objOrArray = get_object_vars( $objOrArray );
225 foreach ( $objOrArray as $key => $value ) {
226 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
230 $array[$key] = $value;
249 $max = mt_getrandmax() + 1;
250 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12,
'.',
'' );
266 for ( $n = 0; $n < $length; $n += 7 ) {
267 $str .= sprintf(
'%07x', mt_rand() & 0xfffffff );
269 return substr( $str, 0, $length );
308 if ( $needle ===
null ) {
309 $needle = [
'%3B',
'%40',
'%24',
'%21',
'%2A',
'%28',
'%29',
'%2C',
'%2F',
'%7E' ];
310 if ( !isset( $_SERVER[
'SERVER_SOFTWARE'] ) ||
311 ( strpos( $_SERVER[
'SERVER_SOFTWARE'],
'Microsoft-IIS/7' ) ===
false )
317 $s = urlencode( $s );
320 [
';',
'@',
'$',
'!',
'*',
'(',
')',
',',
'/',
'~',
':' ],
338 if ( $array2 !==
null ) {
343 foreach ( $array1 as $key => $value ) {
344 if ( $value !==
null && $value !==
false ) {
348 if ( $prefix !==
'' ) {
349 $key = $prefix .
"[$key]";
351 if ( is_array( $value ) ) {
353 foreach ( $value as $k => $v ) {
354 $cgi .= $firstTime ?
'' :
'&';
355 if ( is_array( $v ) ) {
358 $cgi .= urlencode( $key .
"[$k]" ) .
'=' . urlencode( $v );
363 if ( is_object( $value ) ) {
364 $value = $value->__toString();
366 $cgi .= urlencode( $key ) .
'=' . urlencode( $value );
383 if ( isset( $query[0] ) && $query[0] ==
'?' ) {
384 $query = substr( $query, 1 );
386 $bits = explode(
'&', $query );
388 foreach ( $bits as $bit ) {
392 if ( strpos( $bit,
'=' ) ===
false ) {
397 [ $key, $value ] = explode(
'=', $bit );
399 $key = urldecode( $key );
400 $value = urldecode( $value );
401 if ( strpos( $key,
'[' ) !==
false ) {
402 $keys = array_reverse( explode(
'[', $key ) );
403 $key = array_pop(
$keys );
405 foreach (
$keys as $k ) {
406 $k = substr( $k, 0, -1 );
407 $temp = [ $k => $temp ];
409 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
410 $ret[$key] = array_merge( $ret[$key], $temp );
430 if ( is_array( $query ) ) {
433 if ( $query !=
'' ) {
436 $hashPos = strpos( $url,
'#' );
437 if ( $hashPos !==
false ) {
438 $fragment = substr( $url, $hashPos );
439 $url = substr( $url, 0, $hashPos );
443 if ( strpos( $url,
'?' ) ===
false ) {
451 if ( $fragment !==
false ) {
467 if ( MediaWikiServices::hasInstance() ) {
468 $services = MediaWikiServices::getInstance();
469 if ( $services->hasService(
'UrlUtils' ) ) {
470 return $services->getUrlUtils();
554 return wfGetUrlUtils()->removeDotSegments( (
string)$urlPath );
566 $method = $includeProtocolRelative ?
'validProtocols' :
'validAbsoluteProtocols';
633 return wfGetUrlUtils()->matchesDomainList( (
string)$url, (array)$domains );
656function wfDebug( $text, $dest =
'all', array $context = [] ) {
663 $text = trim( $text );
668 $context[
'private'] = ( $dest ===
false || $dest ===
'private' );
670 $logger = LoggerFactory::getInstance(
'wfDebug' );
671 $logger->debug( $text, $context );
680 if ( $cache !==
null ) {
685 if ( ( isset( $_GET[
'action'] ) && $_GET[
'action'] ==
'raw' )
721 $logGroup, $text, $dest =
'all', array $context = []
723 $text = trim( $text );
725 $logger = LoggerFactory::getInstance( $logGroup );
726 $context[
'private'] = ( $dest ===
false || $dest ===
'private' );
727 $logger->info( $text, $context );
739 $logger = LoggerFactory::getInstance(
'wfLogDBError' );
740 $logger->error( trim( $text ), $context );
759function wfDeprecated( $function, $version =
false, $component =
false, $callerOffset = 2 ) {
760 if ( !is_string( $version ) && $version !==
false ) {
761 throw new InvalidArgumentException(
762 "MediaWiki version must either be a string or false. " .
763 "Example valid version: '1.33'"
767 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
790function wfDeprecatedMsg( $msg, $version =
false, $component =
false, $callerOffset = 2 ) {
791 MWDebug::deprecatedMsg( $msg, $version, $component,
792 $callerOffset ===
false ?
false : $callerOffset + 1 );
805function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
806 MWDebug::warning( $msg, $callerOffset + 1, $level,
'auto' );
818function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
819 MWDebug::warning( $msg, $callerOffset + 1, $level,
'production' );
838 # Identify which language to get or create a language object for.
839 # Using is_object here due to Stub objects.
840 if ( is_object( $langcode ) ) {
841 # Great, we already have the object (hopefully)!
846 $services = MediaWikiServices::getInstance();
848 # $langcode is the language code of the wikis content language object.
849 # or it is a boolean and value is true
850 return $services->getContentLanguage();
854 if ( $langcode ===
false || $langcode ===
$wgLang->getCode() ) {
855 # $langcode is the language code of user language object.
856 # or it was a boolean and value is false
860 $languageNames = $services->getLanguageNameUtils()->getLanguageNames();
862 if ( isset( $languageNames[$langcode] ) ) {
863 # $langcode corresponds to a valid language.
864 return $services->getLanguageFactory()->getLanguage( $langcode );
867 # $langcode is a string, but not a valid language code; use content language.
868 wfDebug(
"Invalid language code passed to wfGetLangObj, falling back to content language." );
869 return $services->getContentLanguage();
894 if ( is_array( $key ) ) {
903 $message->params( ...$params );
934 # Fix windows line-endings
935 # Some messages are split with explode("\n", $msg)
936 $message = str_replace(
"\r",
'', $message );
939 if ( is_array( $args ) && $args ) {
940 if ( is_array( $args[0] ) ) {
941 $args = array_values( $args[0] );
943 $replacementKeys = [];
944 foreach ( $args as $n => $param ) {
945 $replacementKeys[
'$' . ( $n + 1 )] = $param;
947 $message = strtr( $message, $replacementKeys );
968 return php_uname(
'n' ) ?:
'unknown';
985 $elapsed = ( microtime(
true ) - $_SERVER[
'REQUEST_TIME_FLOAT'] );
987 $responseTime = round( $elapsed * 1000 );
988 $reportVars = [
'wgBackendResponseTime' => $responseTime ];
994 ResourceLoader::makeInlineScript(
995 ResourceLoader::makeConfigSetScript( $reportVars ),
1012 static $disabled =
null;
1014 if ( $disabled ===
null ) {
1015 $disabled = !function_exists(
'debug_backtrace' );
1017 wfDebug(
"debug_backtrace() is disabled" );
1025 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1027 return array_slice( debug_backtrace(), 1 );
1043 $frameFormat =
"%s line %s calls %s()\n";
1044 $traceFormat =
"%s";
1046 $frameFormat =
"<li>%s line %s calls %s()</li>\n";
1047 $traceFormat =
"<ul>\n%s</ul>\n";
1050 $frames = array_map(
static function ( $frame ) use ( $frameFormat ) {
1051 $file = !empty( $frame[
'file'] ) ? basename( $frame[
'file'] ) :
'-';
1052 $line = $frame[
'line'] ??
'-';
1053 $call = $frame[
'function'];
1054 if ( !empty( $frame[
'class'] ) ) {
1055 $call = $frame[
'class'] . $frame[
'type'] . $call;
1057 return sprintf( $frameFormat,
$file, $line, $call );
1060 return sprintf( $traceFormat, implode(
'', $frames ) );
1074 if ( isset( $backtrace[$level] ) ) {
1090 if ( !$limit || $limit > count( $trace ) - 1 ) {
1091 $limit = count( $trace ) - 1;
1093 $trace = array_slice( $trace, -$limit - 1, $limit );
1094 return implode(
'/', array_map(
'wfFormatStackFrame', $trace ) );
1104 if ( !isset( $frame[
'function'] ) ) {
1105 return 'NO_FUNCTION_GIVEN';
1107 return isset( $frame[
'class'] ) && isset( $frame[
'type'] ) ?
1108 $frame[
'class'] . $frame[
'type'] . $frame[
'function'] :
1124 return wfMessage(
'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1137 static $result =
null;
1138 if ( $result ===
null || $force ) {
1140 if ( isset( $_SERVER[
'HTTP_ACCEPT_ENCODING'] ) ) {
1141 # @todo FIXME: We may want to disallow some broken browsers
1144 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1145 $_SERVER[
'HTTP_ACCEPT_ENCODING'],
1149 if ( isset( $m[2] ) && ( $m[1] ==
'q' ) && ( $m[2] == 0 ) ) {
1152 wfDebug(
"wfClientAcceptsGzip: client accepts gzip." );
1172 static $repl =
null, $repl2 =
null;
1173 if ( $repl ===
null || defined(
'MW_PARSER_TEST' ) || defined(
'MW_PHPUNIT_TEST' ) ) {
1177 '"' =>
'"',
'&' =>
'&',
"'" =>
''',
'<' =>
'<',
1178 '=' =>
'=',
'>' =>
'>',
'[' =>
'[',
']' =>
']',
1179 '{' =>
'{',
'|' =>
'|',
'}' =>
'}',
';' =>
';',
1180 "\n#" =>
"\n#",
"\r#" =>
"\r#",
1181 "\n*" =>
"\n*",
"\r*" =>
"\r*",
1182 "\n:" =>
"\n:",
"\r:" =>
"\r:",
1183 "\n " =>
"\n ",
"\r " =>
"\r ",
1184 "\n\n" =>
"\n ",
"\r\n" =>
" \n",
1185 "\n\r" =>
"\n ",
"\r\r" =>
"\r ",
1186 "\n\t" =>
"\n	",
"\r\t" =>
"\r	",
1187 "\n----" =>
"\n----",
"\r----" =>
"\r----",
1188 '__' =>
'__',
'://' =>
'://',
1193 foreach ( $magicLinks as $magic ) {
1194 $repl[
"$magic "] =
"$magic ";
1195 $repl[
"$magic\t"] =
"$magic	";
1196 $repl[
"$magic\r"] =
"$magic ";
1197 $repl[
"$magic\n"] =
"$magic ";
1198 $repl[
"$magic\f"] =
"$magic";
1205 if ( substr( $prot, -1 ) ===
':' ) {
1206 $repl2[] = preg_quote( substr( $prot, 0, -1 ),
'/' );
1209 $repl2 = $repl2 ?
'/\b(' . implode(
'|', $repl2 ) .
'):/i' :
'/^(?!)/';
1211 $text = substr( strtr(
"\n$text", $repl ), 1 );
1213 $text = preg_replace( $repl2,
'$1:', $text );
1229 if (
$source !==
null || $force ) {
1245 $temp = (bool)( $dest & $bit );
1246 if ( $state !==
null ) {
1264 $s = str_replace(
"\n",
"<br />\n", var_export( $var,
true ) .
"\n" );
1265 if ( headers_sent() || !isset(
$wgOut ) || !is_object(
$wgOut ) ) {
1281 HttpStatus::header( $code );
1284 $wgOut->sendCacheControl();
1287 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1288 header(
'Content-type: text/html; charset=utf-8' );
1290 print
'<!DOCTYPE html>' .
1291 '<html><head><title>' .
1292 htmlspecialchars( $label ) .
1293 '</title></head><body><h1>' .
1294 htmlspecialchars( $label ) .
1296 nl2br( htmlspecialchars( $desc ) ) .
1297 "</p></body></html>\n";
1298 header(
'Content-Length: ' . ob_get_length() );
1320 while ( $status = ob_get_status() ) {
1321 if ( isset( $status[
'flags'] ) ) {
1322 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1323 $deleteable = ( $status[
'flags'] & $flags ) === $flags;
1324 } elseif ( isset( $status[
'del'] ) ) {
1325 $deleteable = $status[
'del'];
1328 $deleteable = $status[
'type'] !== 0;
1330 if ( !$deleteable ) {
1335 if ( $status[
'name'] ===
'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1339 if ( !ob_end_clean() ) {
1344 if ( $resetGzipEncoding && $status[
'name'] ==
'ob_gzhandler' ) {
1347 header_remove(
'Content-Encoding' );
1383 $ret = MWTimestamp::convert( $outputtype, $ts );
1384 if ( $ret ===
false ) {
1385 wfDebug(
"wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1399 if ( $ts ===
null ) {
1412 return MWTimestamp::now( TS_MW );
1433 return TempFSFile::getUsableTempDirectory();
1449 throw new MWException( __FUNCTION__ .
" given storage path '$dir'." );
1452 if ( $caller !==
null ) {
1453 wfDebug(
"$caller: called wfMkdirParents($dir)" );
1456 if ( strval( $dir ) ===
'' || is_dir( $dir ) ) {
1460 $dir = str_replace( [
'\\',
'/' ], DIRECTORY_SEPARATOR, $dir );
1462 if ( $mode ===
null ) {
1467 AtEase::suppressWarnings();
1468 $ok = mkdir( $dir, $mode,
true );
1469 AtEase::restoreWarnings();
1473 if ( is_dir( $dir ) ) {
1478 wfLogWarning( sprintf(
"failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1490 if ( is_dir( $dir ) ) {
1491 $objects = scandir( $dir );
1492 foreach ( $objects as $object ) {
1493 if ( $object !=
"." && $object !=
".." ) {
1494 if ( filetype( $dir .
'/' . $object ) ==
"dir" ) {
1497 unlink( $dir .
'/' . $object );
1512function wfPercent( $nr,
int $acc = 2,
bool $round =
true ) {
1513 $accForFormat = $acc >= 0 ? $acc : 0;
1514 $ret = sprintf(
"%.{$accForFormat}f", $nr );
1515 return $round ? round( (
float)$ret, $acc ) .
'%' :
"$ret%";
1558 $val = strtolower( $val );
1563 || preg_match(
"/^\s*[+-]?0*[1-9]/", $val );
1580 return Shell::escape( ...$args );
1608 $limits = [], $options = []
1610 if ( Shell::isDisabled() ) {
1613 return 'Unable to run external programs, proc_open() is disabled.';
1616 if ( is_array( $cmd ) ) {
1617 $cmd = Shell::escape( $cmd );
1620 $includeStderr = isset( $options[
'duplicateStderr'] ) && $options[
'duplicateStderr'];
1621 $profileMethod = $options[
'profileMethod'] ??
wfGetCaller();
1624 $result = Shell::command( [] )
1625 ->unsafeParams( (array)$cmd )
1626 ->environment( $environ )
1628 ->includeStderr( $includeStderr )
1629 ->profileMethod( $profileMethod )
1631 ->restrict( Shell::RESTRICT_NONE )
1638 $retval = $result->getExitCode();
1640 return $result->getStdout();
1661 return wfShellExec( $cmd, $retval, $environ, $limits,
1662 [
'duplicateStderr' =>
true,
'profileMethod' =>
wfGetCaller() ] );
1684 Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
1685 $cmd = [ $options[
'php'] ??
$wgPhpCli ];
1686 if ( isset( $options[
'wrapper'] ) ) {
1687 $cmd[] = $options[
'wrapper'];
1691 return Shell::escape( array_merge( $cmd, $parameters ) );
1714 ?
string &$simplisticMergeAttempt,
1715 string &$mergeLeftovers =
null
1719 # This check may also protect against code injection in
1720 # case of broken installations.
1721 AtEase::suppressWarnings();
1723 AtEase::restoreWarnings();
1725 if ( !$haveDiff3 ) {
1730 # Make temporary files
1732 $oldtextFile = fopen( $oldtextName = tempnam( $td,
'merge-old-' ),
'w' );
1733 $mytextFile = fopen( $mytextName = tempnam( $td,
'merge-mine-' ),
'w' );
1734 $yourtextFile = fopen( $yourtextName = tempnam( $td,
'merge-your-' ),
'w' );
1736 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1737 # a newline character. To avoid this, we normalize the trailing whitespace before
1738 # creating the diff.
1740 fwrite( $oldtextFile, rtrim( $old ) .
"\n" );
1741 fclose( $oldtextFile );
1742 fwrite( $mytextFile, rtrim( $mine ) .
"\n" );
1743 fclose( $mytextFile );
1744 fwrite( $yourtextFile, rtrim( $yours ) .
"\n" );
1745 fclose( $yourtextFile );
1747 # Check for a conflict
1748 $cmd = Shell::escape(
$wgDiff3,
'--text',
'--overlap-only', $mytextName,
1749 $oldtextName, $yourtextName );
1750 $handle = popen( $cmd,
'r' );
1752 $mergeLeftovers =
'';
1754 $data = fread( $handle, 8192 );
1755 if ( strlen( $data ) == 0 ) {
1758 $mergeLeftovers .= $data;
1762 $conflict = $mergeLeftovers !==
'';
1764 # Merge differences automatically where possible, preferring "my" text for conflicts.
1765 $cmd = Shell::escape(
$wgDiff3,
'--text',
'--ed',
'--merge', $mytextName,
1766 $oldtextName, $yourtextName );
1767 $handle = popen( $cmd,
'r' );
1768 $simplisticMergeAttempt =
'';
1770 $data = fread( $handle, 8192 );
1771 if ( strlen( $data ) == 0 ) {
1774 $simplisticMergeAttempt .= $data;
1777 unlink( $mytextName );
1778 unlink( $oldtextName );
1779 unlink( $yourtextName );
1781 if ( $simplisticMergeAttempt ===
'' && $old !==
'' && !$conflict ) {
1782 wfDebug(
"Unexpected null result from diff3. Command: $cmd" );
1801 if ( $suffix ==
'' ) {
1804 $encSuffix =
'(?:' . preg_quote( $suffix,
'#' ) .
')?';
1808 if ( preg_match(
"#([^/\\\\]*?){$encSuffix}[/\\\\]*$#",
$path,
$matches ) ) {
1826 $path = str_replace(
'/', DIRECTORY_SEPARATOR,
$path );
1827 $from = str_replace(
'/', DIRECTORY_SEPARATOR, $from );
1831 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1833 $pieces = explode( DIRECTORY_SEPARATOR, dirname(
$path ) );
1834 $against = explode( DIRECTORY_SEPARATOR, $from );
1836 if ( $pieces[0] !== $against[0] ) {
1843 while ( count( $pieces ) && count( $against )
1844 && $pieces[0] == $against[0] ) {
1845 array_shift( $pieces );
1846 array_shift( $against );
1850 while ( count( $against ) ) {
1851 array_unshift( $pieces,
'..' );
1852 array_shift( $against );
1857 return implode( DIRECTORY_SEPARATOR, $pieces );
1891function wfGetDB( $db, $groups = [], $wiki =
false ) {
1892 if ( $wiki ===
false ) {
1893 return MediaWikiServices::getInstance()
1894 ->getDBLoadBalancer()
1895 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1897 return MediaWikiServices::getInstance()
1898 ->getDBLoadBalancerFactory()
1899 ->getMainLB( $wiki )
1900 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1914 if ( $script ===
'index' ) {
1916 } elseif ( $script ===
'load' ) {
1919 return "{$wgScriptPath}/{$script}.php";
1931 return $value ?
'true' :
'false';
1954 $name = preg_replace(
1955 "/[^" . Title::legalChars() .
"]" . $illegalFileChars .
"/",
1973 if ( $oldLimit != -1 ) {
1975 if ( $newLimit == -1 ) {
1976 wfDebug(
"Removing PHP's memory limit" );
1977 AtEase::suppressWarnings();
1979 ini_set(
'memory_limit', $newLimit );
1980 AtEase::restoreWarnings();
1981 } elseif ( $newLimit > $oldLimit ) {
1982 wfDebug(
"Raising PHP's memory limit to $newLimit bytes" );
1983 AtEase::suppressWarnings();
1985 ini_set(
'memory_limit', $newLimit );
1986 AtEase::restoreWarnings();
2000 $timeout = RequestTimeout::singleton();
2001 $timeLimit = $timeout->getWallTimeLimit();
2002 if ( $timeLimit !== INF ) {
2009 $timeLimit = (int)ini_get(
'max_execution_time' );
2015 ignore_user_abort(
true );
2028 $string = trim( $string ??
'' );
2029 if ( $string ===
'' ) {
2032 $last = $string[strlen( $string ) - 1];
2033 $val = intval( $string );
2066 if ( $length !==
false ) {
2067 $realLen = strlen( $data );
2068 if ( $realLen < $length ) {
2069 throw new MWException(
"Tried to use wfUnpack on a "
2070 .
"string of length $realLen, but needed one "
2071 .
"of at least length $length."
2076 AtEase::suppressWarnings();
2077 $result = unpack( $format, $data );
2078 AtEase::restoreWarnings();
2080 if ( $result ===
false ) {
2082 throw new MWException(
"unpack could not unpack binary data" );
2096 return in_array( $str, ExpiryDef::INFINITY_VALS );
2116 $multipliers = [ 1 ];
2120 $multipliers[] = 1.5;
2124 $handler =
$file->getHandler();
2125 if ( !$handler || !isset( $params[
'width'] ) ) {
2130 if ( isset( $params[
'page'] ) ) {
2131 $basicParams[
'page'] = $params[
'page'];
2137 foreach ( $multipliers as $multiplier ) {
2138 $thumbLimits = array_merge( $thumbLimits, array_map(
2139 static function ( $width ) use ( $multiplier ) {
2140 return round( $width * $multiplier );
2143 $imageLimits = array_merge( $imageLimits, array_map(
2144 static function ( $pair ) use ( $multiplier ) {
2146 round( $pair[0] * $multiplier ),
2147 round( $pair[1] * $multiplier ),
2154 if ( in_array( $params[
'width'], $thumbLimits ) ) {
2155 $normalParams = $basicParams + [
'width' => $params[
'width'] ];
2157 $handler->normaliseParams(
$file, $normalParams );
2161 foreach ( $imageLimits as $pair ) {
2162 $normalParams = $basicParams + [
'width' => $pair[0],
'height' => $pair[1] ];
2165 $handler->normaliseParams(
$file, $normalParams );
2167 if ( $normalParams[
'width'] == $params[
'width'] ) {
2178 foreach ( $params as $key => $value ) {
2179 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2201 foreach ( $baseArray as $name => &$groupVal ) {
2202 if ( isset( $newValues[$name] ) ) {
2203 $groupVal += $newValues[$name];
2207 $baseArray += $newValues;
wfIsWindows()
Check if the operating system is Windows.
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()
wfMerge(string $old, string $mine, string $yours, ?string &$simplisticMergeAttempt, string &$mergeLeftovers=null)
wfMerge attempts to merge differences between three texts.
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
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).
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...
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.
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)
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.
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...
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.
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:
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...
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.
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.
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...
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
$wgLanguageCode
Config variable stub for the LanguageCode setting, for use by phpdoc and IDEs.
$wgScript
Config variable stub for the Script setting, for use by phpdoc and IDEs.
$wgInternalServer
Config variable stub for the InternalServer setting, for use by phpdoc and IDEs.
$wgThumbLimits
Config variable stub for the ThumbLimits setting, for use by phpdoc and IDEs.
$wgDebugLogPrefix
Config variable stub for the DebugLogPrefix setting, for use by phpdoc and IDEs.
$wgPhpCli
Config variable stub for the PhpCli setting, for use by phpdoc and IDEs.
$wgOverrideHostname
Config variable stub for the OverrideHostname setting, for use by phpdoc and IDEs.
$wgImageLimits
Config variable stub for the ImageLimits setting, for use by phpdoc and IDEs.
$wgShowHostnames
Config variable stub for the ShowHostnames setting, for use by phpdoc and IDEs.
$wgTmpDirectory
Config variable stub for the TmpDirectory setting, for use by phpdoc and IDEs.
$wgStyleDirectory
Config variable stub for the StyleDirectory setting, for use by phpdoc and IDEs.
$wgTransactionalTimeLimit
Config variable stub for the TransactionalTimeLimit setting, for use by phpdoc and IDEs.
$wgIllegalFileChars
Config variable stub for the IllegalFileChars setting, for use by phpdoc and IDEs.
$wgDirectoryMode
Config variable stub for the DirectoryMode setting, for use by phpdoc and IDEs.
$wgDiff3
Config variable stub for the Diff3 setting, for use by phpdoc and IDEs.
$wgUrlProtocols
Config variable stub for the UrlProtocols setting, for use by phpdoc and IDEs.
$wgResponsiveImages
Config variable stub for the ResponsiveImages setting, for use by phpdoc and IDEs.
$wgDebugRawPage
Config variable stub for the DebugRawPage setting, for use by phpdoc and IDEs.
$wgEnableMagicLinks
Config variable stub for the EnableMagicLinks setting, for use by phpdoc and IDEs.
$wgScriptPath
Config variable stub for the ScriptPath setting, for use by phpdoc and IDEs.
$wgExtensionDirectory
Config variable stub for the ExtensionDirectory setting, for use by phpdoc and IDEs.
$wgLoadScript
Config variable stub for the LoadScript setting, for use by phpdoc and IDEs.
$wgCanonicalServer
Config variable stub for the CanonicalServer setting, for use by phpdoc and IDEs.
$wgServer
Config variable stub for the Server setting, for use by phpdoc and IDEs.
$wgHttpsPort
Config variable stub for the HttpsPort setting, for use by phpdoc and IDEs.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!is_readable( $file)) $ext