Decode a message header value

@param string  $input    Header value
@param string  $fallback Fallback charset if none specified

@return string Decoded string
348390
public static function decode_header($input, $fallback = null)
    {
        $str = self::decode_mime_string((string)$input, $fallback);

        return $str;
    }
577448
function decodeStream( $request, $stream, $headers=false, $cookies=array(), $statuscode="200" )
    {
        $this->decodeStreamCommon( $request, $stream, $headers, $cookies, $statuscode );

        $contentType = $this->ContentType;
        $charset = $this->Charset;

        // allow request to force an expected response type
        // this is useful if servers do respond with eg. text/plain content-header for json or xml
        if ( ( $forcedType = $request->responseType() ) != '' )
        {
            list ( $contentType, $charset2 ) = $this->parseContentTypeHeader( $forcedType );
            $this->ContentType = $contentType . '; received="' . $this->ContentType . '"';
            if ( $charset2 != '' )
            {
                $charset = $charset2;
                $this->Charset = $charset . '; received="' . $this->Charset . '"';
            }
        }

        // Allow empty payloads regardless of declared content type, for 204 and 205 responses
        if ( $statuscode == '204' || $statuscode == '205' )
        {
            if ( $stream == '' && ( !isset( $headers['content-length'] ) || $headers['content-length'] == 0 ) )
            {
                $this->Value = null;
                return;
            }
            else
            {
                /// @todo this is not valid according to rfc 2616 - but we should leave that control to client really
                $this->IsFault = true;
                $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . " (received http response 204/205 with a body. Not valid http)";
            }
        }

        /// @todo take into account charset when decoding json / xml

        switch( $this->mimeTypeToEncodeType( $contentType ) )
        {
            case 'json':
            case 'application/json':
                $val = json_decode( $stream, true );
                if ( function_exists( 'json_last_error' ) )
                {
                    $err = json_last_error();
                }
                else
                {
                    $err = ( $val === null ) ? 1 : false;
                }
                if ( $err )
                {
                    $this->IsFault = true;
                    $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                    $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . ' json. Decoding error: ' . $err;
                }
                else
                {
                    $this->Value = $val;
                }
                break;
            case 'xml':
            case 'text/xml':
            case 'application/xml':
                try
                {
                    $doc = new DOMDocument();
                    $prev = libxml_use_internal_errors( true );
                    libxml_clear_errors();
                    $doc->loadXML( $stream );
                    $node = $doc->documentElement;
                    if ( $node == null )
                    {
                        $errors = libxml_get_errors();
                        libxml_use_internal_errors( $prev );
                        $errorText = '';
                        foreach( $errors as $error)
                        {
                            if ( $error->level > LIBXML_ERR_WARNING )
                            {
                                $errorText .= trim ( $error->message ) . ", line: $error->line" . " column: $error->column\n";
                            }
                        }
                        throw new Exception( $errorText );
                    }
                    libxml_use_internal_errors( $prev );
                    $this->Value = new ggSimpleTemplateXML( $node );

                }
                catch ( Exception $e )
                {
                    $this->IsFault = true;
                    $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                    $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . ' xml. ' . $e->getMessage();
                }
                break;
            case 'text/plain':
            case 'text/html':
                $this->Value = $stream;
                break;
            default:
                $this->IsFault = true;
                $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . " (unsupported format $contentType)";
        }
    }
716608
static function convert($input,$outputFormat=self::PHP) {
		if ($input===false) {
			$input=time();
		}

		if ($input instanceof \DateTime) {
			if ($outputFormat===self::INT) return $input->getTimestamp();
			if (is_string($outputFormat)) return date($outputFormat,$input->getTimestamp());
			if ($outputFormat===self::PHP) return $input;
			return null;
		}

		if (!is_numeric($input)) {
			$origInput = $input;
			$input=@strtotime($input);
			if ($input === false or $input === -1) {
				$input = str_replace(" ","",$origInput); // Helps with formats like 13. 5. 2013
				$input=@strtotime($input);
				if ($input === false or $input === -1) {
					throw new \InvalidArgumentException("Invalid input to Time::convert: $origInput");
				}
			}
		}

		if ($outputFormat===self::INT) return $input;
		if (is_string($outputFormat)) return date($outputFormat,$input);
		if ($outputFormat===self::PHP) {
			$d=new \DateTime();
			return $d->setTimestamp($input);
		}
		return null;
	}
