Decode a zlib deflated message (when Content-encoding = deflate)

Currently requires PHP with zlib support

@param string $body
@return string
422029
public static function decodeDeflate($body)
	{
		if (! function_exists('gzuncompress')) {
			throw new RuntimeException('zlib extension is required in order to decode "deflate" encoding');
		}
		
		/**
		 * Some servers (IIS ?) send a broken deflate response, without the
		 * RFC-required zlib header.
		 *
		 * We try to detect the zlib header, and if it does not exsit we
		 * teat the body is plain DEFLATE content.
		 *
		 * This method was adapted from PEAR HTTP_Request2 by (c) Alexey Borzov
		 *
		 * @link http://framework.zend.com/issues/browse/ZF-6040
		 */
		$zlibHeader = unpack('n', substr($body, 0, 2));
		if ($zlibHeader[1] % 31 == 0) {
			return gzuncompress($body);
		} else {
			return gzinflate($body);
		}
	}
900466
public static function decodeHtmlEntities($string)
  {
    // Entities-replacements
    $entities = array ("'&(quot|#34);'i",
                        "'&(amp|#38);'i",
                        "'&(lt|#60);'i",
                        "'&(gt|#62);'i",
                        "'&(nbsp|#160);'i",
                        "'&(iexcl|#161);'i",
                        "'&(cent|#162);'i",
                        "'&(pound|#163);'i",
                        "'&(copy|#169);'i");
                        
    $entitie_replacements = array ("\"",
                                   "&",
                                   "<",
                                   ">",
                                   " ",
                                   chr(161),
                                   chr(162),
                                   chr(163),
                                   chr(169));
    
  
    $string = preg_replace($entities, $entitie_replacements, $string);
    
    // Numeric haracter reference replacement (non-HEX), like &#64; => "@"
    $string = preg_replace_callback("/&#([0-9]{1,4});/ i", function($m) {return chr($m[1]);}, $string);
    
    // Numeric character reference replacement (HEX), like &#x2f; => "/"
    $string = preg_replace_callback("/&#x([0-9a-z]{2,4});/ i", function($m) {return chr(hexdec($m[1]));}, $string);
    
    return $string;
  }
71645
protected function decodeBody()
    {
        $body = $this->getBody();

        if (isset($this->headers['Content-Type']) && in_array('application/json', $this->headers['Content-Type'])) {
            $this->decodedBody = (array) json_decode((string) $body, true);
        }

        // If the response needs to be validated
        if ($this->getRequest()->validateResponse()) {
            //Validate Response
            $this->validateResponse();
        }
    }
387910
public function getDecodedBody()
    {
        if (empty($this->decodedBody) || $this->decodedBody === null) {
            //Decode the Response Body
            $this->decodeBody();
        }

        return $this->decodedBody;
    }
347900
private InputStream decompressBody() {
        if (!decompress) {
            return body;
        }
        // if has no body, some server still set content-encoding header,
        // GZIPInputStream wrap empty input stream will cause exception. we should check this
        if (method.equals(Methods.HEAD)
                || (statusCode >= 100 && statusCode < 200) || statusCode == NOT_MODIFIED || statusCode == NO_CONTENT) {
            return body;
        }

        String contentEncoding = headers.getHeader(NAME_CONTENT_ENCODING);
        if (contentEncoding == null) {
            return body;
        }

        //we should remove the content-encoding header here?
        switch (contentEncoding) {
            case "gzip":
                try {
                    return new GZIPInputStream(body);
                } catch (IOException e) {
                    Closeables.closeQuietly(body);
                    throw new RequestsException(e);
                }
            case "deflate":
                // Note: deflate implements may or may not wrap in zlib due to rfc confusing.
                // here deal with deflate without zlib header
                return new InflaterInputStream(body, new Inflater(true));
            case "identity":
            case "compress": //historic; deprecated in most applications and replaced by gzip or deflate
            default:
                return body;
        }
    }
