Decode a string that is encoded w. "chunked" transfer encoding
as defined in rfc2068 par. 19.4.6
Code shamelessly stolen from nusoap library by Dietrich Ayala

@param string $buffer the string to be decoded
@return string
352512
protected static function decode_chunked( $buffer )
    {
        $length = 0;
        $new = '';

        // read chunk-size, chunk-extension (if any) and crlf
        // get the position of the linebreak
        $chunkend = strpos($buffer,"\r\n") + 2;
        $temp = substr($buffer,0,$chunkend);
        $chunk_size = hexdec( trim($temp) );
        $chunkstart = $chunkend;
        while($chunk_size > 0)
        {
            $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size);

            // just in case we got a broken connection
            if($chunkend == false)
            {
                $chunk = substr($buffer,$chunkstart);
                // append chunk-data to entity-body
                $new .= $chunk;
                $length += strlen($chunk);
                break;
            }

            // read chunk-data and crlf
            $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
            // append chunk-data to entity-body
            $new .= $chunk;
            // length := length + chunk-size
            $length += strlen($chunk);
            // read chunk-size and crlf
            $chunkstart = $chunkend + 2;

            $chunkend = strpos($buffer,"\r\n",$chunkstart)+2;
            if($chunkend == false)
            {
                break; //just in case we got a broken connection
            }
            $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
            $chunk_size = hexdec( trim($temp) );
            $chunkstart = $chunkend;
        }
        return $new;
    }
712711
function decode($text)
    {
        $pad = ord(substr($text, -1));
        if ($pad < 1 || $pad > PKCS7Encoder::$blockSize) {
            $pad = 0;
        }
        return substr($text, 0, strlen($text) - $pad);
    }
611086
public static function softDecode($string) {
		/*
		$data = htmlspecialchars_decode($string);
		$data= html_entity_decode($string);
		$data = ereg_replace("&quot;", chr(34),$data);
		$data = ereg_replace("&lt;", chr(60),$data);
		$data = ereg_replace("&gt;", chr(62),$data);
		$data = ereg_replace("&amp;", chr(38),$data);
		$data = ereg_replace("&nbsp;", chr(32),$data);
		$data = ereg_replace("&amp;nbsp;", "",$data);
		$data= html_entity_decode($data);
		*/

		$data = get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES);
		$data = array_flip($data);
		$original = strtr($string, $data);

		return $original;
	}
32534
private function decodeBody(array $headers, $body)
    {
        $headers = array_change_key_case($headers);

        if (isset($headers['transfer-encoding']) && $headers['transfer-encoding'] === 'chunked') {
            for ($decodedBody = ''; !empty($body); $body = trim($body)) {
                $pos = strpos($body, "\r\n");
                $length = hexdec(substr($body, 0, $pos));
                $decodedBody .= substr($body, $pos + 2, $length);
                $body = substr($body, $pos + $length + 2);
            }

            return $decodedBody;
        }

        return $body;
    }
649748
function decode(buffer, encoding) {
		validateEncoding(encoding);
		if (encoding === null || encoding === 'buffer') return [buffer, new Buffer(0)];
		var decoder = new StringDecoder(encoding);
		var str = decoder.write(buffer);
		var leftover = decoder.charBuffer.slice(0, decoder.charReceived);
		return [str, leftover];
	}
1254526
public function handleQueryFromStream(string $buffer): string
    {
        $message = Decoder::decodeMessage($buffer);
        $this->dispatch(Events::QUERY_RECEIVE, new QueryReceiveEvent($message));

        $responseMessage = clone $message;
        $responseMessage->getHeader()
            ->setResponse(true)
            ->setRecursionAvailable($this->resolver->allowsRecursion())
            ->setAuthoritative($this->isAuthoritative($message->getQuestions()));

        try {
            $answers = $this->resolver->getAnswer($responseMessage->getQuestions());
            $responseMessage->setAnswers($answers);
            $this->needsAdditionalRecords($responseMessage);
            $this->dispatch(Events::QUERY_RESPONSE, new QueryResponseEvent($responseMessage));

            return Encoder::encodeMessage($responseMessage);
        } catch (UnsupportedTypeException $e) {
            $responseMessage
                    ->setAnswers([])
                    ->getHeader()->setRcode(Header::RCODE_NOT_IMPLEMENTED);
            $this->dispatch(Events::QUERY_RESPONSE, new QueryResponseEvent($responseMessage));

            return Encoder::encodeMessage($responseMessage);
        }
    }
