*/ protected static array $singletonInstances = []; /** * Instances returned by `makeInstance`, using the class names as array keys * * @var array> */ protected static array $nonSingletonInstances = []; /** * Cache for `makeInstance` with given class name and final class names to reduce number of * `self::getClassName()` calls * * @var array Given class name => final class name */ protected static array $finalClassNameCache = []; final private function __construct() {} /** * Truncates a string with appended/prepended "..." and takes current character set into consideration. * * @param string $string String to truncate * @param int $chars Must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end. * @param string $appendString Appendix to the truncated string * @return string Cropped string */ public static function fixed_lgd_cs(string $string, int $chars, string $appendString = '...'): string { if ($chars === 0 || mb_strlen($string, 'utf-8') <= abs($chars)) { return $string; } if ($chars > 0) { $string = mb_substr($string, 0, $chars, 'utf-8') . $appendString; } else { $string = $appendString . mb_substr($string, $chars, mb_strlen($string, 'utf-8'), 'utf-8'); } return $string; } /** * Match IP number with list of numbers with wildcard * Dispatcher method for switching into specialised IPv4 and IPv6 methods. * * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR * @param string $list Is a comma-list of IP-addresses to match with. CIDR-notation should be used. For IPv4 addresses only, the *-wildcard is also allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168). If list is "*" no check is done and the function returns TRUE immediately. An empty list always returns FALSE. * @return bool TRUE if an IP-mask from $list matches $baseIP */ public static function cmpIP(string $baseIP, string $list): bool { $list = trim($list); if ($list === '') { return false; } if ($list === '*') { return true; } if (str_contains($baseIP, ':') && self::validIPv6($baseIP)) { return self::cmpIPv6($baseIP, $list); } return self::cmpIPv4($baseIP, $list); } /** * Match IPv4 number with list of numbers with wildcard * * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR * @param string $list Is a comma-list of IP-addresses to match with. CIDR-notation, *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.0.0/16 equals 192.168.*.* equals 192.168), could also contain IPv6 addresses * @return bool TRUE if an IP-mask from $list matches $baseIP */ public static function cmpIPv4(string $baseIP, string $list): bool { $IPpartsReq = explode('.', $baseIP); if (count($IPpartsReq) === 4) { $values = self::trimExplode(',', $list, true); foreach ($values as $test) { $testList = explode('/', $test); if (count($testList) === 2) { [$test, $mask] = $testList; } else { $mask = false; } if ((int)$mask) { $mask = (int)$mask; // "192.168.3.0/24" $lnet = (int)ip2long($test); $lip = (int)ip2long($baseIP); $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT); $firstpart = substr($binnet, 0, $mask); $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT); $firstip = substr($binip, 0, $mask); $yes = $firstpart === $firstip; } else { // "192.168.*.*" $IPparts = explode('.', $test); $yes = 1; foreach ($IPparts as $index => $val) { $val = trim($val); if ($val !== '*' && $IPpartsReq[$index] !== $val) { $yes = 0; } } } if ($yes) { return true; } } } return false; } /** * Match IPv6 address with a list of IPv6 prefixes * * @param string $baseIP Is the current remote IP address for instance * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses. IPv6 addresses * must be specified in CIDR-notation, not with * wildcard, otherwise self::validIPv6() will fail. * @return bool TRUE If a baseIP matches any prefix */ public static function cmpIPv6(string $baseIP, string $list): bool { // Policy default: Deny connection $success = false; $baseIP = self::normalizeIPv6($baseIP); $values = self::trimExplode(',', $list, true); foreach ($values as $test) { $testList = explode('/', $test); if (count($testList) === 2) { [$test, $mask] = $testList; } else { $mask = false; } if (self::validIPv6($test)) { $test = self::normalizeIPv6($test); $maskInt = (int)$mask ?: 128; // Special case; /0 is an allowed mask - equals a wildcard if ($mask === '0') { $success = true; } elseif ($maskInt == 128) { $success = $test === $baseIP; } else { $testBin = (string)inet_pton($test); $baseIPBin = (string)inet_pton($baseIP); $success = true; // Modulo is 0 if this is a 8-bit-boundary $maskIntModulo = $maskInt % 8; $numFullCharactersUntilBoundary = (int)($maskInt / 8); $substring = (string)substr($baseIPBin, 0, $numFullCharactersUntilBoundary); if (!str_starts_with($testBin, $substring)) { $success = false; } elseif ($maskIntModulo > 0) { // If not an 8-bit-boundary, check bits of last character $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT); $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT); if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) { $success = false; } } } } if ($success) { return true; } } return false; } /** * Normalize an IPv6 address to full length * * @param string $address Given IPv6 address * @return string Normalized address */ public static function normalizeIPv6(string $address): string { $normalizedAddress = ''; // According to RFC lowercase-representation is recommended $address = strtolower($address); // Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000) if (strlen($address) === 39) { // Already in full expanded form return $address; } // Count 2 if if address has hidden zero blocks $chunks = explode('::', $address); if (count($chunks) === 2) { $chunksLeft = explode(':', $chunks[0]); $chunksRight = explode(':', $chunks[1]); $left = count($chunksLeft); $right = count($chunksRight); // Special case: leading zero-only blocks count to 1, should be 0 if ($left === 1 && strlen($chunksLeft[0]) === 0) { $left = 0; } $hiddenBlocks = 8 - ($left + $right); $hiddenPart = ''; $h = 0; while ($h < $hiddenBlocks) { $hiddenPart .= '0000:'; $h++; } if ($left === 0) { $stageOneAddress = $hiddenPart . $chunks[1]; } else { $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1]; } } else { $stageOneAddress = $address; } // Normalize the blocks: $blocks = explode(':', $stageOneAddress); $divCounter = 0; foreach ($blocks as $block) { $tmpBlock = ''; $i = 0; $hiddenZeros = 4 - strlen($block); while ($i < $hiddenZeros) { $tmpBlock .= '0'; $i++; } $normalizedAddress .= $tmpBlock . $block; if ($divCounter < 7) { $normalizedAddress .= ':'; $divCounter++; } } return $normalizedAddress; } /** * Validate a given IP address. * * Possible format are IPv4 and IPv6. * * @param string $ip IP address to be tested * @return bool TRUE if $ip is either of IPv4 or IPv6 format. */ public static function validIP(string $ip): bool { return filter_var($ip, FILTER_VALIDATE_IP) !== false; } /** * Validate a given IP address to the IPv4 address format. * * Example for possible format: 10.0.45.99 * * @param string $ip IP address to be tested * @return bool TRUE if $ip is of IPv4 format. */ public static function validIPv4(string $ip): bool { return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; } /** * Validate a given IP address to the IPv6 address format. * * Example for possible format: 43FB::BB3F:A0A0:0 | ::1 * * @param string $ip IP address to be tested * @return bool TRUE if $ip is of IPv6 format. */ public static function validIPv6(string $ip): bool { return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; } /** * Match fully qualified domain name with list of strings with wildcard * * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR) * @param string $list A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong) * @return bool TRUE if a domain name mask from $list matches $baseIP */ public static function cmpFQDN(string $baseHost, string $list): bool { $baseHost = trim($baseHost); if (empty($baseHost)) { return false; } if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) { // Resolve hostname // Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR) $baseHostName = (string)gethostbyaddr($baseHost); if ($baseHostName === $baseHost) { // Unable to resolve hostname return false; } } else { $baseHostName = $baseHost; } $baseHostNameParts = explode('.', $baseHostName); $values = self::trimExplode(',', $list, true); foreach ($values as $test) { $hostNameParts = explode('.', $test); // To match hostNameParts can only be shorter (in case of wildcards) or equal $hostNamePartsCount = count($hostNameParts); $baseHostNamePartsCount = count($baseHostNameParts); if ($hostNamePartsCount > $baseHostNamePartsCount) { continue; } $yes = true; foreach ($hostNameParts as $index => $val) { $val = trim($val); if ($val === '*') { // Wildcard valid for one or more hostname-parts $wildcardStart = $index + 1; // Wildcard as last/only part always matches, otherwise perform recursive checks if ($wildcardStart < $hostNamePartsCount) { $wildcardMatched = false; $tempHostName = implode('.', array_slice($hostNameParts, $index + 1)); while ($wildcardStart < $baseHostNamePartsCount && !$wildcardMatched) { $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart)); $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName); $wildcardStart++; } if ($wildcardMatched) { // Match found by recursive compare return true; } $yes = false; } } elseif ($baseHostNameParts[$index] !== $val) { // In case of no match $yes = false; } } if ($yes) { return true; } } return false; } /** * Checks if a given URL matches the host that currently handles this HTTP request. * Scheme, hostname and (optional) port of the given URL are compared. * * @param string $url URL to compare with the TYPO3 request host * @param ServerRequestInterface $request PSR-7 request including normalizedParams attribute * @return bool Whether the URL matches the TYPO3 request host */ public static function isOnCurrentHost(string $url, ServerRequestInterface $request): bool { $normalizedParams = $request->getAttribute('normalizedParams'); if ($normalizedParams === null) { throw new \RuntimeException('GeneralUtility::isOnCurrentHost() requires the request to have a normalizedParams attribute.', 1775679512); } return stripos($url . '/', $normalizedParams->getRequestHost() . '/') === 0; } /** * Check for item in list * Check if an item exists in a comma-separated list of items. * * @param string $list Comma-separated list of items (string) * @param string $item Item to check for * @return bool TRUE if $item is in $list */ public static function inList($list, $item) { return str_contains(',' . $list . ',', ',' . $item . ','); } /** * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7). * Ranges are limited to 1000 values per range. * * @param string $list Comma-separated list of integers with ranges (string) * @return string New comma-separated list of items */ public static function expandList($list): string { $items = explode(',', $list); $list = []; foreach ($items as $item) { $range = explode('-', $item); if (isset($range[1])) { $runAwayBrake = 1000; for ($n = $range[0]; $n <= $range[1]; $n++) { $list[] = $n; $runAwayBrake--; if ($runAwayBrake <= 0) { break; } } } else { $list[] = $item; } } return implode(',', $list); } /** * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input * * @param string $str String to md5-hash * @return int Returns 28bit integer-hash */ public static function md5int($str) { return hexdec(substr(md5($str), 0, 7)); } /** * Splits a reference to a file in 5 parts * * @param string $fileNameWithPath File name with path to be analyzed (must exist if open_basedir is set) * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext] */ public static function split_fileref(string $fileNameWithPath): array { $info = []; $reg = []; if (preg_match('/(.*\\/)(.*)$/', $fileNameWithPath, $reg)) { $info['path'] = $reg[1]; $info['file'] = $reg[2]; } else { $info['path'] = ''; $info['file'] = $fileNameWithPath; } $reg = ''; // If open_basedir is set and the fileName was supplied without a path the is_dir check fails if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], $reg)) { $info['filebody'] = $reg[1]; $info['fileext'] = strtolower($reg[2]); $info['realFileext'] = $reg[2]; } else { $info['filebody'] = $info['file']; $info['fileext'] = ''; } return $info; } /** * Returns the directory part of a path without trailing slash * If there is no dir-part, then an empty string is returned. * Behaviour: * * '/dir1/dir2/script.php' => '/dir1/dir2' * '/dir1/' => '/dir1' * 'dir1/script.php' => 'dir1' * 'd/script.php' => 'd' * '/script.php' => '' * '' => '' * * @param string $path Directory name / path * @return string Processed input value. See function description. */ public static function dirname($path) { $p = self::revExplode('/', $path, 2); return count($p) === 2 ? $p[0] : ''; } /** * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M) * * @param int $sizeInBytes Number of bytes to format. * @param string $labels Binary unit name "iec", decimal unit name "si" or labels for bytes, kilo, mega, giga, and so on separated by vertical bar (|) and possibly encapsulated in "". Eg: " | K| M| G". Defaults to "iec". * @param int $base The unit base if not using a unit name. Defaults to 1024. * @return string Formatted representation of the byte number, for output. */ public static function formatSize($sizeInBytes, $labels = '', $base = 0, ?int $decimals = null) { $defaultFormats = [ 'iec' => ['base' => 1024, 'labels' => [' ', ' Ki', ' Mi', ' Gi', ' Ti', ' Pi', ' Ei', ' Zi', ' Yi']], 'si' => ['base' => 1000, 'labels' => [' ', ' k', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']], ]; // Set labels and base: if (empty($labels)) { $labels = 'iec'; } if (isset($defaultFormats[$labels])) { $base = $defaultFormats[$labels]['base']; $labelArr = $defaultFormats[$labels]['labels']; } else { $base = (int)$base; if ($base !== 1000 && $base !== 1024) { $base = 1024; } $labelArr = explode('|', str_replace('"', '', $labels)); } // This is set via Site Handling and in the Locales class via setlocale() // LC_NUMERIC is not set because of side effects when calculating with floats // see @\TYPO3\CMS\Core\Localization\Locales::setLocale $currentLocale = setlocale(LC_MONETARY, '0'); $oldLocale = setlocale(LC_NUMERIC, '0'); setlocale(LC_NUMERIC, $currentLocale); $localeInfo = localeconv(); setlocale(LC_NUMERIC, $oldLocale); $sizeInBytes = max($sizeInBytes, 0); $multiplier = floor(($sizeInBytes ? log($sizeInBytes) : 0) / log($base)); $sizeInUnits = $sizeInBytes / $base ** $multiplier; if ($sizeInUnits > ($base * .9)) { $multiplier++; } $multiplier = min($multiplier, count($labelArr) - 1); $sizeInUnits = $sizeInBytes / $base ** $multiplier; $decimals ??= (($multiplier > 0) && ($sizeInUnits < 20)) ? 2 : 0; return number_format($sizeInUnits, $decimals, $localeInfo['decimal_point'], '') . $labelArr[$multiplier]; } /** * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in * * @param string $string Input string, eg "123 + 456 / 789 - 4 * @param string $operators Operators to split by, typically "/+-* * @return array> Array with operators and operands separated. * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc() * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset() */ public static function splitCalc($string, $operators) { $res = []; $sign = '+'; while ($string) { $valueLen = strcspn($string, $operators); $value = substr($string, 0, $valueLen); $res[] = [$sign, trim($value)]; $sign = substr($string, $valueLen, 1); $string = substr($string, $valueLen + 1); } reset($res); return $res; } /** * Checking syntax of input email address * * @param string $email Input string to evaluate * @return bool Returns TRUE if the $email address (input string) is valid */ public static function validEmail(string $email): bool { if (trim($email) !== $email) { return false; } if (!str_contains($email, '@')) { return false; } $validators = []; foreach ($GLOBALS['TYPO3_CONF_VARS']['MAIL']['validators'] ?? [RFCValidation::class] as $className) { $validator = new $className(); if ($validator instanceof EmailValidation) { $validators[] = $validator; } } $emailValidator = new EmailValidator(); $isValid = $emailValidator->isValid($email, new MultipleValidationWithAnd($validators, MultipleValidationWithAnd::STOP_ON_ERROR)); // Currently, the RFCValidation doesn't recognise "email @example.com" // as an invalid email for historic reasons - catch it here // see https://github.com/egulias/EmailValidator/issues/374 if ($isValid) { // If email is valid, check if we have CFWSNearAt warning and // treat it as an invalid email, i.e "email @example.com" foreach ($emailValidator->getWarnings() as $warning) { if ($warning instanceof CFWSNearAt) { return false; } } } return $isValid; } /** * Returns a given string with underscores as UpperCamelCase. * Example: Converts blog_example to BlogExample * * @param string $string String to be converted to camel case * @return string UpperCamelCasedWord */ public static function underscoredToUpperCamelCase($string) { return str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string)))); } /** * Returns a given string with underscores as lowerCamelCase. * Example: Converts minimal_value to minimalValue * * @param string $string String to be converted to camel case * @return string lowerCamelCasedWord */ public static function underscoredToLowerCamelCase($string) { return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string))))); } /** * Returns a given CamelCasedString as a lowercase string with underscores. * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value * * @param string $string String to be converted to lowercase underscore * @return string lowercase_and_underscored_string */ public static function camelCaseToLowerCaseUnderscored($string) { $value = preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string) ?? ''; return mb_strtolower($value, 'utf-8'); } /** * Checks if a given string is a Uniform Resource Locator (URL). * * On seriously malformed URLs, parse_url may return FALSE and emit an * E_WARNING. * * filter_var() requires a scheme to be present. * * http://www.faqs.org/rfcs/rfc2396.html * Scheme names consist of a sequence of characters beginning with a * lower case letter and followed by any combination of lower case letters, * digits, plus ("+"), period ("."), or hyphen ("-"). For resiliency, * programs interpreting URI should treat upper case letters as equivalent to * lower case in scheme names (e.g., allow "HTTP" as well as "http"). * scheme = alpha *( alpha | digit | "+" | "-" | "." ) * * Convert the domain part to punicode if it does not look like a regular * domain name. Only the domain part because RFC3986 specifies the the rest of * the url may not contain special characters: * https://tools.ietf.org/html/rfc3986#appendix-A * * @param string $url The URL to be validated * @return bool Whether the given URL is valid */ public static function isValidUrl(string $url): bool { $parsedUrl = parse_url($url); if (!$parsedUrl || !isset($parsedUrl['scheme'])) { return false; } // HttpUtility::buildUrl() will always build urls with :// // our original $url might only contain : (e.g. mail:) // so we convert that to the double-slashed version to ensure // our check against the $recomposedUrl is proper if (!str_starts_with($url, $parsedUrl['scheme'] . '://')) { $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url); } $recomposedUrl = HttpUtility::buildUrl($parsedUrl); if ($recomposedUrl !== $url) { // The parse_url() had to modify characters, so the URL is invalid return false; } if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) { $host = idn_to_ascii($parsedUrl['host']); if ($host === false) { return false; } $parsedUrl['host'] = $host; } return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== false; } /************************* * * ARRAY FUNCTIONS * *************************/ /** * Explodes a $string delimited by $delimiter and casts each item in the array to (int). * Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values. * * @param string $delimiter Delimiter string to explode with * @param string $string The string to explode * @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output * @return list Exploded values, all converted to integers */ public static function intExplode(string $delimiter, string $string, bool $removeEmptyValues = false): array { $result = explode($delimiter, $string); foreach ($result as $key => &$value) { if ($removeEmptyValues && trim($value) === '') { unset($result[$key]); } else { $value = (int)$value; } } unset($value); /** @var array $result */ return array_values($result); } /** * Reverse explode which explodes the string counting from behind. * * Note: The delimiter has to given in the reverse order as * it is occurring within the string. * * GeneralUtility::revExplode('[]', '[my][words][here]', 2) * ==> array('[my][words', 'here]') * * @param string $delimiter Delimiter string to explode with * @param string $string The string to explode * @param int $limit Number of array entries * * @return list Exploded values */ public static function revExplode(string $delimiter, string $string, int $limit = 0): array { // 2 is the (currently, as of 2014-02) most-used value for `$limit` in the core, therefore we check it first if ($limit === 2) { $position = strrpos($string, strrev($delimiter)); if ($position !== false) { return [substr($string, 0, $position), substr($string, $position + strlen($delimiter))]; } return [$string]; } if ($limit <= 1) { return [$string]; } $explodedValues = explode($delimiter, strrev($string), $limit); $explodedValues = array_map(strrev(...), $explodedValues); return array_reverse($explodedValues); } /** * Explodes a string and removes whitespace-only values. * * If $removeEmptyValues is set, then all values that contain only whitespace are removed. * * Each item will have leading and trailing whitespace removed. However, if the tail items are * returned as a single array item, their internal whitespace will not be modified. * * @param string $delim Delimiter string to explode with * @param string $string The string to explode * @param bool $removeEmptyValues If set, all empty values will be removed in output * @param int $limit If limit is set and positive, the returned array will contain a maximum of limit elements with * the last element containing the rest of string. If the limit parameter is negative, all components * except the last -limit are returned. * @return list Exploded values * @phpstan-return ($removeEmptyValues is true ? list : list) Exploded values */ public static function trimExplode(string $delim, string $string, bool $removeEmptyValues = false, int $limit = 0): array { $result = explode($delim, $string); if ($removeEmptyValues) { // Remove items that are just whitespace, but leave whitespace intact for the rest. $result = array_values(array_filter($result, static fn(string $item): bool => trim($item) !== '')); } if ($limit === 0) { // Return everything. return array_map(trim(...), $result); } if ($limit < 0) { // Trim and return just the first $limit elements and ignore the rest. return array_map(trim(...), array_slice($result, 0, $limit)); } // Fold the last length - $limit elements into a single trailing item, then trim and return the result. $tail = array_slice($result, $limit - 1); $result = array_slice($result, 0, $limit - 1); if ($tail) { $result[] = implode($delim, $tail); } return array_map(trim(...), $result); } /** * Implodes a multidim-array into GET-parameters (eg. ¶m[key][key2]=value2¶m[key][key3]=value3) * * @param string $name Name prefix for entries. Set to blank if you wish none. * @param array $theArray The (multidimensional) array to implode * @param string $str (keep blank) * @param bool $skipBlank If set, parameters which were blank strings would be removed. * @param bool $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well. * @return string Imploded result, fx. ¶m[key][key2]=value2¶m[key][key3]=value3 * @see explodeUrl2Array() */ public static function implodeArrayForUrl(string $name, array $theArray, string $str = '', bool $skipBlank = false, bool $rawurlencodeParamName = false): string { foreach ($theArray as $Akey => $AVal) { $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey; if (is_array($AVal)) { $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName); } else { $stringValue = (string)$AVal; if (!$skipBlank || $stringValue !== '') { $parameterName = $rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName; $parameterValue = rawurlencode($stringValue); $str .= '&' . $parameterName . '=' . $parameterValue; } } } return $str; } /** * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array. * * Note! If you want to use a multi-dimensional string, consider this plain simple PHP code instead: * * $result = []; * parse_str($queryParametersAsString, $result); * * However, if you do magic with a flat structure (e.g. keeping "ext[mykey]" as flat key in a one-dimensional array) * then this method is for you. * * @param string $string GETvars string * @return array Array of values. All values AND keys are rawurldecoded() as they properly should be. But this means that any implosion of the array again must rawurlencode it! * @see implodeArrayForUrl() */ public static function explodeUrl2Array(string $string): array { $output = []; $p = explode('&', $string); foreach ($p as $v) { if ($v !== '') { $nameAndValue = explode('=', $v, 2); $output[rawurldecode($nameAndValue[0])] = isset($nameAndValue[1]) ? rawurldecode($nameAndValue[1]) : ''; } } return $output; } /** * Removes dots "." from end of a key identifier of TypoScript styled array. * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value')) * * @param array $ts TypoScript configuration array * @return array TypoScript configuration array without dots at the end of all keys */ public static function removeDotsFromTS(array $ts): array { $out = []; foreach ($ts as $key => $value) { if (is_array($value)) { $key = rtrim($key, '.'); $out[$key] = self::removeDotsFromTS($value); } else { $out[$key] = $value; } } return $out; } /************************* * * HTML/XML PROCESSING * *************************/ /** * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z * $tag is either a whole tag (eg '') or the parameter list (ex ' OPTION ATTRIB=VALUE>') * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset() * * @param string $tag HTML-tag string (or attributes only) * @param bool $decodeEntities Whether to decode HTML entities * @return array Array with the attribute values. */ public static function get_tag_attributes(string $tag, bool $decodeEntities = false): array { $components = self::split_tag_attributes($tag); // Attribute name is stored here $name = ''; $valuemode = false; $attributes = []; foreach ($components as $val) { // Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value if ($val !== '=') { if ($valuemode) { if ($name) { $attributes[$name] = $decodeEntities ? htmlspecialchars_decode($val) : $val; $name = ''; } } else { if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val) ?? '')) { $attributes[$key] = ''; $name = $key; } } $valuemode = false; } else { $valuemode = true; } } return $attributes; } /** * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes * Removes tag-name if found * * @param string $tag HTML-tag string (or attributes only) * @return string[] Array with the attribute values. */ public static function split_tag_attributes(string $tag): array { $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)) ?? ''); // Removes any > in the end of the string $tag_tmp = trim(rtrim($tag_tmp, '>')); $value = []; // Compared with empty string instead , 030102 while ($tag_tmp !== '') { $firstChar = $tag_tmp[0]; if ($firstChar === '"' || $firstChar === '\'') { $reg = explode($firstChar, $tag_tmp, 3); $value[] = $reg[1]; $tag_tmp = trim($reg[2] ?? ''); } elseif ($firstChar === '=') { $value[] = '='; // Removes = chars. $tag_tmp = trim(substr($tag_tmp, 1)); } else { // There are '' around the value. We look for the next ' ' or '>' $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2); $value[] = trim($reg[0]); $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . ($reg[1] ?? '')); } } reset($value); return $value; } /** * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes) * * @param array $arr Array with attribute key/value pairs, eg. "bgcolor" => "red", "border" => 0 * @param bool $xhtmlSafe If set the resulting attribute list will have a) all attributes in lowercase (and duplicates weeded out, first entry taking precedence) and b) all values htmlspecialchar()'ed. It is recommended to use this switch! * @param bool $keepBlankAttributes If TRUE, don't check if values are blank. Default is to omit attributes with blank values. * @return string Imploded attributes, eg. 'bgcolor="red" border="0"' */ public static function implodeAttributes(array $arr, bool $xhtmlSafe = false, bool $keepBlankAttributes = false): string { if ($xhtmlSafe) { $newArr = []; foreach ($arr as $attributeName => $attributeValue) { $attributeName = strtolower((string)$attributeName); if (!isset($newArr[$attributeName])) { $newArr[$attributeName] = htmlspecialchars((string)$attributeValue); } } $arr = $newArr; } $list = []; foreach ($arr as $attributeName => $attributeValue) { if ((string)$attributeValue !== '' || $keepBlankAttributes) { $list[] = $attributeName . '="' . $attributeValue . '"'; } } return implode(' ', $list); } /** * Render a textarea, taking into account whether a leading linefeed needs to be added * * The HTML ` * @internal */ public static function renderTextarea(string $value, array $attributes = []): string { return sprintf( '%s%s', $attributes === [] ? '' : ' ', GeneralUtility::implodeAttributes($attributes, true), $value !== '' ? LF : '', htmlspecialchars($value), ); } /** * Wraps JavaScript code XHTML ready with '; } return ''; } /** * Parses XML input into a PHP array with associative keys * * @param string $string XML data input * @param int $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML. * @param array $parserOptions Options that will be passed to PHP's xml_parser_set_option() * @return array|string The array with the parsed structure unless the XML parser returns with an error in which case the error message string is returned. */ public static function xml2tree(string $string, int $depth = 999, array $parserOptions = []): array|string { $parser = xml_parser_create(); $vals = []; xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0); foreach ($parserOptions as $option => $value) { xml_parser_set_option($parser, $option, $value); } xml_parse_into_struct($parser, $string, $vals); if (xml_get_error_code($parser)) { return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser)); } $stack = [[]]; $stacktop = 0; $startPoint = 0; $tagi = []; foreach ($vals as $key => $val) { $type = $val['type']; // open tag: if ($type === 'open' || $type === 'complete') { $stack[$stacktop++] = $tagi; if ($depth == $stacktop) { $startPoint = $key; } $tagi = ['tag' => $val['tag']]; if (isset($val['attributes'])) { $tagi['attrs'] = $val['attributes']; } if (isset($val['value'])) { $tagi['values'][] = $val['value']; } } // finish tag: if ($type === 'complete' || $type === 'close') { $oldtagi = $tagi; $tagi = $stack[--$stacktop]; $oldtag = $oldtagi['tag']; unset($oldtagi['tag']); if ($depth == $stacktop + 1) { if ($key - $startPoint > 0) { $partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1); $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray); } else { $oldtagi['XMLvalue'] = $oldtagi['values'][0]; } } $tagi['ch'][$oldtag][] = $oldtagi; unset($oldtagi); } // cdata if ($type === 'cdata') { $tagi['values'][] = $val['value']; } } return $tagi['ch']; } /** * Converts a PHP array into an XML string. * The XML output is optimized for readability since associative keys are used as tag names. * This also means that only alphanumeric characters are allowed in the tag names AND only keys NOT starting with numbers (so watch your usage of keys!). However there are options you can set to avoid this problem. * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats) * The function handles input values from the PHP array in a binary-safe way; All characters below 32 (except 9,10,13) will trigger the content to be converted to a base64-string * The PHP variable type of the data IS preserved as long as the types are strings, arrays, integers and booleans. Strings are the default type unless the "type" attribute is set. * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances with 4.x versions. However, with PHP5 there seems to be the need to add an XML prologue a la - otherwise UTF-8 is assumed! Unfortunately, many times the output from this function is used without adding that prologue meaning that non-ASCII characters will break the parsing!! This sucks of course! Effectively it means that the prologue should always be prepended setting the right characterset, alternatively the system should always run as utf-8! * However using MSIE to read the XML output didn't always go well: One reason could be that the character encoding is not observed in the PHP data. The other reason may be if the tag-names are invalid in the eyes of MSIE. Also using the namespace feature will make MSIE break parsing. There might be more reasons... * * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though. * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:" * @param int $level Current recursion level. Don't change, stay at zero! * @param string $docTag Alternative document tag. Default is "phparray". * @param int $spaceInd If greater than zero, then the number of spaces corresponding to this number is used for indenting, if less than zero - no indentation, if zero - a single TAB is used * @param array $options Options for the compilation. Key "useNindex" => 0/1 (boolean: whether to use "n0, n1, n2" for num. indexes); Key "useIndexTagForNum" => "[tag for numerical indexes]"; Key "useIndexTagForAssoc" => "[tag for associative indexes"; Key "parentTagMap" => array('parentTag' => 'thisLevelTag') * @param array $stackData Stack data. Don't touch. * @return string An XML string made from the input content in the array. * @see xml2array() */ public static function array2xml(array $array, string $NSprefix = '', int $level = 0, string $docTag = 'phparray', int $spaceInd = 0, array $options = [], array $stackData = []): string { // The list of byte values which will trigger binary-safe storage. If any value has one of these char values in it, it will be encoded in base64 $binaryChars = "\0" . chr(1) . chr(2) . chr(3) . chr(4) . chr(5) . chr(6) . chr(7) . chr(8) . chr(11) . chr(12) . chr(14) . chr(15) . chr(16) . chr(17) . chr(18) . chr(19) . chr(20) . chr(21) . chr(22) . chr(23) . chr(24) . chr(25) . chr(26) . chr(27) . chr(28) . chr(29) . chr(30) . chr(31); // Set indenting mode: $indentChar = $spaceInd ? ' ' : "\t"; $indentN = $spaceInd > 0 ? $spaceInd : 1; $nl = $spaceInd >= 0 ? LF : ''; // Init output variable: $output = ''; // Traverse the input array foreach ($array as $k => $v) { $attr = ''; $tagName = (string)$k; // Construct the tag name. // Use tag based on grand-parent + parent tag name if (isset($stackData['grandParentTagName'], $stackData['parentTagName'], $options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) { $attr .= ' index="' . htmlspecialchars($tagName) . '"'; $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']]; } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && MathUtility::canBeInterpretedAsInteger($tagName)) { // Use tag based on parent tag name + if current tag is numeric $attr .= ' index="' . htmlspecialchars($tagName) . '"'; $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']; } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) { // Use tag based on parent tag name + current tag $attr .= ' index="' . htmlspecialchars($tagName) . '"'; $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName]; } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name: $attr .= ' index="' . htmlspecialchars($tagName) . '"'; $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']]; } elseif (MathUtility::canBeInterpretedAsInteger($tagName)) { // If integer...; if ($options['useNindex'] ?? false) { // If numeric key, prefix "n" $tagName = 'n' . $tagName; } else { // Use special tag for num. keys: $attr .= ' index="' . $tagName . '"'; $tagName = ($options['useIndexTagForNum'] ?? false) ?: 'numIndex'; } } elseif (!empty($options['useIndexTagForAssoc'])) { // Use tag for all associative keys: $attr .= ' index="' . htmlspecialchars($tagName) . '"'; $tagName = $options['useIndexTagForAssoc']; } // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either. $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100); // If the value is an array then we will call this function recursively: if (is_array($v)) { // Sub elements: if (isset($options['alt_options']) && ($options['alt_options'][($stackData['path'] ?? '') . '/' . $tagName] ?? false)) { $subOptions = $options['alt_options'][($stackData['path'] ?? '') . '/' . $tagName]; $clearStackPath = (bool)($subOptions['clearStackPath'] ?? false); } else { $subOptions = $options; $clearStackPath = false; } if (empty($v)) { $content = ''; } else { $content = $nl . self::array2xml($v, $NSprefix, $level + 1, '', $spaceInd, $subOptions, [ 'parentTagName' => $tagName, 'grandParentTagName' => $stackData['parentTagName'] ?? '', 'path' => $clearStackPath ? '' : ($stackData['path'] ?? '') . '/' . $tagName, ]) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : ''); } // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array if (!isset($options['disableTypeAttrib']) || (int)$options['disableTypeAttrib'] != 2) { $attr .= ' type="array"'; } } else { $stringValue = (string)$v; // Just a value: // Look for binary chars: $vLen = strlen($stringValue); // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string! if ($vLen && strcspn($stringValue, $binaryChars) != $vLen) { // If the value contained binary chars then we base64-encode it and set an attribute to notify this situation: $content = $nl . chunk_split(base64_encode($stringValue)); $attr .= ' base64="1"'; } else { // Otherwise, just htmlspecialchar the stuff: $content = htmlspecialchars($stringValue); $dType = gettype($v); if ($dType !== 'string' && !($options['disableTypeAttrib'] ?? false)) { $attr .= ' type="' . $dType . '"'; } } } if ($tagName !== '') { // Add the element to the output string: $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '') . '<' . $NSprefix . $tagName . $attr . '>' . $content . '' . $nl; } } // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value: if (!$level) { $output = '<' . $docTag . '>' . $nl . $output . ''; } return $output; } /** * Converts an XML string to a PHP array. * This is the reverse function of array2xml() * This is a wrapper for xml2arrayProcess that adds a two-level cache * * @param string $string XML content to convert into an array * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:" * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array * @return array|string If the parsing had errors, a string with the error message is returned. Otherwise an array with the content. * @see array2xml() * @see xml2arrayProcess() */ public static function xml2array(string $string, string $NSprefix = '', bool $reportDocTag = false): array|string { $runtimeCache = static::makeInstance(CacheManager::class)->getCache('runtime'); $firstLevelCache = $runtimeCache->get('generalUtilityXml2Array') ?: []; $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0')); // Look up in first level cache if (empty($firstLevelCache[$identifier])) { $firstLevelCache[$identifier] = self::xml2arrayProcess($string, $NSprefix, $reportDocTag); $runtimeCache->set('generalUtilityXml2Array', $firstLevelCache); } return $firstLevelCache[$identifier]; } /** * Converts an XML string to a PHP array. * This is the reverse function of array2xml() * * @param string $string XML content to convert into an array * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:" * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array * @return array|string If the parsing had errors, a string with the error message is returned. Otherwise an array with the content. * @see array2xml() */ public static function xml2arrayProcess(string $string, string $NSprefix = '', bool $reportDocTag = false): array|string { $string = trim((string)$string); // Create parser: $parser = xml_parser_create(); $vals = []; xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0); // Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!! $match = []; preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match); $theCharset = $match[1] ?? 'utf-8'; // us-ascii / utf-8 / iso-8859-1 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); // Parse content: xml_parse_into_struct($parser, $string, $vals); // If error, return error message: if (xml_get_error_code($parser)) { return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser)); } // Init vars: $stack = [[]]; $stacktop = 0; $current = []; $tagName = ''; $documentTag = ''; // Traverse the parsed XML structure: foreach ($vals as $val) { // First, process the tag-name (which is used in both cases, whether "complete" or "close") $tagName = $val['tag']; if (!$documentTag) { $documentTag = $tagName; } // Test for name space: $tagName = $NSprefix && str_starts_with($tagName, $NSprefix) ? substr($tagName, strlen($NSprefix)) : $tagName; // Test for numeric tag, encoded on the form "nXXX": $testNtag = substr($tagName, 1); // Closing tag. $tagName = $tagName[0] === 'n' && MathUtility::canBeInterpretedAsInteger($testNtag) ? (int)$testNtag : $tagName; // Test for alternative index value: if ((string)($val['attributes']['index'] ?? '') !== '') { $tagName = $val['attributes']['index']; } // Setting tag-values, manage stack: switch ($val['type']) { case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array: // Setting blank place holder $current[$tagName] = []; $stack[$stacktop++] = $current; $current = []; break; case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer. $oldCurrent = $current; $current = $stack[--$stacktop]; // Going to the end of array to get placeholder key, key($current), and fill in array next: end($current); $current[key($current)] = $oldCurrent; unset($oldCurrent); break; case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it. if (!empty($val['attributes']['base64'])) { $current[$tagName] = base64_decode($val['value']); } else { // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!! $current[$tagName] = (string)($val['value'] ?? ''); // Cast type: switch ((string)($val['attributes']['type'] ?? '')) { case 'integer': $current[$tagName] = (int)$current[$tagName]; break; case 'double': $current[$tagName] = (float)$current[$tagName]; break; case 'boolean': $current[$tagName] = (bool)$current[$tagName]; break; case 'NULL': $current[$tagName] = null; break; case 'array': // MUST be an empty array since it is processed as a value; Empty arrays would end up here because they would have no tags inside... $current[$tagName] = []; break; } } break; } } if ($reportDocTag) { $current[$tagName]['_DOCUMENT_TAG'] = $documentTag; } // Finally return the content of the document tag. return $current[$tagName]; } /** * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again. * * @param array> $vals An array of XML parts, see xml2tree * @return string Re-compiled XML data. */ public static function xmlRecompileFromStructValArray(array $vals): string { $XMLcontent = ''; foreach ($vals as $val) { $type = $val['type']; // Open tag: if ($type === 'open' || $type === 'complete') { $XMLcontent .= '<' . $val['tag']; if (isset($val['attributes'])) { foreach ($val['attributes'] as $k => $v) { $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"'; } } if ($type === 'complete') { if (isset($val['value'])) { $XMLcontent .= '>' . htmlspecialchars($val['value']) . ''; } else { $XMLcontent .= '/>'; } } else { $XMLcontent .= '>'; } if ($type === 'open' && isset($val['value'])) { $XMLcontent .= htmlspecialchars($val['value']); } } // Finish tag: if ($type === 'close') { $XMLcontent .= ''; } // Cdata if ($type === 'cdata') { $XMLcontent .= htmlspecialchars($val['value']); } } return $XMLcontent; } /************************* * * FILES FUNCTIONS * *************************/ /** * Reads the file or url $url and returns the content * If you are having trouble with proxies when reading URLs you can configure your way out of that with settings within $GLOBALS['TYPO3_CONF_VARS']['HTTP']. * * @param string $url File/URL to read * @return string|false The content from the resource given as input. FALSE if an error has occurred. */ public static function getUrl(string $url): string|false { // Looks like it's an external file, use Guzzle by default if (preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) { $requestFactory = static::makeInstance(RequestFactory::class); try { $response = $requestFactory->request($url); } catch (TransferException $exception) { return false; } $content = $response->getBody()->getContents(); } else { $content = @file_get_contents($url); } return $content; } /** * Writes $content to the file $file * * @param string $file Filepath to write to * @param string $content Content to write * @param bool $changePermissions If TRUE, permissions are forced to be set * @return bool TRUE if the file was successfully opened and written to. */ public static function writeFile(string $file, string $content, bool $changePermissions = false): bool { if (!@is_file($file)) { $changePermissions = true; } if ($fd = fopen($file, 'wb')) { $res = fwrite($fd, $content); fclose($fd); if ($res === false) { return false; } // Change the permissions only if the file has just been created if ($changePermissions) { static::fixPermissions($file); } return true; } return false; } /** * Sets the file system mode and group ownership of a file or a folder. * * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative * @param bool $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder) * @return bool TRUE on success, FALSE on error, always TRUE on Windows OS */ public static function fixPermissions(string $path, bool $recursive = false): bool { $targetPermissions = null; if (Environment::isWindows()) { return true; } $result = false; // Make path absolute if (!PathUtility::isAbsolutePath($path)) { $path = static::getFileAbsFileName($path); } if (static::isAllowedAbsPath($path)) { if (@is_file($path)) { $targetPermissions = (string)($GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'] ?? '0644'); } elseif (@is_dir($path)) { $targetPermissions = (string)($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] ?? '0755'); } if (!empty($targetPermissions)) { // make sure it's always 4 digits $targetPermissions = str_pad($targetPermissions, 4, '0', STR_PAD_LEFT); $targetPermissions = octdec($targetPermissions); // "@" is there because file is not necessarily OWNED by the user $result = @chmod($path, (int)$targetPermissions); } // Set createGroup if not empty if ( isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']) && $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'] !== '' ) { // "@" is there because file is not necessarily OWNED by the user $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']); $result = $changeGroupResult ? $result : false; } // Call recursive if recursive flag if set and $path is directory if ($recursive && @is_dir($path)) { $handle = opendir($path); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { $recursionResult = null; if ($file !== '.' && $file !== '..') { if (@is_file($path . '/' . $file)) { $recursionResult = static::fixPermissions($path . '/' . $file); } elseif (@is_dir($path . '/' . $file)) { $recursionResult = static::fixPermissions($path . '/' . $file, true); } if (isset($recursionResult) && !$recursionResult) { $result = false; } } } closedir($handle); } } } return $result; } /** * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...) * Accepts an additional subdirectory in the file path! * * @param string $filepath Absolute file path to write within the typo3temp/ or Environment::getVarPath() folder - the file path must be prefixed with this path * @param string $content Content string to write * @return string|null Returns NULL on success, otherwise an error string telling about the problem. */ public static function writeFileToTypo3tempDir(string $filepath, string $content): ?string { // Parse filepath into directory and basename: $fI = pathinfo($filepath); $fI['dirname'] .= '/'; // Check parts: if (!static::validPathStr($filepath) || !$fI['basename'] || strlen($fI['basename']) >= 60) { return 'Input filepath "' . $filepath . '" was generally invalid!'; } // Setting main temporary directory name (standard) $allowedPathPrefixes = [ Environment::getPublicPath() . '/typo3temp' => 'Environment::getPublicPath() + "/typo3temp/"', ]; // Also allow project-path + /var/ if (Environment::getVarPath() !== Environment::getPublicPath() . '/typo3temp/var') { $relPath = substr(Environment::getVarPath(), strlen(Environment::getProjectPath()) + 1); $allowedPathPrefixes[Environment::getVarPath()] = 'ProjectPath + ' . $relPath; } $errorMessage = null; foreach ($allowedPathPrefixes as $pathPrefix => $prefixLabel) { $dirName = $pathPrefix . '/'; // Invalid file path, let's check for the other path, if it exists if (!str_starts_with($fI['dirname'], $dirName)) { if ($errorMessage === null) { $errorMessage = '"' . $fI['dirname'] . '" was not within directory ' . $prefixLabel; } continue; } // This resets previous error messages from the first path $errorMessage = null; if (!@is_dir($dirName)) { $errorMessage = $prefixLabel . ' was not a directory!'; // continue and see if the next iteration resets the errorMessage above continue; } // Checking if the "subdir" is found $subdir = substr($fI['dirname'], strlen($dirName)); if ($subdir) { if (preg_match('#^(?:[[:alnum:]_]+/)+$#', $subdir)) { $dirName .= $subdir; if (!@is_dir($dirName)) { static::mkdir_deep($pathPrefix . '/' . $subdir); } } else { $errorMessage = 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/+"'; break; } } // Checking dir-name again (sub-dir might have been created) if (@is_dir($dirName)) { if ($filepath === $dirName . $fI['basename']) { static::writeFile($filepath, $content, true); if (!@is_file($filepath)) { $errorMessage = 'The file was not written to the disk. Please, check that you have write permissions to the ' . $prefixLabel . ' directory.'; } break; } $errorMessage = 'Calculated file location didn\'t match input "' . $filepath . '".'; break; } $errorMessage = '"' . $dirName . '" is not a directory!'; break; } return $errorMessage; } /** * Wrapper function for mkdir. * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'] * * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally. * @return bool TRUE if operation was successful */ public static function mkdir(string $newFolder): bool { $result = @mkdir($newFolder, (int)octdec((string)($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] ?? '0'))); if ($result) { static::fixPermissions($newFolder); } return $result; } /** * Creates a directory - including parent directories if necessary and * sets permissions on newly created directories. * * @param string $directory Target directory to create * @throws \RuntimeException If directory could not be created */ public static function mkdir_deep(string $directory): void { // Ensure there is only one slash $fullPath = rtrim($directory, '/'); if ($fullPath !== '' && !is_dir($fullPath)) { $firstCreatedPath = static::createDirectoryPath($fullPath . '/'); if ($firstCreatedPath !== '') { static::fixPermissions($firstCreatedPath, true); } } } /** * Creates directories for the specified paths if they do not exist. This * functions sets proper permission mask but does not set proper user and * group. * * @return string Path to the first created directory in the hierarchy * @see \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep * @throws \RuntimeException If directory could not be created */ protected static function createDirectoryPath(string $fullDirectoryPath): string { $currentPath = $fullDirectoryPath; $firstCreatedPath = ''; $permissionMask = (int)octdec((string)($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] ?? '0')); if (!@is_dir($currentPath)) { do { $firstCreatedPath = $currentPath; $separatorPosition = (int)strrpos($currentPath, DIRECTORY_SEPARATOR); $currentPath = substr($currentPath, 0, $separatorPosition); } while (!is_dir($currentPath) && $separatorPosition > 0); $result = @mkdir($fullDirectoryPath, $permissionMask, true); // Check existence of directory again to avoid race condition. Directory could have get created by another process between previous is_dir() and mkdir() if (!$result && !@is_dir($fullDirectoryPath)) { throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251401); } } return $firstCreatedPath; } /** * Wrapper function for rmdir, allowing recursive deletion of folders and files * * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally. * @param bool $removeNonEmpty Allow deletion of non-empty directories * @return bool TRUE if operation was successful */ public static function rmdir(string $path, bool $removeNonEmpty = false): bool { $OK = false; // Remove trailing slash $path = preg_replace('|/$|', '', $path) ?? ''; $isWindows = DIRECTORY_SEPARATOR === '\\'; if (file_exists($path)) { $OK = true; if (!is_link($path) && is_dir($path)) { if ($removeNonEmpty === true && ($handle = @opendir($path))) { $entries = []; while (false !== ($file = readdir($handle))) { if ($file === '.' || $file === '..') { continue; } $entries[] = $path . '/' . $file; } closedir($handle); foreach ($entries as $entry) { if (!static::rmdir($entry, $removeNonEmpty)) { $OK = false; } } } if ($OK) { $OK = @rmdir($path); } } elseif (is_link($path) && is_dir($path) && $isWindows) { $OK = @rmdir($path); } else { // If $path is a file, simply remove it $OK = @unlink($path); } clearstatcache(); } elseif (is_link($path)) { $OK = @unlink($path); if (!$OK && $isWindows) { // Try to delete dead folder links on Windows systems $OK = @rmdir($path); } clearstatcache(); } return $OK; } /** * Returns an array with the names of folders in a specific path * Will return 'error' (string) if there were an error with reading directory content. * Will return null if provided path is false. * * @param string $path Path to list directories from * @return string[]|string|null Returns an array with the directory entries as values. If no path is provided, the return value will be null. */ public static function get_dirs(string $path): array|string|null { $dirs = null; if ($path) { if (is_dir($path)) { $dir = scandir($path); $dirs = []; foreach ($dir as $entry) { if (is_dir($path . '/' . $entry) && $entry !== '..' && $entry !== '.') { $dirs[] = $entry; } } } else { $dirs = 'error'; } } return $dirs; } /** * Finds all files in a given path and returns them as an array. Each * array key is a md5 hash of the full path to the file. This is done because * 'some' extensions like the import/export extension depend on this. * * @param string $path The path to retrieve the files from. * @param string $extensionList A comma-separated list of file extensions. Only files of the specified types will be retrieved. When left blank, files of any type will be retrieved. * @param bool $prependPath If TRUE, the full path to the file is returned. If FALSE only the file name is returned. * @param string $order The sorting order. The default sorting order is alphabetical. Setting $order to 'mtime' will sort the files by modification time. * @param string $excludePattern A regular expression pattern of file names to exclude. For example: 'clear.gif' or '(clear.gif|.htaccess)'. The pattern will be wrapped with: '/^' and '$/'. * @return array|string Array of the files found, or an error message in case the path could not be opened. */ public static function getFilesInDir(string $path, string $extensionList = '', bool $prependPath = false, string $order = '', string $excludePattern = ''): array|string { $excludePattern = (string)$excludePattern; $path = rtrim($path, '/'); if (!@is_dir($path)) { return []; } $rawFileList = scandir($path); if ($rawFileList === false) { return 'error opening path: "' . $path . '"'; } $pathPrefix = $path . '/'; $allowedFileExtensionArray = self::trimExplode(',', $extensionList); $extensionList = ',' . str_replace(' ', '', $extensionList) . ','; $files = []; foreach ($rawFileList as $entry) { $completePathToEntry = $pathPrefix . $entry; if (!@is_file($completePathToEntry)) { continue; } foreach ($allowedFileExtensionArray as $allowedFileExtension) { if ( ($extensionList === ',,' || str_ends_with(mb_strtolower($entry), mb_strtolower('.' . $allowedFileExtension))) && ($excludePattern === '' || !preg_match('/^' . $excludePattern . '$/', $entry)) ) { if ($order !== 'mtime') { $files[] = $entry; } else { // Store the value in the key so we can do a fast asort later. $files[$entry] = filemtime($completePathToEntry); } } } } $valueName = 'value'; if ($order === 'mtime') { asort($files); $valueName = 'key'; } $valuePathPrefix = $prependPath ? $pathPrefix : ''; $foundFiles = []; /** @noinspection PhpUnusedLocalVariableInspection key is possibly used with "valueName */ foreach ($files as $key => $value) { // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension) $foundFiles[md5($pathPrefix . ${$valueName})] = $valuePathPrefix . ${$valueName}; } return $foundFiles; } /** * Recursively gather all files and folders of a path. * * @param string[] $fileArr Empty input array (will have files added to it) * @param string $path The path to read recursively from (absolute) (include trailing slash!) * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected. * @param bool $regDirs If set, directories are also included in output. * @param int $recursivityLevels The number of levels to dig down... * @param string $excludePattern regex pattern of files/directories to exclude * @return array An array with the found files/directories. */ public static function getAllFilesAndFoldersInPath(array $fileArr, string $path, string $extList = '', bool $regDirs = false, int $recursivityLevels = 99, string $excludePattern = ''): array { if ($regDirs) { $fileArr[md5($path)] = $path; } $fileArr = array_merge($fileArr, (array)self::getFilesInDir($path, $extList, true, '', $excludePattern)); $dirs = self::get_dirs($path); if ($recursivityLevels > 0 && is_array($dirs)) { foreach ($dirs as $subdirs) { if ((string)$subdirs !== '' && ($excludePattern === '' || !preg_match('/^' . $excludePattern . '$/', $subdirs))) { $fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern); } } } return $fileArr; } /** * Removes the absolute part of all files/folders in fileArr * * @param string[] $fileArr The file array to remove the prefix from * @param string $prefixToRemove The prefix path to remove (if found as first part of string!) * @return string[]|string The input $fileArr processed, or a string with an error message, when an error occurred. */ public static function removePrefixPathFromList(array $fileArr, string $prefixToRemove): array|string { foreach ($fileArr as &$absFileRef) { if (str_starts_with($absFileRef, $prefixToRemove)) { $absFileRef = substr($absFileRef, strlen($prefixToRemove)); } else { return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!'; } } unset($absFileRef); return $fileArr; } /** * Fixes a path for windows-backslashes and reduces double-slashes to single slashes */ public static function fixWindowsFilePath(string $theFile): string { return str_replace(['\\', '//'], '/', $theFile); } /** * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already. * - If already having a scheme, nothing is prepended * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host) * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR) * * @param string $path URL / path to prepend full URL addressing to. * @return ($path is non-empty-string ? non-empty-string : string) */ public static function locationHeaderUrl(string $path, ServerRequestInterface $request): string { if (str_starts_with($path, '//')) { return $path; } $normalizedParams = $request->getAttribute('normalizedParams'); // relative to HOST if (str_starts_with($path, '/')) { return $normalizedParams->getRequestHost() . $path; } $urlComponents = parse_url($path); if (!($urlComponents['scheme'] ?? false)) { // No scheme either return $normalizedParams->getRequestDir() . $path; } return $path; } /** * Returns the maximum upload size for a file that is allowed. Measured in KB. * This might be handy to find out the real upload limit that is possible for this * TYPO3 installation. * * @return int Maximum size of uploads that are allowed in KiB (divider 1024) */ public static function getMaxUploadFileSize(): int { $uploadMaxFilesize = (string)ini_get('upload_max_filesize'); $postMaxSize = (string)ini_get('post_max_size'); // Check for PHP restrictions of the maximum size of one of the $_FILES $phpUploadLimit = self::getBytesFromSizeMeasurement($uploadMaxFilesize); // Check for PHP restrictions of the maximum $_POST size $phpPostLimit = self::getBytesFromSizeMeasurement($postMaxSize); // If the total amount of post data is smaller (!) than the upload_max_filesize directive, // then this is the real limit in PHP $phpUploadLimit = $phpPostLimit > 0 && $phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit; return (int)(floor($phpUploadLimit) / 1024); } /** * Gets the bytes value from a measurement string like "100k". * * @param string $measurement The measurement (e.g. "100k") * @return int The bytes value (e.g. 102400) */ public static function getBytesFromSizeMeasurement(string $measurement): int { $bytes = (float)$measurement; if (stripos($measurement, 'G')) { $bytes *= 1024 * 1024 * 1024; } elseif (stripos($measurement, 'M')) { $bytes *= 1024 * 1024; } elseif (stripos($measurement, 'K')) { $bytes *= 1024; } return (int)$bytes; } /** * Writes string to a temporary file named after the md5-hash of the string * Quite useful for extensions adding their custom built JavaScript during runtime. * * @param string $content JavaScript to write to file. * @return string filename to include in the ` * (`[[JSON]]` represents return value of this function) */ public static function jsonEncodeForJavaScript(mixed $value): string { $json = (string)json_encode($value, JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG); return strtr( $json, [ // comments below refer to JSON-encoded data '\\\\' => '\\\\u005C', // `"\\Vendor\\Package"` -> `"\\u005CVendor\\u005CPackage"` '\\t' => '\\u0009', // `"\t"` -> `"\u0009"` '\\n' => '\\u000A', // `"\n"` -> `"\u000A"` '\\r' => '\\u000D', // `"\r"` -> `"\u000D"` ] ); } /** * Very, very, very basic CSS sanitizer which removes `{`, `}`, `\n`, `\r` * from CSS variable values and encodes potential HTML entities `<`+`>`. */ public static function sanitizeCssVariableValue(string $value): string { $value = str_replace(['{', '}', "\n", "\r"], '', $value); // keep quotes, e.g. for `background: url("/res/background.png")` return htmlspecialchars($value, ENT_SUBSTITUTE); } protected static function getLogger(): LoggerInterface { return static::makeInstance(LogManager::class)->getLogger(__CLASS__); } }