336153
public static function jsonEncode($input)
    {
        $json = json_encode($input);

        if ($json === 'null' && $input !== null) {
            throw new DomainException('Null result with non-null input');
        }

        return $json;
    }
388774
public function send_timing_header( $input ) {

		if ( headers_sent() ) {
			return $input;
		}

		$ajax = defined( 'DOING_AJAX' ) && DOING_AJAX;
		$rest = defined( 'REST_REQUEST' ) && REST_REQUEST;

		if ( ! $ajax && ! $rest ) {
			return $input;
		}

		// This will be false in REST API w/o nonce, even with valid cookie. Might make sense to filter to true in dev.
		if ( ! apply_filters( 'laps_can_see', current_user_can( 'manage_options' ) ) ) {
			return $input;
		}

		$header  = '';

		/** @var Record_Interface $record */
		foreach ( $this->collector->get_records() as $record ) {
			$duration = $record->get_duration() * 1000;

			if ( $duration < 1 ) {
				continue;
			}

			$header .= sprintf( '%s;dur=%.2f;desc="%s", ', $record->get_category(), $duration, $record->get_name() );
		}

		header( 'Server-Timing: ' . preg_replace( '/\R/', '', $header ) );

		return $input;
	}
220702
protected function decodeData(Buffer $input)
    {
        $firstByte = $input[0];
        $output = new Buffer;

        if ($firstByte <= 0x7f) {
            return [
                'data' => $input->slice(0, 1),
                'remainder' => $input->slice(1)
            ];
        } elseif ($firstByte <= 0xb7) {
            $length = $firstByte - 0x7f;
            $data = new Buffer([]);

            if ($firstByte !== 0x80) {
                // for ($i = 1; $i < $length; $i++) {
                //     $data[] = $input[$i];
                // }
                $data = $input->slice(1, $length);
            }
            if ($length === 2 && $data[0] < 0x80) {
                throw new RuntimeException('Byte must be less than 0x80.');
            }
            return [
                'data' => $data,
                'remainder' => $input->slice($length)
            ];
        } elseif ($firstByte <= 0xbf) {
            $llength = $firstByte - 0xb6;
            $hexLength = $input->slice(1, $llength)->toString('hex');

            if ($hexLength === '00') {
                throw new RuntimeException('Invalid RLP.');
            }
            $length = hexdec($hexLength);
            $data = $input->slice($llength, $length + $llength);

            if ($data->length() < $length) {
                throw new RuntimeException('Invalid RLP.');
            }
            return [
                'data' => $data,
                'remainder' => $input->slice($length + $llength)
            ];
        } elseif ($firstByte <= 0xf7) {
            $length = $firstByte - 0xbf;
            $innerRemainder = $input->slice(1, $length);
            $decoded = [];

            while ($innerRemainder->length()) {
                $data = $this->decodeData($innerRemainder);
                $decoded[] = $data['data'];
                $innerRemainder = $data['remainder'];
            }
            return [
                'data' => $decoded,
                'remainder' => $input->slice($length)
            ];
        } else {
            $llength = $firstByte - 0xf6;
            $hexLength = $input->slice(1, $llength)->toString('hex');
            $decoded = [];

            if ($hexLength === '00') {
                throw new RuntimeException('Invalid RLP.');
            }
            $length = hexdec($hexLength);
            $totalLength = $llength + $length;

            if ($totalLength > $input->length()) {
                throw new RuntimeException('Invalid RLP: total length is bigger than data length.');
            }
            $innerRemainder = $input->slice($llength, $totalLength);

            if ($innerRemainder->length() === 0) {
                throw new RuntimeException('Invalid RLP: list has invalid length.');
            }

            while ($innerRemainder->length()) {
                $data = $this->decodeData($innerRemainder);
                $decoded[] = $data['data'];
                $innerRemainder = $data['remainder'];
            }
            return [
                'data' => $decoded,
                'remainder' => $input->slice($length)
            ];
        }
    }
1347008
protected function readOption(string $key, $fallback = null)
    {
        $value = get_option($this->prefix . $key, $fallback ?? false);
        if (false === $value) {
            return $fallback;
        }

        return $value;
    }
5462
public function parse($input)
    {
        if (strlen($input) == 0) {
            return null;
        }
        return $this->parser->parse(new TokenStream($this->tokenizer->getTokens($input)));
    }
