compressToBuffer($outputBuffer); return \pack('C*', ...$outputBuffer); } public function uncompress(string $compressedText): string { if ($compressedText === '') { return $compressedText; } $byteArray = \array_values(\unpack('C*', $compressedText) ?: []); $outputBuffer = []; (new SnappyDecompressor($byteArray))->uncompressToBuffer($outputBuffer); return \pack('C*', ...$outputBuffer); } } /** * @internal This class is not meant to be used by library users. Please use Flow\Snappy\Snappy instead. */ final class SnappyCompressor { private const BLOCK_LOG = 16; private const BLOCK_SIZE = 1 << self::BLOCK_LOG; private const MAX_HASH_TABLE_BITS = 14; private array $array; private int $arrayLength; private array $globalHashTables = []; public function __construct(array $uncompressed) { $this->array = $uncompressed; $this->arrayLength = \count($uncompressed); } public function compressToBuffer(array &$outBuffer): int { $pos = 0; $outPos = 0; $outPos = $this->putVarInt($this->arrayLength, $outBuffer, $outPos); while ($pos < $this->arrayLength) { $fragmentSize = \min($this->arrayLength - $pos, self::BLOCK_SIZE); $outPos = $this->compressFragment($this->array, $pos, $fragmentSize, $outBuffer, $outPos); $pos += $fragmentSize; } return $outPos; } public function maxCompressedLength(): int { $sourceLen = \count($this->array); return 32 + $sourceLen + (int) \floor($sourceLen / 6); } private function compressFragment(array $input, int $ip, int $inputSize, array &$output, int $op): int { $hashTableBits = 1; while ((1 << $hashTableBits) <= $inputSize && $hashTableBits <= self::MAX_HASH_TABLE_BITS) { $hashTableBits++; } $hashTableBits--; $hashFuncShift = 32 - $hashTableBits; if (!isset($this->globalHashTables[$hashTableBits])) { $this->globalHashTables[$hashTableBits] = \array_fill(0, 1 << $hashTableBits, 0); } $hashTable = []; foreach ($this->globalHashTables[$hashTableBits] as $key => $value) { $hashTable[$key] = 0; } $ipEnd = $ip + $inputSize; $baseIp = $ip; $nextEmit = $ip; $inputMargin = 15; if ($inputSize >= $inputMargin) { $ipLimit = $ipEnd - $inputMargin; $ip++; $nextHash = $this->hashFunc($this->load32($input, $ip), $hashFuncShift); $candidate = 0; while (true) { $skip = 32; $nextIp = $ip; do { $ip = $nextIp; $hash = $nextHash; $bytesBetweenHashLookups = (int) ($skip / 32); $skip++; $nextIp = $ip + $bytesBetweenHashLookups; if ($ip > $ipLimit) { break 2; } $nextHash = $this->hashFunc($this->load32($input, $nextIp), $hashFuncShift); $candidate = $baseIp + $hashTable[$hash]; $hashTable[$hash] = $ip - $baseIp; } while (!$this->equals32($input, $ip, $candidate)); $op = $this->emitLiteral($input, $nextEmit, $ip - $nextEmit, $output, $op); do { $base = $ip; $matched = 4; while ($ip + $matched < $ipEnd && $input[$ip + $matched] === $input[$candidate + $matched]) { $matched++; } $ip += $matched; $offset = $base - $candidate; $op = $this->emitCopy($output, $op, $offset, $matched); $nextEmit = $ip; if ($ip >= $ipLimit) { break 2; } $prevHash = $this->hashFunc($this->load32($input, $ip - 1), $hashFuncShift); $hashTable[$prevHash] = $ip - 1 - $baseIp; $curHash = $this->hashFunc($this->load32($input, $ip), $hashFuncShift); $candidate = $baseIp + $hashTable[$curHash]; $hashTable[$curHash] = $ip - $baseIp; } while ($this->equals32($input, $ip, $candidate)); $ip++; $nextHash = $this->hashFunc($this->load32($input, $ip), $hashFuncShift); } } if ($nextEmit < $ipEnd) { return $this->emitLiteral($input, $nextEmit, $ipEnd - $nextEmit, $output, $op); } return $op; } private function copyBytes(array $fromArray, int $fromPos, array &$toArray, int $toPos, int $length): void { for ($i = 0; $i < $length; $i++) { $toArray[$toPos + $i] = $fromArray[$fromPos + $i]; } } private function emitCopy(array &$output, int $op, int $offset, int $len): int { while ($len >= 68) { $op = $this->emitCopyLessThan64($output, $op, $offset, 64); $len -= 64; } if ($len > 64) { $op = $this->emitCopyLessThan64($output, $op, $offset, 60); $len -= 60; } return $this->emitCopyLessThan64($output, $op, $offset, $len); } private function emitCopyLessThan64(array &$output, int $op, int $offset, int $len): int { if ($len < 12 && $offset < 2048) { $output[$op] = 1 + (($len - 4) << 2) + (($offset >> 8) << 5); $output[$op + 1] = $offset & 0xFF; return $op + 2; } $output[$op] = 2 + (($len - 1) << 2); $output[$op + 1] = $offset & 0xFF; $output[$op + 2] = $offset >> 8; return $op + 3; } private function emitLiteral(array &$input, int $ip, int $len, array &$output, int $op): int { if ($len <= 60) { $output[$op] = ($len - 1) << 2; $op++; } elseif ($len < 256) { $output[$op] = 60 << 2; $output[$op + 1] = $len - 1; $op += 2; } else { $output[$op] = 61 << 2; $output[$op + 1] = ($len - 1) & 0xFF; $output[$op + 2] = ($len - 1) >> 8; $op += 3; } $this->copyBytes($input, $ip, $output, $op, $len); return $op + $len; } private function equals32(array $array, int $pos1, int $pos2): bool { return $array[$pos1] === $array[$pos2] && $array[$pos1 + 1] === $array[$pos2 + 1] && $array[$pos1 + 2] === $array[$pos2 + 2] && $array[$pos1 + 3] === $array[$pos2 + 3]; } private function hashFunc(int $key, int $hashFuncShift): int { $multiplied = $key * 0x1E35A7BD; // Emulate unsigned right shift in PHP return ($multiplied >> $hashFuncShift) & ((1 << (32 - $hashFuncShift)) - 1); } private function load32(array $array, int $pos): int { if (!isset($array[$pos])) { return 0; } if (!isset($array[$pos + 1])) { return $array[$pos]; } if (!isset($array[$pos + 2])) { return $array[$pos] + ($array[$pos + 1] << 8); } if (!isset($array[$pos + 3])) { return $array[$pos] + ($array[$pos + 1] << 8) + ($array[$pos + 2] << 16); } return $array[$pos] + ($array[$pos + 1] << 8) + ($array[$pos + 2] << 16) + ($array[$pos + 3] << 24); } private function putVarInt(int $value, array &$output, int $op): int { do { $output[$op] = $value & 0x7F; $value = $value >> 7; if ($value > 0) { $output[$op] += 0x80; } $op++; } while ($value > 0); return $op; } } /** * @internal This class is not meant to be used by library users. Please use Flow\Snappy\Snappy instead. */ final class SnappyDecompressor { private const WORD_MASK = [0, 0xFF, 0xFFFF, 0xFFFFFF, 0xFFFFFFFF]; private array $array; private int $arrayLength; private int $pos = 0; public function __construct(array $compressed) { $this->array = $compressed; $this->arrayLength = \count($compressed); } public function readUncompressedLength(): int { $result = 0; $shift = 0; while ($shift < 32 && $this->pos < $this->arrayLength) { $c = $this->array[$this->pos]; $this->pos++; $val = $c & 0x7F; if (($val << $shift >> $shift) !== $val) { return -1; } $result |= $val << $shift; if ($c < 128) { return $result; } $shift += 7; } return -1; } public function uncompressToBuffer(array &$outBuffer): bool { $outBuffer = \array_fill(0, $this->readUncompressedLength(), 0); $pos = $this->pos; $outPos = 0; $len = $offset = 0; while ($pos < \count($this->array)) { $c = $this->array[$pos]; $pos++; if (($c & 0x3) === 0) { // Literal $len = ($c >> 2) + 1; if ($len > 60) { if ($pos + 3 >= $this->arrayLength) { return false; } $smallLen = $len - 60; $len = $this->array[$pos] + ($this->array[$pos + 1] << 8) + ($this->array[$pos + 2] << 16) + ($this->array[$pos + 3] << 24); $len = ($len & self::WORD_MASK[$smallLen]) + 1; $pos += $smallLen; } if ($pos + $len > $this->arrayLength) { return false; } $this->copyBytes($this->array, $pos, $outBuffer, $outPos, (int) $len); $pos += $len; $outPos += $len; } else { switch ($c & 0x3) { case 1: $len = (($c >> 2) & 0x7) + 4; $offset = $this->array[$pos] + (($c >> 5) << 8); $pos++; break; case 2: if ($pos + 1 >= $this->arrayLength) { return false; } $len = ($c >> 2) + 1; $offset = $this->array[$pos] + ($this->array[$pos + 1] << 8); $pos += 2; break; case 3: if ($pos + 3 >= $this->arrayLength) { return false; } $len = ($c >> 2) + 1; $offset = $this->array[$pos] + ($this->array[$pos + 1] << 8) + ($this->array[$pos + 2] << 16) + ($this->array[$pos + 3] << 24); $pos += 4; break; } if ($offset === 0 || $offset > $outPos) { return false; } $this->selfCopyBytes($outBuffer, $outPos, $offset, $len); $outPos += $len; } } return true; } private function copyBytes(array $fromArray, int $fromPos, array &$toArray, int $toPos, int $length): void { for ($i = 0; $i < $length; $i++) { $toArray[$toPos + $i] = $fromArray[$fromPos + $i]; } } private function selfCopyBytes(array &$array, int $pos, int $offset, int $length): void { for ($i = 0; $i < $length; $i++) { $array[$pos + $i] = $array[$pos - $offset + $i]; } } } /** * BEGIN LIB: PSR-MESSAGE */ /** * php-fig/http-message: Copyright (c) 2014 PHP Framework Interoperability Group Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Describes a data stream. * * Typically, an instance will wrap a PHP stream; this interface provides * a wrapper around the most common operations, including serialization of * the entire stream to a string. */ interface StreamInterface { /** * Reads all data from the stream into a string, from the beginning to end. * * This method MUST attempt to seek to the beginning of the stream before * reading data and read the stream until the end is reached. * * Warning: This could attempt to load a large amount of data into memory. * * This method MUST NOT raise an exception in order to conform with PHP's * string casting operations. * * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring * @return string */ public function __toString(): string; /** * Closes the stream and any underlying resources. * * @return void */ public function close(): void; /** * Separates any underlying resources from the stream. * * After the stream has been detached, the stream is in an unusable state. * * @return resource|null Underlying PHP stream, if any */ public function detach(); /** * Get the size of the stream if known. * * @return int|null Returns the size in bytes if known, or null if unknown. */ public function getSize(): ?int; /** * Returns the current position of the file read/write pointer * * @return int Position of the file pointer * @throws \RuntimeException on error. */ public function tell(): int; /** * Returns true if the stream is at the end of the stream. * * @return bool */ public function eof(): bool; /** * Returns whether or not the stream is seekable. * * @return bool */ public function isSeekable(): bool; /** * Seek to a position in the stream. * * @link http://www.php.net/manual/en/function.fseek.php * @param int $offset Stream offset * @param int $whence Specifies how the cursor position will be calculated * based on the seek offset. Valid values are identical to the built-in * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to * offset bytes SEEK_CUR: Set position to current location plus offset * SEEK_END: Set position to end-of-stream plus offset. * @throws \RuntimeException on failure. */ public function seek(int $offset, int $whence = SEEK_SET): void; /** * Seek to the beginning of the stream. * * If the stream is not seekable, this method will raise an exception; * otherwise, it will perform a seek(0). * * @see seek() * @link http://www.php.net/manual/en/function.fseek.php * @throws \RuntimeException on failure. */ public function rewind(): void; /** * Returns whether or not the stream is writable. * * @return bool */ public function isWritable(): bool; /** * Write data to the stream. * * @param string $string The string that is to be written. * @return int Returns the number of bytes written to the stream. * @throws \RuntimeException on failure. */ public function write(string $string): int; /** * Returns whether or not the stream is readable. * * @return bool */ public function isReadable(): bool; /** * Read data from the stream. * * @param int $length Read up to $length bytes from the object and return * them. Fewer than $length bytes may be returned if underlying stream * call returns fewer bytes. * @return string Returns the data read from the stream, or an empty string * if no bytes are available. * @throws \RuntimeException if an error occurs. */ public function read(int $length): string; /** * Returns the remaining contents in a string * * @return string * @throws \RuntimeException if unable to read or an error occurs while * reading. */ public function getContents(): string; /** * Get stream metadata as an associative array or retrieve a specific key. * * The keys returned are identical to the keys returned from PHP's * stream_get_meta_data() function. * * @link http://php.net/manual/en/function.stream-get-meta-data.php * @param string|null $key Specific metadata to retrieve. * @return array|mixed|null Returns an associative array if no key is * provided. Returns a specific key value if a key is provided and the * value is found, or null if the key is not found. */ public function getMetadata(?string $key = null); } /** * END LIB: PSR-MESSAGE */ /** * BEGIN LIB: TAR (https://github.com/jakubboucek/php-tar-stream-reader) */ /** * jakubboucek/php-tar-stream-reader MIT License Copyright (c) 2023 Jakub Bouček Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** TAR -> BEGIN: src/Exception */ class EofException extends RuntimeException { } class FileContentClosedException extends LogicException { } class InvalidArchiveFormatException extends RuntimeException { } /** TAR -> END: src/Exception */ /** TAR -> BEGIN: src/FileHandler */ interface FileHandler { /** * @param string $filename * @return resource */ public function open(string $filename); /** * @param resource $stream */ public function close($stream): void; } class Plain implements FileHandler { /** * @inheritDoc */ public function open(string $filename) { $handle = fopen($filename, 'rb'); if (is_resource($handle) === false) { throw new RuntimeException("Unable to open file '$filename'"); } return $handle; } /** * @inheritDoc */ public function close($stream): void { fclose($stream); } } class Gzip implements FileHandler { public static function match(string $filename): bool { return (bool)preg_match('/\.t?gz$/D', $filename); } /** * @inheritDoc */ public function open(string $filename) { if (!self::isAvailable()) { throw new LogicException( __CLASS__ . " requires `ext-zlib` extension to open GZipped archive: '$filename'" ); } $handle = gzopen($filename, 'rb'); if (is_resource($handle) === false) { throw new RuntimeException("Unable to open file '$filename'"); } return $handle; } /** * @inheritDoc */ public function close($stream): void { gzclose($stream); } public static function isAvailable(): bool { return function_exists('gzopen'); } } class Bz2 implements FileHandler { public static function match(string $filename): bool { return (bool)preg_match('/\.t?bz2?$/D', $filename); } /** * @inheritDoc */ public function open(string $filename) { if (!self::isAvailable()) { throw new LogicException( __CLASS__ . " requires `ext-bz2` extension to open BZ2 compressed archive: '$filename'" ); } $stream = bzopen($filename, 'r'); if (is_resource($stream) === false) { throw new RuntimeException("Unable to open file '$filename'"); } return $stream; } /** * @inheritDoc */ public function close($stream): void { bzclose($stream); } public static function isAvailable(): bool { return function_exists('bzopen'); } } /** TAR -> END: src/FileHandler */ /** TAR -> BEGIN: src/Parser */ class Header { private string $content; public function __construct(string $content) { $length = strlen($content); if ($length !== 512) { throw new InvalidArgumentException(sprintf('Tar header must be 512 bytes length, %d bytes got', $length)); } $this->content = $content; } public function isValid(): bool { return $this->getMagic() === 'ustar'; } public function getName(): string { $str = substr($this->content, 0, 100); return rtrim($str, "\0"); } public function getSize(): int { $str = rtrim(substr($this->content, 124, 12)); if (preg_match('/^[0-7]+$/D', $str) !== 1) { throw new InvalidArchiveFormatException( sprintf( "Invalid Tar header format, file size must be octal number, '%s' got instead", $str ) ); } return (int)octdec($str); } /* * Values used in typeflag field * #define REGTYPE '0' // regular file * #define AREGTYPE '\0' // regular file * #define LNKTYPE '1' // link * #define SYMTYPE '2' // reserved * #define CHRTYPE '3' // character special * #define BLKTYPE '4' // block special * #define DIRTYPE '5' // directory * #define FIFOTYPE '6' // FIFO special * #define CONTTYPE '7' // reserved * #define XHDTYPE 'x' // Extended header referring to the next file in the archive * #define XGLTYPE 'g' // Global extended header */ public function getType(): string { return $this->content[156]; } public function isFile(): bool { return $this->getType() === '0' || $this->getType() === "\0"; } public function isDir(): bool { return $this->getType() === '5'; } protected function getMagic(): string { return rtrim(substr($this->content, 257, 6)); } } interface LightStreamInterface extends StreamInterface { /** * @param resource $stream * @return void */ public function toStream($stream): void; /** * @param resource|null $context Stream context (e.g. from `stream_context_create()`) */ public function toFile(string $file, $context = null): void; } class LazyContent implements LightStreamInterface { private ?Closure $contentClosure; /** @var resource|null */ private $stream; public function __construct(Closure $contentClosure) { $this->contentClosure = $contentClosure; } public function __destruct() { $this->close(); } public function __toString(): string { if ($this->isSeekable()) { $this->seek(0); } return $this->getContents(); } /** * @param resource $stream * @return void */ public function toStream($stream): void { if ($this->isClosed()) { throw new FileContentClosedException( "File's Content is already closed, try to fetch it right after File fetched from Reader." ); } if (!is_resource($stream)) { throw new InvalidArgumentException('Stream must be a resource'); } // Direct stream-clean way, memory humble way if (!$this->isLoaded()) { // Call closure to fill stream ($this->contentClosure)($stream); $this->contentClosure = null; return; } // Backup way - reuse already loaded stream $result = stream_copy_to_stream($this->getStream(), $stream); if ($result === false) { throw new RuntimeException('Unable to write to stream'); } // Close to prevent reuse content only writed to external stream $this->close(); } /** * @param resource|null $context Stream context (e.g. from `stream_context_create()`) */ public function toFile(string $file, $context = null): void { $stream = fopen($file, 'wb', false, $context); if (!is_resource($stream)) { throw new InvalidArgumentException("Unable to open file: '$file'"); } $this->toStream($stream); fclose($stream); } public function isLoaded(): bool { return isset($this->stream); } public function isClosed(): bool { return !isset($this->stream) && !isset($this->contentClosure); } public function close(): void { if ($this->isClosed()) { return; } if (is_resource($this->stream)) { fclose($this->stream); } $this->stream = $this->contentClosure = null; } /** * @return resource */ public function detach() { $stream = $this->getStream(); if ($this->isSeekable()) { $this->seek(0); } $this->stream = $this->contentClosure = null; return $stream; } public function getSize(): ?int { trigger_error(sprintf("Method '%s' not implemented.", __METHOD__), E_USER_WARNING); return null; } public function tell(): int { $result = ftell($this->getStream()); if ($result === false) { throw new RuntimeException('Unable to determine stream position'); } return $result; } public function eof(): bool { return feof($this->getStream()); } public function isSeekable(): bool { return (bool)stream_get_meta_data($this->getStream())['seekable']; } public function seek(int $offset, int $whence = SEEK_SET): void { if (!$this->isSeekable()) { throw new RuntimeException('Stream is not seekable'); } if (fseek($this->getStream(), $offset, $whence) === -1) { throw new RuntimeException( sprintf( "Unable to seek to stream position %d with whence %s", $offset, var_export($whence, true) ) ); } } public function rewind(): void { $this->seek(0); } public function isWritable(): bool { return false; } public function write(string $string): int { throw new RuntimeException('Cannot write to a non-writable stream'); } public function isReadable(): bool { $this->getStream(); return true; } public function read(int $length): string { if ($length < 0) { throw new RuntimeException('Length parameter cannot be negative'); } if (0 === $length) { return ''; } try { $string = fread($this->getStream(), $length); } catch (Exception $e) { throw new RuntimeException('Unable to read from stream', 0, $e); } if ($string === false) { throw new RuntimeException('Unable to read from stream'); } return $string; } public function getContents(): string { /** @var string|false $contents */ $contents = stream_get_contents($this->getStream()); if ($contents === false) { throw new RuntimeException('Unable to read stream contents'); } return $contents; } public function getMetadata(?string $key = null) { $stream = $this->getStream(); if (!$key) { return stream_get_meta_data($stream); } $meta = stream_get_meta_data($stream); return $meta[$key] ?? null; } /** * @return resource */ private function getStream() { if ($this->isClosed()) { throw new FileContentClosedException( "File's Content is already closed, try to fetch it right after File fetched from Reader." ); } if (!isset($this->stream)) { $stream = ($this->contentClosure)(); $this->stream = $stream; $this->contentClosure = null; } return $this->stream; } } class Usage { private bool $used = false; public function used(): bool { return $this->used; } public function use(): void { if ($this->used) { throw new FileContentClosedException( "File's Content is already closed, try to fetch it right after File fetched from Reader." ); } $this->used = true; } } /** TAR -> END: src/Parser */ class File { private Header $header; private LightStreamInterface $content; /** * @param Header $header * @param LightStreamInterface $content */ public function __construct(Header $header, LightStreamInterface $content) { $this->header = $header; $this->content = $content; } public function __toString(): string { return $this->getName(); } public function getName(): string { return $this->header->getName(); } public function getType(): string { return $this->header->getType(); } public function isFile(): bool { return $this->header->isFile(); } public function isDir(): bool { return $this->header->isDir(); } public function getSize(): int { return $this->header->getSize(); } public function getContent(): LightStreamInterface { return $this->content; } } class StreamReader implements IteratorAggregate { /** @var resource */ private $stream; /** * @param resource $stream Stream resource of TAR file */ public function __construct($stream) { if (!is_resource($stream)) { throw new InvalidArgumentException('Stream must be a resource'); } $this->stream = $stream; } /** * @return Iterator */ public function getIterator(): Iterator { while (!feof($this->stream)) { try { $header = $this->readHeader(); } catch (Exception $e) { return; } $blockStart = ftell($this->stream); if (!$header->isValid()) { throw new InvalidArchiveFormatException( sprintf( 'Invalid TAR archive format: Invalid Tar header format: at %s. bytes', $blockStart ) ); } $usage = new Usage(); $contentSize = $header->getSize(); $contentPadding = ($contentSize % 512) === 0 ? 0 : 512 - ($contentSize % 512); // Closure to lazy read, prevents backwards seek or repeated reads of discharged content /** * @param resource|null $target Resource to external stream to fill it by file content * @return resource */ $contentClosure = function ($target = null) use ($usage, $contentSize, $contentPadding, $blockStart) { $usage->use(); $isExternal = is_resource($target) && get_resource_type($target); $stream = $isExternal ? $target : fopen('php://temp/maxmemory:' . PHP_TEMP_LIMIT, 'wb+'); // modified! added unlimited limit if (!$stream) { throw new RuntimeException('Unable to create temporary stream.'); } // Empty content means nothing to transport, nothing to seek if (!$contentSize) { return $stream; } $bytes = stream_copy_to_stream($this->stream, $stream, $contentSize); if ($bytes !== $contentSize) { throw new InvalidArchiveFormatException( sprintf( 'Invalid TAR archive format: Unexpected end of file at position: %s, expected %d bytes, only %d bytes read', $blockStart, $contentSize, ($bytes ?: 0) ) ); } // Only internal stream rewind if (!$isExternal) { fseek($stream, 0); } if (!$contentPadding) { return $stream; } // Skip padding $bytes = fseek($this->stream, $contentPadding, SEEK_CUR); if ($bytes === -1) { throw new InvalidArchiveFormatException( sprintf( 'Invalid TAR archive format: Unexpected end of file at position: %s, expected %d bytes of block padding', $blockStart, $contentPadding, ) ); } return $stream; }; $content = new LazyContent($contentClosure); yield new File($header, $content); // Seek after unused content if (!$usage->used()) { $usage->use(); $content->close(); if ($contentSize) { // Skip unused content $bytes = fseek($this->stream, $contentSize + $contentPadding, SEEK_CUR); if ($bytes === -1) { throw new InvalidArchiveFormatException( sprintf( 'Invalid TAR archive format: Unexpected end of file at position: %s, expected %d bytes of content and block padding', $blockStart, $contentSize + $contentPadding, ) ); } } } } } private function readHeader(): Header { do { $header = fread($this->stream, 512); if ($header === '') { throw new EofException(); } if ($header === false || strlen($header) < 512) { throw new InvalidArchiveFormatException( sprintf( 'Invalid TAR archive format: Unexpected end of file, returned non-block size: %d bytes', $header === false ? 0 : strlen($header) ) ); } } while (self::isNullFilled($header)); // ↑↑↑ TAR format inserts few blocks of nulls to EOF - just skip it return new Header($header); } private static function isNullFilled(string $string): bool { return trim($string, "\0") === ''; } } class FileReader implements IteratorAggregate { private string $filename; private FileHandler $handler; public function __construct(string $filename, ?FileHandler $handler = null) { $this->filename = $filename; if (!$handler) { // modified from // $handler = match (true) { // Gzip::match($filename) => new Gzip(), // Bz2::match($filename) => new Bz2(), // default => new Plain(), // }; $handler = null; if (Gzip::match($filename)) { $handler = new Gzip(); } elseif (Bz2::match($filename)) { $handler = new Bz2(); } else { $handler = new Plain(); } } $this->handler = $handler; } /** * @return Iterator */ public function getIterator(): Iterator { $stream = $this->handler->open($this->filename); yield from new StreamReader($stream); $this->handler->close($stream); } } /** * END LIB: TAR */ /** -------------------------------------------- * END LIBRARIES * -------------------------------------------- */ /** ------------------------------------------- * BEGIN CODE LOADER * ------------------------------------------ */ function trim_trailing_slash($x) { if (substr_count($x, '/') > 2) { if (substr($x, -1) === '/') { $x = rtrim($x, '/'); } } return $x; } $stream = fopen('php://memory', 'rw+'); $decompressedData = base64_decode(PACKED_FILE); if (SNAPPY_COMPRESSION) { $snappy = new Snappy(); $decompressedData = $snappy->uncompress($decompressedData); } fwrite($stream, $decompressedData); rewind($stream); $GLOBALS['file_map'] = array(); foreach (new StreamReader($stream) as $file) { $stream2 = fopen('php://temp/maxmemory:' . PHP_TEMP_LIMIT, 'rw+'); fwrite($stream2, $file->getContent()); rewind($stream2); $GLOBALS['file_map'][$file->getName()] = stream_get_contents($stream2); fclose($stream2); } fclose($stream); $files_parsed = 0; foreach ($GLOBALS['file_map'] as $fn => $fv) { if (str_ends_with($fn, ".php") && $fn !== "index.php") { if (str_starts_with($fv, "