1345982
private function parse($body)
    {
        $response = array();
        $xml = new \SimpleXMLElement($body);

        foreach ($xml as $name => $value) {
            $k = str_replace('eway', '', $name);
            $response[$k] = (string) $value;
        }

        return $response;
    }
569268
protected function decodeBody(string $body) {
        $decoded_body = json_decode($body, true);

        if ($decoded_body === null || !is_array($decoded_body)) {
            $decoded_body = [];
        }

        return $decoded_body;
    }
206831
public static function decodeMessage(string $message): Message
    {
        $offset = 0;
        $header = self::decodeHeader($message, $offset);
        $messageObject = new Message($header);
        $messageObject->setQuestions(self::decodeResourceRecords($message, $header->getQuestionCount(), $offset, true));
        $messageObject->setAnswers(self::decodeResourceRecords($message, $header->getAnswerCount(), $offset));
        $messageObject->setAuthoritatives(self::decodeResourceRecords($message, $header->getNameServerCount(), $offset));
        $messageObject->setAdditionals(self::decodeResourceRecords($message, $header->getAdditionalRecordsCount(), $offset));

        return $messageObject;
    }
289539
def decoded_gzip_body
      unless gzip = Zlib::GzipReader.new(StringIO.new(raw_body))
        raise ArgumentError, "Unable to create Zlib::GzipReader"
      end
      gzip.read
    ensure
      gzip.close if gzip
    end
527734
public function decode($encrypted)
    {

        //$cipher_all = explode("/", $cipher_in);
        //$cipher = $cipher_all[0];

        $blocks = explode("|x", $encrypted);
        $delimiter = array_search("::", $blocks);


        $cipherStream = array_slice($blocks, 0, (int)$delimiter);


        unset($blocks[(int)$delimiter]);
        unset($blocks[(int)$delimiter + 1]);

        $publicKeyArray = array_slice($blocks, (int)$delimiter);

        $publicKey = implode('', $publicKeyArray);
        $privateKey = $this->key;

        $hashKey = sha1($privateKey . "+" . (string)$publicKey);
        $hashArray = str_split($hashKey);

        $counter = 0;
        for ($i = 0; $i < sizeof($cipherStream); $i++) {
            if ($counter > 40)
                $counter = 0;
            $cryptChar = hexdec($cipherStream[$i]) - ord((string)$hashArray[$counter]);
            $cryptChar -= floor($cryptChar / 127) * 127;
            $cipherText[$i] = chr($cryptChar);
            $counter++;
        }

        $plaintext = implode("", $cipherText);

        return $plaintext;
    }
118475
public static function decodeChunkedBody($body)
    {
        $decBody = '';
        
        while (trim($body)) {
            if (! preg_match("/^([\da-fA-F]+)[^\r\n]*\r\n/sm", $body, $m)) {
                require_once 'Zend/Http/Exception.php';
                throw new Zend_Http_Exception("Error parsing body - doesn't seem to be a chunked message");
            }

            $length = hexdec(trim($m[1]));
            $cut = strlen($m[0]);

            $decBody .= substr($body, $cut, $length);
            $body = substr($body, $cut + $length + 2);
        }

        return $decBody;
    }
1135282
public static function decodeChunkedBody($body)
    {
        $decBody = '';

        // If mbstring overloads substr and strlen functions, we have to
        // override it's internal encoding
        if (function_exists('mb_internal_encoding') &&
           ((int) ini_get('mbstring.func_overload')) & 2) {

            $mbIntEnc = mb_internal_encoding();
            mb_internal_encoding('ASCII');
        }

        while (trim($body)) {
            if (! preg_match("/^([\da-fA-F]+)[^\r\n]*\r\n/sm", $body, $m)) {

                throw new Zend_Http_Exception("Error parsing body - doesn't seem to be a chunked message");
            }

            $length = hexdec(trim($m[1]));
            $cut = strlen($m[0]);
            $decBody .= substr($body, $cut, $length);
            $body = substr($body, $cut + $length + 2);
        }

        if (isset($mbIntEnc)) {
            mb_internal_encoding($mbIntEnc);
        }

        return $decBody;
    }