1278464
public function decrypt($input)
    {
        // Decode the IV + data
        $input = base64_decode($input);
        // Remove the IV
        $iv = substr($input, 0, Cipher::IV_SIZE);
        // Return Decrypted Data
        return openssl_decrypt(substr($input, Cipher::IV_SIZE), "AES-256-CBC", $this->secretKey, 0, $iv);
    }
688249
public function decode(string $input, int $maxSize) { /* : ?array */
        $headers = [];
        $off = 0;
        $inputLength = \strlen($input);
        $size = 0;

        // dynamic $table as per 2.3.2
        while ($off < $inputLength) {
            $index = \ord($input[$off++]);

            if ($index & 0x80) {
                // range check
                if ($index <= self::LAST_INDEX + 0x80) {
                    if ($index === 0x80) {
                        return null;
                    }

                    list($name, $value) = $headers[] = self::TABLE[$index - 0x81];
                } else {
                    if ($index == 0xff) {
                        $index = self::decodeDynamicInteger($input, $off) + 0xff;
                    }

                    $index -= 0x81 + self::LAST_INDEX;
                    if (!isset($this->headers[$index])) {
                        return null;
                    }

                    list($name, $value) = $headers[] = $this->headers[$index];
                }
            } elseif (($index & 0x60) !== 0x20) { // (($index & 0x40) || !($index & 0x20)): bit 4: never index is ignored
                $dynamic = (bool) ($index & 0x40);

                if ($index & ($dynamic ? 0x3f : 0x0f)) { // separate length
                    if ($dynamic) {
                        if ($index === 0x7f) {
                            $index = self::decodeDynamicInteger($input, $off) + 0x3f;
                        } else {
                            $index &= 0x3f;
                        }
                    } else {
                        $index &= 0x0f;
                        if ($index === 0x0f) {
                            $index = self::decodeDynamicInteger($input, $off) + 0x0f;
                        }
                    }

                    if ($index <= self::LAST_INDEX) {
                        $header = self::TABLE[$index - 1];
                    } else {
                        $header = $this->headers[$index - 1 - self::LAST_INDEX];
                    }
                } else {
                    $len = \ord($input[$off++]);
                    $huffman = $len & 0x80;
                    $len &= 0x7f;

                    if ($len === 0x7f) {
                        $len = self::decodeDynamicInteger($input, $off) + 0x7f;
                    }

                    if ($inputLength - $off < $len || $len <= 0) {
                        return null;
                    }

                    if ($huffman) {
                        $header = [self::huffmanDecode(\substr($input, $off, $len))];
                    } else {
                        $header = [\substr($input, $off, $len)];
                    }

                    $off += $len;
                }

                if ($off === $inputLength) {
                    return null;
                }

                $len = \ord($input[$off++]);
                $huffman = $len & 0x80;
                $len &= 0x7f;

                if ($len === 0x7f) {
                    $len = self::decodeDynamicInteger($input, $off) + 0x7f;
                }

                if ($inputLength - $off < $len || $len < 0) {
                    return null;
                }

                if ($huffman) {
                    $header[1] = self::huffmanDecode(\substr($input, $off, $len));
                } else {
                    $header[1] = \substr($input, $off, $len);
                }

                $off += $len;

                if ($dynamic) {
                    \array_unshift($this->headers, $header);
                    $this->size += 32 + \strlen($header[0]) + \strlen($header[1]);
                    if ($this->maxSize < $this->size) {
                        $this->resizeTable();
                    }
                }

                list($name, $value) = $headers[] = $header;
            } else { // if ($index & 0x20) {
                if ($index === 0x3f) {
                    $index = self::decodeDynamicInteger($input, $off) + 0x40;
                }

                if ($index > 4096) { // initial limit … may be adjusted??
                    return null;
                }

                $name = $value = '';
                $this->resizeTable($index);
            }

            $size += \strlen($name) + \strlen($value);

            if ($size > $maxSize) {
                return null;
            }
        }

        return $headers;
    }