334742
public static function input($buffer)
    {
        if (strlen($buffer) < self::HEAD_LEN) {
            return 0;
        }
        $data = unpack("Npack_len", $buffer);
        return $data['pack_len'];
    }
439301
protected function decode($string)
    {
        // decode if specified
        if (($pos = strpos($string, ':')) !== false) {
            if (!strncmp($string, 'base64', 6)) {
                return base64_decode(substr($string, 7));
            } elseif (!strncmp($string, 'urlencode', 9)) {
                return urldecode(substr($string, 10));
            }
        }

        return $string;
    }
906695
public function decrypt($payload)
    {
        $payload = $this->getJsonPayload($payload);

        // We'll go ahead and remove the PKCS7 padding from the encrypted value before
        // we decrypt it. Once we have the de-padded value, we will grab the vector
        // and decrypt the data, passing back the unserialized from of the value.
        $value = base64_decode($payload['value']);

        $iv = base64_decode($payload['iv']);

        return unserialize($this->stripPadding($this->mcryptDecrypt($value, $iv)));
    }
629615
public function chunkMe($string)
    {
        if ($this->useChunks === true && strlen($string) > 10000) {
            // Get the key.
            $key = $this->genKey();
            // Detect the encoding in the chunk.
            $this->detectEncoding($string);
            // Write the key to the chunks folder.
            $this->pool->fileService->putFileContents($this->chunkDir . $key . '.Krexx.tmp', $string);
            // Return the first part plus the key.
            return static::STRING_DELIMITER . $key . static::STRING_DELIMITER;
        }

        // Return the original, because it's too small.
        return $string;
    }
319734
function parseFrame(&$buffer)
    {
        //$this->log("PaserFrame. BufferLen=".strlen($buffer));
        //websocket
        $ws  = array();
        $ws['finish'] = false;

        $data_offset = 0;

        //fin:1 rsv1:1 rsv2:1 rsv3:1 opcode:4
        $handle        = ord($buffer[$data_offset]);
        $ws['fin']    = ($handle >> 7) & 0x1;
        $ws['rsv1']   = ($handle >> 6) & 0x1;
        $ws['rsv2']   = ($handle >> 5) & 0x1;
        $ws['rsv3']   = ($handle >> 4) & 0x1;
        $ws['opcode'] =  $handle       & 0xf;
        $data_offset ++;

        //mask:1 length:7
        $handle        = ord($buffer[$data_offset]);
        $ws['mask']    = ($handle >> 7) & 0x1;
        //0-125
        $ws['length']  =  $handle       & 0x7f;
        $length        =  &$ws['length'];
        $data_offset ++;

        //126 short
        if($length == 0x7e)
        {
            //2
            $handle = unpack('nl', substr($buffer, $data_offset, 2));
            $data_offset += 2;
            $length = $handle['l'];
        }
        //127 int64
        elseif($length > 0x7e)
        {
            //8
            $handle = unpack('N*l', substr($buffer, $data_offset, 8));
            $data_offset += 8;
            $length = $handle['l'];

            //超过最大允许的长度了
            if ($length > $this->max_frame_size)
            {
                $this->log('Message is too long.');
                return false;
            }
        }

        //mask-key: int32
        if (0x0 !== $ws['mask'])
        {
            $ws['mask'] = array_map('ord', str_split(substr($buffer, $data_offset, 4)));
            $data_offset += 4;
        }

        //把头去掉
        $buffer = substr($buffer, $data_offset);

        //数据长度为0的帧
        if (0 === $length)
        {
            $ws['finish'] = true;
            $ws['message'] = '';
            return $ws;
        }

        //完整的一个数据帧
        if (strlen($buffer) >= $length)
        {
            $ws['finish'] = true;
            $ws['data'] =  substr($buffer, 0, $length);
            $ws['message'] = $this->parseMessage($ws);
            //截取数据
            $buffer = substr($buffer, $length);
            return $ws;
        }
        //需要继续等待数据
        else
        {
            $ws['finish'] = false;
            $ws['data'] = $buffer;
            $buffer = "";
            return $ws;
        }
    }
