Get accepted content mimetypes from request header
@param  str   $acceptString
@return str[]
330365
private function getAcceptArrayFromEnvironment($acceptString)
    {
        $accept = $acceptArray = array();
        foreach (explode(',', strtolower($acceptString)) as $part) {
            $parts = preg_split('/\s*;\s*q=/', $part);
            if (isset($parts) && isset($parts[1]) && $parts[1]) {
                $num = $parts[1] * 10;
            } else {
                $num = 10;
            }
            if ($parts[0]) {
                $accept[$num][] = $parts[0];
            }
        }
        krsort($accept);
        foreach ($accept as $parts) {
            foreach ($parts as $part) {
                $acceptArray[] = trim($part);
            }
        }

        return $acceptArray;
    }
1001437
public function getAcceptedTypes()
    {
        return $this->getCachedProperty(
            'accept',
            function () {
                $result = [];
                /** @var \DOMNodeList $nodes */
                // No REQUIRED — no exception.
                $nodes = $this->query('app:accept');
                foreach ($nodes as $value) {
                    $result[] = trim($value->textContent);
                }

                return $result;
            }
        );
    }
288211
private function parseHeader($header)
    {
        $res = preg_match_all('/(?:[^,"]*+(?:"[^"]*+")?)+[^,"]*+/', $header, $matches);

        if (!$res) {
            throw new InvalidHeader(sprintf('Failed to parse accept header: "%s"', $header));
        }

        return array_values(array_filter(array_map('trim', $matches[0])));
    }
75478
protected function parseRuleString($ruleString)
    {
        if (is_string($ruleString)) {
            // Parse for @charset rule
            if (preg_match('/^@charset\s+(["\'])([-a-zA-Z0-9_]+)\g{1}/i', rtrim($ruleString), $matches)) {
                $this->setValue($matches[2]);
            } else {
                throw new \InvalidArgumentException("Invalid format for @charset rule.");
            }
        } else {
            throw new \InvalidArgumentException(
                "Invalid type '" . gettype($ruleString) . "' for argument 'ruleString' given. String expected."
            );
        }
    }
23537
public function loadString(&$string): array
    {
        /** @noinspection CallableParameterUseCaseInTypeContextInspection */
        $string = $this->unwrap($string);
        $this->rawSegments = $string;

        return $this->parse($string);
    }
11082
public static function parseAccept(string $accept)
    {
        $result = [];

        foreach (explode(',', $accept) as $directive) {
            $parts = explode(';', $directive, 2);

            $type = trim($parts[0]);

            $priority = ((float) filter_var(
                $parts[1] ?? 1,
                FILTER_SANITIZE_NUMBER_FLOAT,
                FILTER_FLAG_ALLOW_FRACTION
            ));
            $priority = Utils::numberLimit($priority, 0, 1);

            if (strpos($type, '*') !== false) {
                $priority -= 0.0001;
            }
            $result[$type] = $priority;
        }

        return $result;
    }
302392
protected function _inspectContentType()
    {
        $mime = null;
        $charset = null;
        if (preg_match('/([-\w\/\.+]+)(;\s*?charset=(.+))?/i', $this->_headers['Content-Type']->value(), $matches)) {
            $mime = $mime ?: $matches[1];
            if (isset($matches[3])) {
                $charset = $charset ?: $matches[3];
            }
        }
        return [$mime, $charset];
    }
556109
public function findMatch(AcceptHeader $acceptedMimeTypes)
    {
        if (count($this->mimeTypes) === 0) {
            return 'text/html';
        }

        if (count($acceptedMimeTypes) === 0) {
            reset($this->mimeTypes);
            return current($this->mimeTypes);
        }

        return $acceptedMimeTypes->findMatchWithGreatestPriority($this->mimeTypes);
    }
94086
private static function getParametersFromContentType(string $contentType): array
    {
        $parameters = array_merge(
            self::getParametersFromGlobal($_GET),
            self::getParametersFromGlobal($_POST),
            self::getParametersFromGlobal($_FILES));
        $paramsSource = [];
        $rawInput = file_get_contents('php://input');
        switch ($contentType) {
            case ContentType::JSON:
                $paramsSource = (array) json_decode($rawInput);
                break;
            case ContentType::XML:
            case ContentType::XML_APP:
                $xml = new \SimpleXMLElement($rawInput);
                $paramsSource = (array) $xml;
                break;
            default:
                parse_str($rawInput, $paramsSource);
        }
        return array_merge($parameters, self::getParametersFromGlobal($paramsSource));
    }
