23 if ( !defined(
'MEDIAWIKI' ) ) {
24 die(
"This file is part of MediaWiki, it is not a valid entry point" );
33 use Wikimedia\AtEase\AtEase;
35 use Wikimedia\RequestTimeout\RequestTimeout;
36 use Wikimedia\WrappedString;
51 $path =
"$wgExtensionDirectory/$ext/extension.json";
72 foreach ( $exts as
$ext ) {
73 $registry->queue(
"$wgExtensionDirectory/$ext/extension.json" );
88 $path =
"$wgStyleDirectory/$skin/skin.json";
103 foreach ( $skins as $skin ) {
104 $registry->queue(
"$wgStyleDirectory/$skin/skin.json" );
119 $comparator =
static function ( $a, $b ):
int {
120 if ( is_string( $a ) && is_string( $b ) ) {
121 return strcmp( $a, $b );
123 if ( !is_array( $a ) && !is_array( $b ) ) {
124 throw new InvalidArgumentException(
125 'This function assumes that array elements are all strings or all arrays'
128 if ( count( $a ) !== count( $b ) ) {
129 return count( $a ) <=> count( $b );
133 while ( key( $a ) !==
null && key( $b ) !==
null ) {
134 $valueA = current( $a );
135 $valueB = current( $b );
136 $cmp = strcmp( $valueA, $valueB );
146 return array_udiff( $arr1, $arr2, $comparator );
170 foreach (
$args as $errors ) {
171 foreach ( $errors as $params ) {
172 $originalParams = $params;
175 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
177 # @todo FIXME: Sometimes get nested arrays for $params,
178 # which leads to E_NOTICEs
179 $spec = implode(
"\t", $params );
180 $out[$spec] = $originalParams;
183 return array_values( $out );
197 $keys = array_keys( $array );
198 $offsetByKey = array_flip(
$keys );
200 if ( !\array_key_exists( $after, $offsetByKey ) ) {
203 $offset = $offsetByKey[$after];
206 $before = array_slice( $array, 0, $offset + 1,
true );
207 $after = array_slice( $array, $offset + 1, count( $array ) - $offset,
true );
209 $output = $before + $insert + $after;
224 if ( is_object( $objOrArray ) ) {
225 $objOrArray = get_object_vars( $objOrArray );
227 foreach ( $objOrArray as $key => $value ) {
228 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
232 $array[$key] = $value;
251 $max = mt_getrandmax() + 1;
252 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12,
'.',
'' );
268 for ( $n = 0; $n < $length; $n += 7 ) {
269 $str .= sprintf(
'%07x', mt_rand() & 0xfffffff );
271 return substr( $str, 0, $length );
310 if ( $needle ===
null ) {
311 $needle = [
'%3B',
'%40',
'%24',
'%21',
'%2A',
'%28',
'%29',
'%2C',
'%2F',
'%7E' ];
312 if ( !isset( $_SERVER[
'SERVER_SOFTWARE'] ) ||
313 ( strpos( $_SERVER[
'SERVER_SOFTWARE'],
'Microsoft-IIS/7' ) ===
false )
319 $s = urlencode(
$s );
322 [
';',
'@',
'$',
'!',
'*',
'(',
')',
',',
'/',
'~',
':' ],
340 if ( $array2 !==
null ) {
345 foreach ( $array1 as $key => $value ) {
346 if ( $value !==
null && $value !==
false ) {
350 if ( $prefix !==
'' ) {
351 $key = $prefix .
"[$key]";
353 if ( is_array( $value ) ) {
355 foreach ( $value as $k => $v ) {
356 $cgi .= $firstTime ?
'' :
'&';
357 if ( is_array( $v ) ) {
360 $cgi .= urlencode( $key .
"[$k]" ) .
'=' . urlencode( $v );
365 if ( is_object( $value ) ) {
366 $value = $value->__toString();
368 $cgi .= urlencode( $key ) .
'=' . urlencode( $value );
385 if ( isset( $query[0] ) && $query[0] ==
'?' ) {
386 $query = substr( $query, 1 );
388 $bits = explode(
'&', $query );
390 foreach ( $bits as $bit ) {
394 if ( strpos( $bit,
'=' ) ===
false ) {
399 list( $key, $value ) = explode(
'=', $bit );
401 $key = urldecode( $key );
402 $value = urldecode( $value );
403 if ( strpos( $key,
'[' ) !==
false ) {
404 $keys = array_reverse( explode(
'[', $key ) );
405 $key = array_pop(
$keys );
407 foreach (
$keys as $k ) {
408 $k = substr( $k, 0, -1 );
409 $temp = [ $k => $temp ];
411 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
412 $ret[$key] = array_merge( $ret[$key], $temp );
432 if ( is_array( $query ) ) {
435 if ( $query !=
'' ) {
438 $hashPos = strpos( $url,
'#' );
439 if ( $hashPos !==
false ) {
440 $fragment = substr( $url, $hashPos );
441 $url = substr( $url, 0, $hashPos );
445 if ( strpos( $url,
'?' ) ===
false ) {
453 if ( $fragment !==
false ) {
469 if ( MediaWikiServices::hasInstance() ) {
470 $services = MediaWikiServices::getInstance();
471 if ( $services->hasService(
'UrlUtils' ) ) {
472 return $services->getUrlUtils();
512 return wfGetUrlUtils()->expand( (
string)$url, $defaultProto ) ??
false;
556 return wfGetUrlUtils()->removeDotSegments( (
string)$urlPath );
568 $method = $includeProtocolRelative ?
'validProtocols' :
'validAbsoluteProtocols';
635 return wfGetUrlUtils()->matchesDomainList( (
string)$url, (array)$domains );
658 function wfDebug( $text, $dest =
'all', array $context = [] ) {
665 $text = trim( $text );
670 $context[
'private'] = ( $dest ===
false || $dest ===
'private' );
672 $logger = LoggerFactory::getInstance(
'wfDebug' );
673 $logger->debug( $text, $context );
687 if ( ( isset( $_GET[
'action'] ) && $_GET[
'action'] ==
'raw' )
723 $logGroup, $text, $dest =
'all', array $context = []
725 $text = trim( $text );
727 $logger = LoggerFactory::getInstance( $logGroup );
728 $context[
'private'] = ( $dest ===
false || $dest ===
'private' );
729 $logger->info( $text, $context );
741 $logger = LoggerFactory::getInstance(
'wfLogDBError' );
742 $logger->error( trim( $text ), $context );
761 function wfDeprecated( $function, $version =
false, $component =
false, $callerOffset = 2 ) {
762 if ( !is_string( $version ) && $version !==
false ) {
763 throw new InvalidArgumentException(
764 "MediaWiki version must either be a string or false. " .
765 "Example valid version: '1.33'"
792 function wfDeprecatedMsg( $msg, $version =
false, $component =
false, $callerOffset = 2 ) {
794 $callerOffset ===
false ?
false : $callerOffset + 1 );
807 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
820 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
830 $profiler->logData();
834 MediaWikiServices::getInstance()->getStatsdDataFactory(),
835 MediaWikiServices::getInstance()->getMainConfig()
847 return MediaWikiServices::getInstance()->getReadOnlyMode()
862 return MediaWikiServices::getInstance()->getReadOnlyMode()
882 # Identify which language to get or create a language object for.
883 # Using is_object here due to Stub objects.
884 if ( is_object( $langcode ) ) {
885 # Great, we already have the object (hopefully)!
890 $services = MediaWikiServices::getInstance();
892 # $langcode is the language code of the wikis content language object.
893 # or it is a boolean and value is true
894 return $services->getContentLanguage();
898 if ( $langcode ===
false || $langcode ===
$wgLang->getCode() ) {
899 # $langcode is the language code of user language object.
900 # or it was a boolean and value is false
904 $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
905 if ( in_array( $langcode, $validCodes ) ) {
906 # $langcode corresponds to a valid language.
907 return $services->getLanguageFactory()->getLanguage( $langcode );
910 # $langcode is a string, but not a valid language code; use content language.
911 wfDebug(
"Invalid language code passed to wfGetLangObj, falling back to content language." );
912 return $services->getContentLanguage();
937 if ( is_array( $key ) ) {
946 $message->params( ...$params );
977 # Fix windows line-endings
978 # Some messages are split with explode("\n", $msg)
979 $message = str_replace(
"\r",
'', $message );
983 if ( is_array(
$args[0] ) ) {
986 $replacementKeys = [];
987 foreach (
$args as $n => $param ) {
988 $replacementKeys[
'$' . ( $n + 1 )] = $param;
990 $message = strtr( $message, $replacementKeys );
1011 return php_uname(
'n' ) ?:
'unknown';
1027 $elapsed = ( microtime(
true ) - $_SERVER[
'REQUEST_TIME_FLOAT'] );
1029 $responseTime = round( $elapsed * 1000 );
1030 $reportVars = [
'wgBackendResponseTime' => $responseTime ];
1054 static $disabled =
null;
1056 if ( $disabled ===
null ) {
1057 $disabled = !function_exists(
'debug_backtrace' );
1059 wfDebug(
"debug_backtrace() is disabled" );
1067 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1069 return array_slice( debug_backtrace(), 1 );
1084 if ( $raw ===
null ) {
1089 $frameFormat =
"%s line %s calls %s()\n";
1090 $traceFormat =
"%s";
1092 $frameFormat =
"<li>%s line %s calls %s()</li>\n";
1093 $traceFormat =
"<ul>\n%s</ul>\n";
1096 $frames = array_map(
static function ( $frame ) use ( $frameFormat ) {
1097 $file = !empty( $frame[
'file'] ) ? basename( $frame[
'file'] ) :
'-';
1098 $line = $frame[
'line'] ??
'-';
1099 $call = $frame[
'function'];
1100 if ( !empty( $frame[
'class'] ) ) {
1101 $call = $frame[
'class'] . $frame[
'type'] . $call;
1103 return sprintf( $frameFormat,
$file,
$line, $call );
1106 return sprintf( $traceFormat, implode(
'', $frames ) );
1120 if ( isset( $backtrace[$level] ) ) {
1136 if ( !$limit || $limit > count( $trace ) - 1 ) {
1137 $limit = count( $trace ) - 1;
1139 $trace = array_slice( $trace, -$limit - 1, $limit );
1140 return implode(
'/', array_map(
'wfFormatStackFrame', $trace ) );
1150 if ( !isset( $frame[
'function'] ) ) {
1151 return 'NO_FUNCTION_GIVEN';
1153 return isset( $frame[
'class'] ) && isset( $frame[
'type'] ) ?
1154 $frame[
'class'] . $frame[
'type'] . $frame[
'function'] :
1168 return wfMessage(
'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1181 static $result =
null;
1182 if ( $result ===
null || $force ) {
1184 if ( isset( $_SERVER[
'HTTP_ACCEPT_ENCODING'] ) ) {
1185 # @todo FIXME: We may want to disallow some broken browsers
1188 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1189 $_SERVER[
'HTTP_ACCEPT_ENCODING'],
1193 if ( isset( $m[2] ) && ( $m[1] ==
'q' ) && ( $m[2] == 0 ) ) {
1196 wfDebug(
"wfClientAcceptsGzip: client accepts gzip." );
1216 static $repl =
null, $repl2 =
null;
1217 if ( $repl ===
null || defined(
'MW_PARSER_TEST' ) || defined(
'MW_PHPUNIT_TEST' ) ) {
1221 '"' =>
'"',
'&' =>
'&',
"'" =>
''',
'<' =>
'<',
1222 '=' =>
'=',
'>' =>
'>',
'[' =>
'[',
']' =>
']',
1223 '{' =>
'{',
'|' =>
'|',
'}' =>
'}',
';' =>
';',
1224 "\n#" =>
"\n#",
"\r#" =>
"\r#",
1225 "\n*" =>
"\n*",
"\r*" =>
"\r*",
1226 "\n:" =>
"\n:",
"\r:" =>
"\r:",
1227 "\n " =>
"\n ",
"\r " =>
"\r ",
1228 "\n\n" =>
"\n ",
"\r\n" =>
" \n",
1229 "\n\r" =>
"\n ",
"\r\r" =>
"\r ",
1230 "\n\t" =>
"\n	",
"\r\t" =>
"\r	",
1231 "\n----" =>
"\n----",
"\r----" =>
"\r----",
1232 '__' =>
'__',
'://' =>
'://',
1237 foreach ( $magicLinks as $magic ) {
1238 $repl[
"$magic "] =
"$magic ";
1239 $repl[
"$magic\t"] =
"$magic	";
1240 $repl[
"$magic\r"] =
"$magic ";
1241 $repl[
"$magic\n"] =
"$magic ";
1242 $repl[
"$magic\f"] =
"$magic";
1249 if ( substr( $prot, -1 ) ===
':' ) {
1250 $repl2[] = preg_quote( substr( $prot, 0, -1 ),
'/' );
1253 $repl2 = $repl2 ?
'/\b(' . implode(
'|', $repl2 ) .
'):/i' :
'/^(?!)/';
1255 $text = substr( strtr(
"\n$text", $repl ), 1 );
1257 $text = preg_replace( $repl2,
'$1:', $text );
1273 if (
$source !==
null || $force ) {
1289 $temp = (bool)( $dest & $bit );
1290 if ( $state !==
null ) {
1308 $s = str_replace(
"\n",
"<br />\n", var_export( $var,
true ) .
"\n" );
1309 if ( headers_sent() || !isset(
$wgOut ) || !is_object(
$wgOut ) ) {
1328 $wgOut->sendCacheControl();
1332 header(
'Content-type: text/html; charset=utf-8' );
1334 print
'<!DOCTYPE html>' .
1335 '<html><head><title>' .
1336 htmlspecialchars( $label ) .
1337 '</title></head><body><h1>' .
1338 htmlspecialchars( $label ) .
1340 nl2br( htmlspecialchars( $desc ) ) .
1341 "</p></body></html>\n";
1342 header(
'Content-Length: ' . ob_get_length() );
1364 while ( $status = ob_get_status() ) {
1365 if ( isset( $status[
'flags'] ) ) {
1366 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1367 $deleteable = ( $status[
'flags'] & $flags ) === $flags;
1368 } elseif ( isset( $status[
'del'] ) ) {
1369 $deleteable = $status[
'del'];
1372 $deleteable = $status[
'type'] !== 0;
1374 if ( !$deleteable ) {
1379 if ( $status[
'name'] ===
'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1383 if ( !ob_end_clean() ) {
1388 if ( $resetGzipEncoding && $status[
'name'] ==
'ob_gzhandler' ) {
1391 header_remove(
'Content-Encoding' );
1425 $ret = MWTimestamp::convert( $outputtype, $ts );
1426 if ( $ret ===
false ) {
1427 wfDebug(
"wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1441 if ( $ts ===
null ) {
1454 return MWTimestamp::now( TS_MW );
1463 return PHP_OS_FAMILY ===
'Windows';
1473 return PHP_SAPI ===
'cli' || PHP_SAPI ===
'phpdbg';
1510 throw new MWException( __FUNCTION__ .
" given storage path '$dir'." );
1513 if ( $caller !==
null ) {
1514 wfDebug(
"$caller: called wfMkdirParents($dir)" );
1517 if ( strval( $dir ) ===
'' || is_dir( $dir ) ) {
1521 $dir = str_replace( [
'\\',
'/' ], DIRECTORY_SEPARATOR, $dir );
1523 if ( $mode ===
null ) {
1528 AtEase::suppressWarnings();
1529 $ok = mkdir( $dir, $mode,
true );
1530 AtEase::restoreWarnings();
1534 if ( is_dir( $dir ) ) {
1539 wfLogWarning( sprintf(
"failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1550 wfDebug( __FUNCTION__ .
"( $dir )" );
1552 if ( is_dir( $dir ) ) {
1553 $objects = scandir( $dir );
1554 foreach ( $objects as $object ) {
1555 if ( $object !=
"." && $object !=
".." ) {
1556 if ( filetype( $dir .
'/' . $object ) ==
"dir" ) {
1559 unlink( $dir .
'/' . $object );
1574 function wfPercent( $nr,
int $acc = 2,
bool $round =
true ) {
1575 $accForFormat = $acc >= 0 ? $acc : 0;
1576 $ret = sprintf(
"%.${accForFormat}f", $nr );
1577 return $round ? round( (
float)$ret, $acc ) .
'%' :
"$ret%";
1620 $val = strtolower( $val );
1625 || preg_match(
"/^\s*[+-]?0*[1-9]/", $val );
1642 return Shell::escape( ...
$args );
1670 $limits = [], $options = []
1672 if ( Shell::isDisabled() ) {
1675 return 'Unable to run external programs, proc_open() is disabled.';
1678 if ( is_array( $cmd ) ) {
1679 $cmd = Shell::escape( $cmd );
1682 $includeStderr = isset( $options[
'duplicateStderr'] ) && $options[
'duplicateStderr'];
1683 $profileMethod = $options[
'profileMethod'] ??
wfGetCaller();
1686 $result = Shell::command( [] )
1687 ->unsafeParams( (array)$cmd )
1688 ->environment( $environ )
1690 ->includeStderr( $includeStderr )
1691 ->profileMethod( $profileMethod )
1693 ->restrict( Shell::RESTRICT_NONE )
1700 $retval = $result->getExitCode();
1702 return $result->getStdout();
1723 return wfShellExec( $cmd, $retval, $environ, $limits,
1724 [
'duplicateStderr' =>
true,
'profileMethod' =>
wfGetCaller() ] );
1746 Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
1747 $cmd = [ $options[
'php'] ??
$wgPhpCli ];
1748 if ( isset( $options[
'wrapper'] ) ) {
1749 $cmd[] = $options[
'wrapper'];
1753 return Shell::escape( array_merge( $cmd, $parameters ) );
1767 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult =
null ) {
1770 # This check may also protect against code injection in
1771 # case of broken installations.
1772 AtEase::suppressWarnings();
1774 AtEase::restoreWarnings();
1776 if ( !$haveDiff3 ) {
1781 # Make temporary files
1783 $oldtextFile = fopen( $oldtextName = tempnam( $td,
'merge-old-' ),
'w' );
1784 $mytextFile = fopen( $mytextName = tempnam( $td,
'merge-mine-' ),
'w' );
1785 $yourtextFile = fopen( $yourtextName = tempnam( $td,
'merge-your-' ),
'w' );
1787 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1788 # a newline character. To avoid this, we normalize the trailing whitespace before
1789 # creating the diff.
1791 fwrite( $oldtextFile, rtrim( $old ) .
"\n" );
1792 fclose( $oldtextFile );
1793 fwrite( $mytextFile, rtrim( $mine ) .
"\n" );
1794 fclose( $mytextFile );
1795 fwrite( $yourtextFile, rtrim( $yours ) .
"\n" );
1796 fclose( $yourtextFile );
1798 # Check for a conflict
1799 $cmd = Shell::escape(
$wgDiff3,
'-a',
'--overlap-only', $mytextName,
1800 $oldtextName, $yourtextName );
1801 $handle = popen( $cmd,
'r' );
1803 $mergeAttemptResult =
'';
1805 $data = fread( $handle, 8192 );
1806 if ( strlen( $data ) == 0 ) {
1809 $mergeAttemptResult .= $data;
1813 $conflict = $mergeAttemptResult !==
'';
1816 $cmd = Shell::escape(
$wgDiff3,
'-a',
'-e',
'--merge', $mytextName,
1817 $oldtextName, $yourtextName );
1818 $handle = popen( $cmd,
'r' );
1821 $data = fread( $handle, 8192 );
1822 if ( strlen( $data ) == 0 ) {
1828 unlink( $mytextName );
1829 unlink( $oldtextName );
1830 unlink( $yourtextName );
1832 if ( $result ===
'' && $old !==
'' && !$conflict ) {
1833 wfDebug(
"Unexpected null result from diff3. Command: $cmd" );
1852 if ( $suffix ==
'' ) {
1855 $encSuffix =
'(?:' . preg_quote( $suffix,
'#' ) .
')?';
1859 if ( preg_match(
"#([^/\\\\]*?){$encSuffix}[/\\\\]*$#",
$path,
$matches ) ) {
1877 $path = str_replace(
'/', DIRECTORY_SEPARATOR,
$path );
1878 $from = str_replace(
'/', DIRECTORY_SEPARATOR, $from );
1882 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1884 $pieces = explode( DIRECTORY_SEPARATOR, dirname(
$path ) );
1885 $against = explode( DIRECTORY_SEPARATOR, $from );
1887 if ( $pieces[0] !== $against[0] ) {
1894 while ( count( $pieces ) && count( $against )
1895 && $pieces[0] == $against[0] ) {
1896 array_shift( $pieces );
1897 array_shift( $against );
1901 while ( count( $against ) ) {
1902 array_unshift( $pieces,
'..' );
1903 array_shift( $against );
1908 return implode( DIRECTORY_SEPARATOR, $pieces );
1942 function wfGetDB( $db, $groups = [], $wiki =
false ) {
1943 if ( $wiki ===
false ) {
1944 return MediaWikiServices::getInstance()
1945 ->getDBLoadBalancer()
1946 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1948 return MediaWikiServices::getInstance()
1949 ->getDBLoadBalancerFactory()
1950 ->getMainLB( $wiki )
1951 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1964 return MediaWikiServices::getInstance()->getRepoGroup()->findFile(
$title, $options );
1977 return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile(
$title );
2004 if ( $script ===
'index' ) {
2007 } elseif ( $script ===
'load' ) {
2010 return "{$wgScriptPath}/{$script}.php";
2022 if ( isset( $_SERVER[
'SCRIPT_NAME'] ) ) {
2033 return $_SERVER[
'SCRIPT_NAME'];
2035 return $_SERVER[
'URL'];
2047 return $value ?
'true' :
'false';
2070 $name = preg_replace(
2089 if ( $oldLimit != -1 ) {
2091 if ( $newLimit == -1 ) {
2092 wfDebug(
"Removing PHP's memory limit" );
2093 AtEase::suppressWarnings();
2095 ini_set(
'memory_limit', $newLimit );
2096 AtEase::restoreWarnings();
2097 } elseif ( $newLimit > $oldLimit ) {
2098 wfDebug(
"Raising PHP's memory limit to $newLimit bytes" );
2099 AtEase::suppressWarnings();
2101 ini_set(
'memory_limit', $newLimit );
2102 AtEase::restoreWarnings();
2116 $timeout = RequestTimeout::singleton();
2117 $timeLimit = $timeout->getWallTimeLimit();
2118 if ( $timeLimit !== INF ) {
2125 $timeLimit = (int)ini_get(
'max_execution_time' );
2131 ignore_user_abort(
true );
2144 $string = trim( $string );
2145 if ( $string ===
'' ) {
2148 $last = $string[strlen( $string ) - 1];
2149 $val = intval( $string );
2182 if ( $length !==
false ) {
2183 $realLen = strlen( $data );
2184 if ( $realLen < $length ) {
2185 throw new MWException(
"Tried to use wfUnpack on a "
2186 .
"string of length $realLen, but needed one "
2187 .
"of at least length $length."
2192 AtEase::suppressWarnings();
2193 $result = unpack( $format, $data );
2194 AtEase::restoreWarnings();
2196 if ( $result ===
false ) {
2198 throw new MWException(
"unpack could not unpack binary data" );
2226 return in_array( $str, ExpiryDef::INFINITY_VALS );
2246 $multipliers = [ 1 ];
2250 $multipliers[] = 1.5;
2254 $handler =
$file->getHandler();
2255 if ( !$handler || !isset( $params[
'width'] ) ) {
2260 if ( isset( $params[
'page'] ) ) {
2261 $basicParams[
'page'] = $params[
'page'];
2267 foreach ( $multipliers as $multiplier ) {
2268 $thumbLimits = array_merge( $thumbLimits, array_map(
2269 static function ( $width ) use ( $multiplier ) {
2270 return round( $width * $multiplier );
2273 $imageLimits = array_merge( $imageLimits, array_map(
2274 static function ( $pair ) use ( $multiplier ) {
2276 round( $pair[0] * $multiplier ),
2277 round( $pair[1] * $multiplier ),
2284 if ( in_array( $params[
'width'], $thumbLimits ) ) {
2285 $normalParams = $basicParams + [
'width' => $params[
'width'] ];
2287 $handler->normaliseParams(
$file, $normalParams );
2291 foreach ( $imageLimits as $pair ) {
2292 $normalParams = $basicParams + [
'width' => $pair[0],
'height' => $pair[1] ];
2295 $handler->normaliseParams(
$file, $normalParams );
2297 if ( $normalParams[
'width'] == $params[
'width'] ) {
2308 foreach ( $params as $key => $value ) {
2309 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2331 foreach ( $baseArray as $name => &$groupVal ) {
2332 if ( isset( $newValues[$name] ) ) {
2333 $groupVal += $newValues[$name];
2337 $baseArray += $newValues;
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.
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.
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.
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:
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.
wfShorthandToInteger( $string='', $default=-1)
Converts shorthand byte notation to integer form.
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.
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 runner()
Get a HookRunner instance for calling hooks using the new interfaces.
static header( $code)
Output an HTTP status code header.
static warning( $msg, $callerOffset=1, $level=E_USER_NOTICE, $log='auto')
Adds a warning entry to the log.
static deprecated( $function, $version=false, $component=false, $callerOffset=2)
Show a warning that $function is deprecated.
static deprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
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 instance()
Singleton.
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.
static getUsableTempDirectory()
static legalChars()
Get a regex character class describing the legal characters in a link.
static detectProtocol()
Detect the protocol from $_SERVER.
$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.
$wgMiserMode
Config variable stub for the MiserMode 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.
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