645469
public static function decodeUnicode($text)
    {
        if (preg_match('/^\xFE\xFF/i', $text)) {
            // Strip U+FEFF byte order marker.
            $decode = substr($text, 2);
            $text   = '';
            $length = strlen($decode);

            for ($i = 0; $i < $length; $i += 2) {
                $text .= self::uchr(hexdec(bin2hex(substr($decode, $i, 2))));
            }
        }

        return $text;
    }
913513
private function decodeDeflate($fromFilename, $toFilename)
    {
        if (!function_exists('gzuncompress')) {
            throw new UserMessageException(t(/*i18n: %s is a compression method, like gzip*/'The PHP zlib extension is required in order to decode "%s" encodings.', 'deflate'));
        }
        $compressed = @file_get_contents($fromFilename);
        if ($compressed === false) {
            throw new UserMessageException(t('Failed to read the file to be decoded with inflate.'));
        }
        $isGZip = false;
        if (isset($compressed[1])) {
            $zlibHeader = unpack('n', substr($compressed, 0, 2));
            if ($zlibHeader[1] % 31 === 0) {
                $isGZip = true;
            }
        }
        if ($isGZip) {
            $decompressed = @gzuncompress($compressed);
            if ($decompressed === false) {
                throw new UserMessageException(t('Failed to decode the ZLIB compressed data.'));
            }
        } else {
            $decompressed = @gzinflate($compressed);
            if ($decompressed === false) {
                throw new UserMessageException(t('Failed to inflate the deflated data.'));
            }
        }
        if (@file_put_contents($toFilename, $decompressed) === false) {
            throw new UserMessageException(t('Failed to decompress  the file to be decoded with inflate.'));
        }
        throw new UserMessageException(t('Failed to write the deflated data.'));
    }
1037352
public function decompress($buffer)
    {
        $decodeBook = $this->getDecodeBook();
        $output     = '';
        $i          = 0;

        while ($i < strlen($buffer)) {
            $code = ord($buffer[$i]);

            if ($code == 254) {
                $output .= $buffer[$i + 1];
                $i      += 2;

            } else if($code == 255) {
                $len     = ord($buffer[$i + 1]);
                $output .= substr($buffer, $i + 2, $len);
                $i      += 2 + $len;

            } else {
                $output .= $decodeBook[$code];
                $i++;
            }
        }

        return $output;
    }
890385
def decode_response(response):
    
    def is_compressed(headers):
        encoding = headers.get('content-encoding', [])
        return encoding and encoding[0] in ('gzip', 'deflate')

    def decompress_body(body, encoding):
        """Returns decompressed body according to encoding using zlib.
        to (de-)compress gzip format, use wbits = zlib.MAX_WBITS | 16
        """
        if encoding == 'gzip':
            return zlib.decompress(body, zlib.MAX_WBITS | 16)
        else:  # encoding == 'deflate'
            return zlib.decompress(body)

    # Deepcopy here in case `headers` contain objects that could
    # be mutated by a shallow copy and corrupt the real response.
    response = copy.deepcopy(response)
    headers = CaseInsensitiveDict(response['headers'])
    if is_compressed(headers):
        encoding = headers['content-encoding'][0]
        headers['content-encoding'].remove(encoding)
        if not headers['content-encoding']:
            del headers['content-encoding']

        new_body = decompress_body(response['body']['string'], encoding)
        response['body']['string'] = new_body
        headers['content-length'] = [str(len(new_body))]
        response['headers'] = dict(headers)
    return response
313226
private static function jsonDecode(string $body)
    {
        $content = json_decode($body, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            $msg = json_last_error_msg();

            throw new DecodingFailedException(
                'Failed to decode the json response body.'.($msg ? " {$msg}." : '')
            );
        }

        if (!is_array($content)) {
            throw new DecodingFailedException(
                'Failed to decode the json response body. Expected to decode to an array.'
            );
        }

        return $content;
    }