527430
protected function parseRuleString($ruleString)
    {
        if (is_string($ruleString)) {
            // Check for valid rule format
            // (with vendor prefix check to match e.g. "@-moz-document")
            if (preg_match(
                '/^[ \r\n\t\f]*@(' . self::getVendorPrefixRegExp("/") . ')?document[ \r\n\t\f]+(.*)$/i',
                $ruleString,
                $matches
            )) {
                $vendorPrefix = $matches[1];
                $ruleString = trim($matches[2], " \r\n\t\f");
                $charset = $this->getCharset();

                $inFunction = false;
                $isEscaped = false;

                $conditions = [];
                $currentCondition = "";
                $currentValue  = "";
                for ($i = 0, $j = mb_strlen($ruleString, $charset); $i < $j; $i++) {
                    $char = mb_substr($ruleString, $i, 1, $charset);
                    if ($char === "\\") {
                        if ($isEscaped === false) {
                            $isEscaped = true;
                        } else {
                            $isEscaped = false;
                        }
                    } else {
                        if ($char === "(") {
                            if ($isEscaped === false) {
                                $inFunction = true;
                                continue;
                            } else {
                                $currentValue .= $char;
                            }
                        } else if ($char === ")") {
                            if ($isEscaped === false) {
                                $conditions[$currentCondition] = trim($currentValue, " \r\n\t\f");
                                $currentCondition = "";
                                $currentValue = "";
                                $inFunction = false;
                                continue;
                            } else {
                                $currentValue .= $char;
                            }
                        } else if ($char === "," || $char === " ") {
                            if ($currentCondition === "" && $currentValue === "") {
                                continue;
                            } elseif ($currentValue !== "") {
                                $currentValue .= $char;
                            } else {
                                // something wrong here...
                            }
                        } else {
                            if ($inFunction === false) {
                                $currentCondition .= $char;
                            } else {
                                $currentValue .= $char;
                            }
                        }
                    }

                    // Reset escaped flag
                    if ($isEscaped === true && $char !== "\\") {
                        $isEscaped = false;
                    }
                }

                foreach ($conditions as $key => $value) {
                    $conditions[$key] = Placeholder::replaceStringPlaceholders($value, true);
                }

                if (isset($conditions["url"])) {
                    $this->setUrl($conditions["url"]);
                }
                if (isset($conditions["url-prefix"])) {
                    $this->setUrlPrefix($conditions["url-prefix"]);
                }
                if (isset($conditions["domain"])) {
                    $this->setDomain($conditions["domain"]);
                }
                if (isset($conditions["regexp"])) {
                    $this->setRegexp($conditions["regexp"]);
                }
                if ($vendorPrefix !== "") {
                    $this->setVendorPrefix($vendorPrefix);
                }
            } else {
                throw new \InvalidArgumentException("Invalid format for @document rule.");
            }
        } else {
            throw new \InvalidArgumentException(
                "Invalid type '" . gettype($ruleString) . "' for argument 'ruleString' given. String expected."
            );
        }
    }
1159796
protected function parseRuleString($ruleString)
    {
        $charset = $this->getCharset();

        // Remove at-rule and unnecessary white-spaces
        $ruleString = preg_replace('/^[ \r\n\t\f]*@import[ \r\n\t\f]+/i', '', $ruleString);
        $ruleString = trim($ruleString, " \r\n\t\f");

        // Remove trailing semicolon
        $ruleString = rtrim($ruleString, ";");

        $isEscaped  = false;
        $inFunction = false;

        $url = "";
        $mediaQuery = "";
        $currentPart  = "";
        for ($i = 0, $j = mb_strlen($ruleString, $charset); $i < $j; $i++) {
            $char = mb_substr($ruleString, $i, 1, $charset);
            if ($char === "\\") {
                if ($isEscaped === false) {
                    $isEscaped = true;
                } else {
                    $isEscaped = false;
                }
            } else {
                if ($char === " ") {
                    if ($isEscaped === false) {
                        if ($inFunction == false) {
                            $currentPart = trim($currentPart, " \r\n\t\f");
                            if ($currentPart !== "") {
                                if ($url === "") {
                                    $url = trim($currentPart, " \r\n\t\f");
                                } else {
                                    $mediaQuery .= trim($currentPart, " \r\n\t\f");
                                    $mediaQuery .= $char;
                                }
                                $currentPart = "";
                            }
                        }
                    } else {
                        $currentPart .= $char;
                    }
                } elseif ($isEscaped === false && $char === "(") {
                    $inFunction = true;
                    $currentPart .= $char;
                } elseif ($isEscaped === false && $char === ")") {
                    $inFunction = false;
                    $currentPart .= $char;
                } else {
                    $currentPart .= $char;
                }
            }

            // Reset escaped flag
            if ($isEscaped === true && $char !== "\\") {
                $isEscaped = false;
            }
        }
        if ($currentPart !== "") {
            $currentPart = trim($currentPart, " \r\n\t\f");
            if ($currentPart !== "") {
                if ($url === "") {
                    $url = trim($currentPart, " \r\n\t\f");
                } else {
                    $mediaQuery .= trim($currentPart, " \r\n\t\f");
                }
            }
        }

        // Get URL value
        $url = Url::extractUrl($url);
        $this->setUrl($url);

        // Process media query
        $mediaRule = new MediaRule($mediaQuery);
        $this->setQueries($mediaRule->getQueries());
    }