618336
public function decode($input)
    {
        // Don't use UCS-2.
        $output = [];
        $inputLength = strlen($input);
        $i = 0;
        $n = self::INITIAL_N;
        $bias = self::INITIAL_BIAS;

        // Handle the basic code points: let `basic` be the number of input code
        // points before the last delimiter, or `0` if there is none, then copy
        // the first basic code points to the output.

        $basic = strrpos($input, self::DELIMITER);
        if ($basic === false ) {
            $basic = 0;
        }

        for ($j = 0; $j < $basic; ++$j) {
            // if it's not a basic code point
            if ( ord($input[$j]) >= 0x80) {
                $this->error('not-basic');
            }
            $output[] = ord($input[$j]);
        }

        // Main decoding loop: start just after the last delimiter if any basic code
        // points were copied; start at the beginning otherwise.

        for ( $index = $basic > 0 ? $basic + 1 : 0; $index < $inputLength; /* no final expression */) {

            // `index` is the index of the next character to be consumed.
            // Decode a generalized variable-$length integer into `delta`,
            // which gets added to `i`. The overflow checking is easier
            // if we increase `i` as we go, then subtract off its starting
            // value at the end to obtain `delta`.
            $oldi = $i;
            for ( $w = 1, $k = self::BASE; /* no condition */; $k += self::BASE) {

                if ($index >= $inputLength) {
                    $this->error('invalid-input');
                }

                $digit = $this->basicToDigit(ord($input[$index++]));

                if ($digit >= self::BASE || $digit > floor((self::MAX_INT - $i) / $w)) {
                    $this->error('overflow');
                }

                $i += $digit * $w;
                $t = $k <= $bias ? self::T_MIN : ($k >= $bias + self::T_MAX ? self::T_MAX : $k - $bias);

                if ($digit < $t) {
                    break;
                }

                $baseMinusT = self::BASE - $t;
                if ($w > floor(self::MAX_INT / $baseMinusT)) {
                    $this->error('overflow');
                }

                $w *= $baseMinusT;

            }

            $out = count($output) + 1;
            $bias = $this->adapt($i - $oldi, $out, $oldi == 0);

            // `i` was supposed to wrap around from `out` to `0`,
            // incrementing `n` each time, so we'll fix that now:
            if (floor($i / $out) > self::MAX_INT - $n) {
                $this->error('overflow');
            }

            $n += floor($i / $out);
            $i %= $out;

            // Insert `n` at position `i` of the output.
            array_splice($output, $i++, 0, $n);
        }

        return mb_convert_encoding($this->ucs2Encode($output), "UTF-8", "UTF-16");
    }
845932
public static function safe_base64_decode($input) {
    $remainder = strlen($input) % 4;
    if ($remainder) {
      $padlen = 4 - $remainder;
      $input .= str_repeat('=', $padlen);
    }
    return base64_decode(strtr($input, '-_', '+/'));
  }
62007
public static function urlsafeB64Decode(string $input): string
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $padlen = 4 - $remainder;
            $input .= str_repeat('=', $padlen);
        }

        return base64_decode(strtr($input, '-_', '+/'));
    }
100292
protected function parse($input): string
    {
        if (!is_array($input)) {
            return json_encode($input);
        }

        $parsed = "";
        foreach ($input as $key => $value) {
            $key = (!is_numeric($key) ? ($key . ": " ) : '');
            if (!is_array($value)) {
                $parsed .= $key . $this->parse($value) . ', ';
            } elseif (is_null(key($value)) || is_numeric(key($value))) {
                $parsed .= $key . "[" . $this->parse($value) . "], ";
            } else {
                $parsed .= $key . "{" . $this->parse($value) . "}, ";
            }
        }

        return rtrim($parsed, ', ');
    }
1141646
public static function decode($input, $secret = null) {
        // no input?
        if(!$input)
            return false;

        // decode
        $decoded = self::base64decode($input);
        if(!$decoded)
            return false;

        // output
        return self::xor($decoded, self::secret($secret));
    }
1317404
public static function convert($input = STDIN)
    {
        $stream = fopen('php://temp', 'rw');

        foreach ($_SERVER as $key => $value) {
            if (0 === strpos($key, 'HTTP_')) {
                $key = str_replace('_', '-', strtolower(substr($key, 5)));
                fwrite($stream, "$key: $value\r\n");
            } elseif (in_array($key, ['CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'])) {
                $key = str_replace('_', '-', strtolower($key));
                fwrite($stream, "$key: $value\r\n");
            }
        }

        fwrite($stream, "\r\n");

        stream_copy_to_stream($input, $stream);

        rewind($stream);

        return new StreamedPart($stream);
    }
484405
public function jsonp($input, $callback)
    {
        return $this
            ->withHeader('Content-Type', 'application/javascript')
            ->write(sprintf('%s(%s);', $callback, json_encode($input)));
    }