925302
public function compress($buffer)
    {
        $dictionary = array();
        $data       = str_split($buffer . '');
        $out        = array();
        $phrase     = $data[0];
        $code       = 256;
        $countData  = count($data);

        for ($i = 1; $i < $countData; ++$i) {
            $currentCharacter = $data[$i];

            if (isset($dictionary[$phrase.$currentCharacter])) {
                $phrase .= $currentCharacter;

            } else {
                $out[] = strlen($phrase) > 1 ? $dictionary[$phrase] : $this->charCodeAt($phrase,0);
                $dictionary[$phrase.$currentCharacter] = $code;
                $code++;
                $phrase = $currentCharacter;
            }
        }

        $out[]    = strlen($phrase) > 1 ? $dictionary[$phrase] : $this->charCodeAt($phrase,0);
        $countOut = count($out);

        for ($i = 0; $i < $countOut; ++$i) {
            $out[$i] = $this->unichr($out[$i]);
        }

        return implode('', $out);
    }
462911
public static function decode($string)
    {
        if (is_array($string)) {
            foreach ($string as $k => $substring) {
                $string[$k] = static::decode($substring);
            }
        } else {
            $string = urldecode($string);
        }

        return $string;
    }
787348
static public String decodeString(final ByteBuffer bb) {
        final int strlength = bb.getInt();
        final int position = bb.position();
        String decoded = new String(bb.array(), bb.arrayOffset() + position, strlength, Charsets.UTF_8);
        bb.position(position + strlength);
        return decoded;
    }
1166559
public static function decode($bytes, $connection)
    {
        $data_length = ord($bytes[1]);

        if ($data_length === 126) {
            $decoded_data = substr($bytes, 4);
        } else if ($data_length === 127) {
            $decoded_data = substr($bytes, 10);
        } else {
            $decoded_data = substr($bytes, 2);
        }
        if ($connection->websocketCurrentFrameLength) {
            $connection->websocketDataBuffer .= $decoded_data;
            return $connection->websocketDataBuffer;
        } else {
            if ($connection->websocketDataBuffer !== '') {
                $decoded_data                    = $connection->websocketDataBuffer . $decoded_data;
                $connection->websocketDataBuffer = '';
            }
            return $decoded_data;
        }
    }
299527
public function decode( string$encoded )
	{
		$data= [];

		foreach( explode( '&', $encoded ) as $value )
		{
			$key= urldecode( strtok( $value, '=' ) );
			$value= urldecode( strtok( '' ) );

			$keys= explode( '[', str_replace( ']', '', $key ) );

			$p= &$data;

			foreach( $keys as $key )
			{
				is_array( $p ) or $p= [];

				$p= &$p[$key];
			}

			$p= $value;

			unset( $p );
		}

		return $data;
	}
643296
protected function decodeSingleHeader($input)
    {
        // For each encoded-word...
        while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)((\s+)=\?)?/i', $input, $matches)) {
            $encoded = $matches[1];
            $charset = $matches[2];
            $encoding = $matches[3];
            $text = $matches[4];
            $space = isset($matches[6]) ? $matches[6] : '';

            switch (strtolower($encoding)) {
                case 'b':
                    $text = $this->decodeContentTransfer($text, 'base64');
                    break;

                case 'q':
                    $text = str_replace('_', ' ', $text);
                    preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);
                    foreach ($matches[1] as $value) {
                        $text = str_replace('='.$value, chr(hexdec($value)), $text);
                    }
                    break;
            }

            $text = $this->charset->decodeCharset($text, $this->charset->getCharsetAlias($charset));
            $input = str_replace($encoded.$space, $text, $input);
        }

        return $input;
    }