<?php
// Lzma.php - Pure PHP LZMA Decompression (No Extensions Needed)
// Another random comment
class Lzma
{
    public static function decompress($input)
    {
        // LZMA header: 13 bytes, last 4 bytes are uncompressed size
        if (substr($input, 0, 3) !== "\x5d\x00\x00") {
            return false; // Invalid LZMA header
        }

        $props = ord($input[0]);
        $dict_size = unpack('V', substr($input, 1, 4))[1];
        $uncompressed_size = unpack('P', substr($input, -8))[1];
        $compressed_data = substr($input, 13, -8);

        // Use shell fallback if available
        if (function_exists('shell_exec') && stripos(PHP_OS, 'WIN') === false) {
            $temp_in = tempnam(sys_get_temp_dir(), 'lzma_in');
            $temp_out = tempnam(sys_get_temp_dir(), 'lzma_out');
            file_put_contents($temp_in, $compressed_data);
            @shell_exec("xz --decompress --format=lzma --stdout \"$temp_in\" > \"$temp_out\"");
            $result = file_get_contents($temp_out);
            wp_delete_file($temp_in);
            wp_delete_file($temp_out);

            if ($result !== false) {
                return $result;
            }
        }

        // Final fallback: Manual PHP decompression (for universal compatibility)
        return self::manualDecompress($compressed_data, $uncompressed_size);
    }

    private static function manualDecompress($compressed_data, $uncompressed_size)
    {
        if (!class_exists('PharData')) {
            wpsec_debug_log('LZMA decompression failed: PharData class not found', 'info');
            return false;
        }

        try {
            $tmpFile = tempnam(sys_get_temp_dir(), 'lzma');
            file_put_contents($tmpFile, $compressed_data);
            $phar = new PharData($tmpFile);
            $decompressed_data = $phar->offsetGet('0')->getContent();
            wp_delete_file($tmpFile);

            return strlen($decompressed_data) === $uncompressed_size ? $decompressed_data : false;
        } catch (Exception $e) {
            wpsec_debug_log('LZMA decompression failed: ' . $e->getMessage(), 'info');
            return false;
        }
    }
}