505998
public static function get_headers(): array
	{
		if (function_exists('apache_request_headers')) {
			// we need this to get the actual Authorization: header
			// because apache tends to tell us it doesn't exist
			$headers = apache_request_headers();

			// sanitize the output of apache_request_headers because
			// we always want the keys to be Cased-Like-This and arh()
			// returns the headers in the same case as they are in the
			// request
			$out = [];
			foreach ($headers as $key => $value) {
				$key = str_replace(
					' ',
					'-',
					ucwords(strtolower(str_replace('-', ' ', $key)))
				);
				$out[$key] = $value;
			}
		} else {
			// otherwise we don't have apache and are just going to have to hope
			// that $_SERVER actually contains what we need
			$out = [];
			if (isset($_SERVER['CONTENT_TYPE'])) {
				$out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
			}
			if (isset($_ENV['CONTENT_TYPE'])) {
				$out['Content-Type'] = $_ENV['CONTENT_TYPE'];
			}

			foreach ($_SERVER as $key => $value) {
				if (substr($key, 0, 5) == 'HTTP_') {
					// this is chaos, basically it is just there to capitalize the first
					// letter of every word that is not an initial HTTP and strip HTTP
					// code from przemek
					$key = str_replace(
						' ',
						'-',
						ucwords(strtolower(str_replace('_', ' ', substr($key, 5))))
					);
					$out[$key] = $value;
				}
			}
		}
		return $out;
	}
1218196
def _get_acceptable_response_type():
    """"""
    if ('Accept' not in request.headers or request.headers['Accept'] in
            ALL_CONTENT_TYPES):
        return JSON
    acceptable_content_types = set(
        request.headers['ACCEPT'].strip().split(','))
    if acceptable_content_types & HTML_CONTENT_TYPES:
        return HTML
    elif acceptable_content_types & JSON_CONTENT_TYPES:
        return JSON
    else:
        # HTTP 406 Not Acceptable
        raise InvalidAPIUsage(406)
590941
protected function mime_in_header($mime, $accept_header)
	{
		// make sure we have input
		if (empty($mime) or empty($accept_header))
		{
			// no header or no mime to check
			return true;
		}

		// process the accept header and get a list of accepted mimes
		$accept_mimes = array();
		$accept_header = explode(',', $accept_header);
		foreach ($accept_header as $accept_def)
		{
			$accept_def = explode(';', $accept_def);
			$accept_def = trim($accept_def[0]);
			if ( ! in_array($accept_def, $accept_mimes))
			{
				$accept_mimes[] = $accept_def;
			}
		}

		// match on generic mime type
		if (in_array('*/*', $accept_mimes))
		{
			return true;
		}

		// match on full mime type
		if (in_array($mime, $accept_mimes))
		{
			return true;
		}

		// match on generic mime type
		$mime = substr($mime, 0, strpos($mime, '/')).'/*';
		if (in_array($mime, $accept_mimes))
		{
			return true;
		}

		// no match
		return false;
	}
589725
public function getFromClient() {
		$returner = [];

		// Example string
		// en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2

		if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
			$parts = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);

			foreach ($parts as $part) {
				preg_match("|^
					(.*?)		# the language part
					([-].*?)?	# the country part (optional)
					(;q=(.*))?	# the quality part (optional)
				$|x", $part, $matches);

				// set quality to 1.0 if not given
				$quality	= isset($matches[4]) ? $matches[4] : '1.0';

				$returner[$quality] = strtolower(trim($matches[1]));
			}
			krsort($returner);
		}
		return $returner;
	}
1078993
protected function getRequestHeaders($sendData = false)
    {
        $headers = [
            'Accept'     => 'application/json',
            'User-Agent' => $this->options->userAgent() . '/' . Client::VERSION,
        ];

        if ($sendData) {
            $headers['Content-Type'] = 'application/json;charset=utf-8';
        }

        return $headers;
    }
1284182
public function getSupportedMimes()
    {
        if ($this->mimes) {
            return $this->mimes;
        }

        $response = $this->get(
            'mime-types',
            $this->getGuzzleOptions([
                'headers' => [
                    'Accept' => 'application/json',
                ],
            ])
        );

        return $this->mimes = Convert::json2array($response->getBody());
    }