Parses the `HTTP_ACCEPT` information the requesting client sends, and converts
that data to an array for consumption by the rest of the framework.

@return array All the types of content the client can accept.
337411
protected function _parseAccept() {
		$accept = $this->env('HTTP_ACCEPT');
		$accept = (preg_match('/[a-z,-]/i', $accept)) ? explode(',', $accept) : ['text/html'];

		foreach (array_reverse($accept) as $i => $type) {
			unset($accept[$i]);
			list($type, $q) = (explode(';q=', $type, 2) + [$type, 1.0 + $i / 100]);
			$accept[$type] = ($type === '*/*') ? 0.1 : floatval($q);
		}
		arsort($accept, SORT_NUMERIC);

		if (isset($accept['application/xhtml+xml']) && $accept['application/xhtml+xml'] >= 1) {
			unset($accept['application/xml']);
		}
		$media = $this->_classes['media'];

		if (isset($this->params['type']) && ($handler = $media::type($this->params['type']))) {
			if (isset($handler['content'])) {
				$type = (array) $handler['content'];
				$accept = [current($type) => 1] + $accept;
			}
		}
		return array_keys($accept);
	}
171505
protected function readFromHttpData()
    {
        // Check validity of the uploaded files
        $aTempFiles = [];
        foreach($_FILES as $sVarName => $aFile)
        {
            if(is_array($aFile['name']))
            {
                $nFileCount = count($aFile['name']);
                for($i = 0; $i < $nFileCount; $i++)
                {
                    if(!$aFile['name'][$i])
                    {
                        continue;
                    }
                    if(!array_key_exists($sVarName, $aTempFiles))
                    {
                        $aTempFiles[$sVarName] = [];
                    }
                    // Filename without the extension
                    $sFilename = $this->filterFilename(pathinfo($aFile['name'][$i], PATHINFO_FILENAME), $sVarName);
                    // Copy the file data into the local array
                    $aTempFiles[$sVarName][] = [
                        'name' => $aFile['name'][$i],
                        'type' => $aFile['type'][$i],
                        'tmp_name' => $aFile['tmp_name'][$i],
                        'error' => $aFile['error'][$i],
                        'size' => $aFile['size'][$i],
                        'filename' => $sFilename,
                        'extension' => pathinfo($aFile['name'][$i], PATHINFO_EXTENSION),
                    ];
                }
            }
            else
            {
                if(!$aFile['name'])
                {
                    continue;
                }
                if(!array_key_exists($sVarName, $aTempFiles))
                {
                    $aTempFiles[$sVarName] = [];
                }
                // Filename without the extension
                $sFilename = $this->filterFilename(pathinfo($aFile['name'], PATHINFO_FILENAME), $sVarName);
                // Copy the file data into the local array
                $aTempFiles[$sVarName][] = [
                    'name' => $aFile['name'],
                    'type' => $aFile['type'],
                    'tmp_name' => $aFile['tmp_name'],
                    'error' => $aFile['error'],
                    'size' => $aFile['size'],
                    'filename' => $sFilename,
                    'extension' => pathinfo($aFile['name'], PATHINFO_EXTENSION),
                ];
            }
        }

        // Check uploaded files validity
        foreach($aTempFiles as $sVarName => $aFiles)
        {
            foreach($aFiles as $aFile)
            {
                // Verify upload result
                if($aFile['error'] != 0)
                {
                    throw new \Jaxon\Exception\Error($this->trans('errors.upload.failed', $aFile));
                }
                // Verify file validity (format, size)
                if(!$this->validateUploadedFile($sVarName, $aFile))
                {
                    throw new \Jaxon\Exception\Error($this->getValidatorMessage());
                }
                // Get the path to the upload dir
                $this->getUploadDir($sVarName);
            }
        }

        // Copy the uploaded files from the temp dir to the user dir
        foreach($aTempFiles as $sVarName => $aTempFiles)
        {
            $this->aUserFiles[$sVarName] = [];
            foreach($aTempFiles as $aFile)
            {
                // Get the path to the upload dir
                $sUploadDir = $this->getUploadDir($sVarName);
                // Set the user file data
                $xUploadedFile = UploadedFile::fromHttpData($sUploadDir, $aFile);
                // All's right, move the file to the user dir.
                move_uploaded_file($aFile["tmp_name"], $xUploadedFile->path());
                $this->aUserFiles[$sVarName][] = $xUploadedFile;
            }
        }
    }
610075
public function getRequestHeaders()
    {
        $headers = array();

        foreach ($this->data->getAll() as $key => $value) {
            if ('HTTP_' === substr($key, 0, 5)) {
                $headers[substr($key, 5)] = $value;
            }
        }

        return $headers;
    }
1142314
protected function httpProcessHeaders()
    {
        $this->state = self::STATE_PREHANDSHAKE;
        if (isset($this->server['HTTP_SEC_WEBSOCKET_EXTENSIONS'])) {
            $str = strtolower($this->server['HTTP_SEC_WEBSOCKET_EXTENSIONS']);
            $str = preg_replace($this->extensionsCleanRegex, '', $str);
            $this->extensions = explode(', ', $str);
        }
        if (!isset($this->server['HTTP_CONNECTION'])
            || (!preg_match('~(?:^|\W)Upgrade(?:\W|$)~i',
                $this->server['HTTP_CONNECTION'])) // "Upgrade" is not always alone (ie. "Connection: Keep-alive, Upgrade")
            || !isset($this->server['HTTP_UPGRADE'])
            || (strtolower($this->server['HTTP_UPGRADE']) !== 'websocket') // Lowercase comparison iss important
        ) {
            $this->finish();
            return false;
        }
        if (isset($this->server['HTTP_COOKIE'])) {
            Generic::parseStr(strtr($this->server['HTTP_COOKIE'], Generic::$hvaltr), $this->cookie);
        }
        if (isset($this->server['QUERY_STRING'])) {
            Generic::parseStr($this->server['QUERY_STRING'], $this->get);
        }
        // ----------------------------------------------------------
        // Protocol discovery, based on HTTP headers...
        // ----------------------------------------------------------
        if (isset($this->server['HTTP_SEC_WEBSOCKET_VERSION'])) { // HYBI
            if ($this->server['HTTP_SEC_WEBSOCKET_VERSION'] === '8') { // Version 8 (FF7, Chrome14)
                $this->switchToProtocol('V13');
            } elseif ($this->server['HTTP_SEC_WEBSOCKET_VERSION'] === '13') { // newest protocol
                $this->switchToProtocol('V13');
            } else {
                Daemon::$process->log(get_class($this) . '::' . __METHOD__ . " : Websocket protocol version " . $this->server['HTTP_SEC_WEBSOCKET_VERSION'] . ' is not yet supported for client "' . $this->addr . '"');
                $this->finish();
                return false;
            }
        } elseif (!isset($this->server['HTTP_SEC_WEBSOCKET_KEY1']) || !isset($this->server['HTTP_SEC_WEBSOCKET_KEY2'])) {
            $this->switchToProtocol('VE');
        } else { // Defaulting to HIXIE (Safari5 and many non-browser clients...)
            $this->switchToProtocol('V0');
        }
        // ----------------------------------------------------------
        // End of protocol discovery
        // ----------------------------------------------------------
        return true;
    }
628944
public function getRequestHeaders(): array
    {
        $headers = clone $this->headers();

        if (!$headers->headerExists('Content-type')) {
            if ($contentType = $this->getContentType()) {
                if (($charset = $this->getCharset()) && (stripos($contentType, 'charset=') === false)) {
                    $contentType .= "; charset={$charset}";
                }

                $headers->setHeader('Content-type', $contentType);
            }
        }

        return $headers->getHeadersForRequest();
    }
63763
public function type()
    {
        $accept = $this->server('HTTP_ACCEPT');
        if (empty($accept)) {
            return false;
        }

        foreach ($this->mimeType as $key => $val) {
            $array = explode(',', $val);
            foreach ($array as $k => $v) {
                if (stristr($accept, $v)) {
                    return $key;
                }
            }
        }
        return false;
    }
1276295
protected function parse_request() {
        // Retrieve and clean the POST/GET parameters from the parameters specific to the server.
        parent::set_web_service_call_settings();

        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
            $this->username = isset($_GET['wsusername']) ? $_GET['wsusername'] : null;
            $this->password = isset($_GET['wspassword']) ? $_GET['wspassword'] : null;
        } else {
            $this->token = isset($_GET['wstoken']) ? $_GET['wstoken'] : null;
        }

        // Get the XML-RPC request data.
        $rawpostdata = $this->fetch_input_content();
        $methodname = null;

        // Decode the request to get the decoded parameters and the name of the method to be called.
        $decodedparams = xmlrpc_decode_request($rawpostdata, $methodname, 'UTF-8');
        $methodinfo = external_api::external_function_info($methodname);
        $methodparams = array_keys($methodinfo->parameters_desc->keys);
        $methodvariables = [];

        // Add the decoded parameters to the methodvariables array.
        if (is_array($decodedparams)) {
            foreach ($decodedparams as $index => $param) {
                // See MDL-53962 - XML-RPC requests will usually be sent as an array (as in, one with indicies).
                // We need to use a bit of "magic" to add the correct index back. Zend used to do this for us.
                $methodvariables[$methodparams[$index]] = $param;
            }
        }

        $this->functionname = $methodname;
        $this->parameters = $methodvariables;
    }
181906
private function getClientBrowserAccepted()
    {
        $this->autoPopulateSuperGlobals();
        $sReturn = [
            'accept'          => $this->brServerGlobals->server->get('HTTP_ACCEPT'),
            'accept_encoding' => $this->brServerGlobals->server->get('HTTP_ACCEPT_ENCODING'),
        ];
        if (!is_null($this->brServerGlobals->server->get('HTTP_ACCEPT_LANGUAGE'))) {
            $sReturn['accept_language']     = $this->brServerGlobals->server->get('HTTP_ACCEPT_LANGUAGE');
            $prfd                           = null;
            preg_match_all('/([a-z]{2})(?:-[a-zA-Z]{2})?/', $sReturn['accept_language'], $prfd);
            $sReturn['preferred locale']    = $prfd[0];
            $sReturn['preferred languages'] = array_values(array_unique(array_values($prfd[1])));
        }
        return $sReturn;
    }
1077042
public function getAcceptedEncodings()
    {
        if (null === $this->encodings) {
            if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
                $this->encodings = strtolower(trim($_SERVER['HTTP_ACCEPT_ENCODING']));
            } else {
                $this->encodings = '';
            }
        }

        return $this->encodings;
    }
241438
public static function acceptJson()
    {
        $accept = self::getService('HTTP_ACCEPT');
        if (false !== strpos($accept, 'json') || false !== strpos($accept, 'javascript')) {
            return true;
        }
        return false;
    }
250016
protected function parseParams()
    {
        if (!isset($this->attrs->server['HTTP_CONTENT_LENGTH'])) {
            $this->attrs->contentLength = 0;
        } else {
            $this->attrs->contentLength = (int)$this->attrs->server['HTTP_CONTENT_LENGTH'];
        }

        if (isset($this->attrs->server['CONTENT_TYPE']) && !isset($this->attrs->server['HTTP_CONTENT_TYPE'])) {
            $this->attrs->server['HTTP_CONTENT_TYPE'] = $this->attrs->server['CONTENT_TYPE'];
        }

        if (isset($this->attrs->server['QUERY_STRING'])) {
            self::parseStr($this->attrs->server['QUERY_STRING'], $this->attrs->get);
        }
        if (isset($this->attrs->server['REQUEST_METHOD'])
            && ($this->attrs->server['REQUEST_METHOD'] === 'POST' || $this->attrs->server['REQUEST_METHOD'] === 'PUT')
            && isset($this->attrs->server['HTTP_CONTENT_TYPE'])
        ) {
            $this->attrs->server['REQUEST_METHOD_POST'] = true;
            self::parseStr($this->attrs->server['HTTP_CONTENT_TYPE'], $this->contype, true);
            $found = false;
            foreach ($this->contype as $k => $v) {
                if (mb_orig_strpos($k, '/') === false) {
                    continue;
                }
                if (!$found) {
                    $found = true;
                } else {
                    unset($this->contype[$k]);
                }
            }

            if (isset($this->contype['multipart/form-data'])
                && (isset($this->contype['boundary']))
            ) {
                $this->attrs->input->setBoundary($this->contype['boundary']);
            }
        } else {
            $this->attrs->server['REQUEST_METHOD_POST'] = false;
        }

        if (isset($this->attrs->server['HTTP_COOKIE'])) {
            self::parseStr($this->attrs->server['HTTP_COOKIE'], $this->attrs->cookie, true);
        }

        if (isset($this->attrs->server['HTTP_AUTHORIZATION'])) {
            $e = explode(' ', $this->attrs->server['HTTP_AUTHORIZATION'], 2);

            if (($e[0] === 'Basic') && isset($e[1])) {
                $e[1] = base64_decode($e[1]);
                $e = explode(':', $e[1], 2);

                if (isset($e[1])) {
                    list($this->attrs->server['PHP_AUTH_USER'], $this->attrs->server['PHP_AUTH_PW']) = $e;
                }
            }
        }

        $this->onParsedParams();
    }
1243029
private function ParseDataFromPhpInput() {
        if (file_get_contents('php://input') == "") {
            return array();
        }
        $jsonDecodedData = json_decode(file_get_contents('php://input'));
        if (is_null($jsonDecodedData)) {
            return array();
        }
        $postData = get_object_vars($jsonDecodedData);
        if (empty($postData)) {
            return array();
        }
        return $postData;
    }
299049
protected static function _parseAccept($accept, array $defaults = null)
    {
        if (! empty($accept)) {
            // Get all of the types
            $types = explode(',', $accept);

            foreach ($types as $type) {
                // Split the type into parts
                $parts = explode(';', $type);

                // Make the type only the MIME
                $type = trim(array_shift($parts));

                // Default quality is 1.0
                $options = array('quality' => 1.0);

                foreach ($parts as $part) {
                    // Prevent undefined $value notice below
                    if (strpos($part, '=') === false) {
                        continue;
                    }

                    // Separate the key and value
                    list($key, $value) = explode('=', trim($part));

                    switch ($key) {
                        case 'q':
                            $options['quality'] = (float) trim($value);
                            break;
                        case 'version':
                            $options['version'] = (float) trim($value);
                            break;
                    }
                }

                // Add the accept type and quality
                $defaults[$type] = $options;
            }
        }

        // Make sure that accepts is an array
        $accepts = (array) $defaults;

        // Order by quality
        arsort($accepts);

        return $accepts;
    }
1198094
public function dumpRequest(): array
    {
        if (empty($this->request)) {
            return ['http_status' => $this->httpStatus, 'response' => $this->data];
        }
        $this->request->getBody()->rewind();
        # rewind the request
        $size = $this->request->getBody()->getSize() ?: 1024;
        # get the size, we need it to be able to read through; else we assume 1024
        $bodyParams = json_decode($this->request->getBody()->read($size), true);
        # the body parameters
        $possibleJsonString = (string) $this->request->getBody();
        # cast it to a string
        $jsonData = json_decode($possibleJsonString);
        $uri = $this->request->getUri();
        $url = $uri->getScheme() . '://' . $uri->getAuthority() . '/' . $uri->getPath();
        return [
            'http_status' => $this->httpStatus,
            'endpoint' => $url,
            'params'   => $bodyParams,
            'response' => $jsonData ?: $possibleJsonString
        ];
    }
1243782
private function parseProxy()
    {
        if($this->request->getAttribute('useProxy', false))
        {
            $type = $this->request->getAttribute('proxy.type', 'http');
            curl_setopt_array($this->handler, array(
                CURLOPT_PROXYAUTH    => self::$proxyAuths[$this->request->getAttribute('proxy.auth', 'basic')],
                CURLOPT_PROXY        => $this->request->getAttribute('proxy.server'),
                CURLOPT_PROXYPORT    => $this->request->getAttribute('proxy.port'),
                CURLOPT_PROXYUSERPWD => $this->request->getAttribute('proxy.username', '') . ':' . $this->request->getAttribute('proxy.password', ''),
                CURLOPT_PROXYTYPE    => 'socks5' === $type ? (defined('CURLPROXY_SOCKS5_HOSTNAME') ? CURLPROXY_SOCKS5_HOSTNAME : self::$proxyType[$type]) : self::$proxyType[$type],
            ));
        }
    }
485209
protected function parseRequest()
    {
        if ($this->customParams === false) {
            // pull various supported inputs from post
            $request = $this->di->get('request');

            // only process if it is a get
            if ($request->isGet() == false) {
                return;
            }
        } else {
            $_REQUEST = $_GET = $this->customParams;
            $request = $this->di->get('request');
        }

        // simple stuff first
        $with = $request->get('with', "string", null);
        $include = $request->get('include', "string", null);
        if (!is_null($with)) {
            $this->suppliedWith = $with;
        } elseif (!is_null($include)) {
            $this->suppliedWith = $include;
        }

        // load possible sort values in the following order
        // be sure to mark this as a paginated result set
        if ($request->get('sort', "string", null) != null) {
            $this->suppliedSort = $request->get('sort', "string", null);
            $this->isPager = true;
        } elseif ($request->get('sort_field', "string", null) != null) {
            $this->suppliedSort = $request->get('sort_field', "string", null);
            $this->isPager = true;
        } elseif ($request->get('sortField', "string", null) != null) {
            $this->suppliedSort = $request->get('sortField', "string", null);
            $this->isPager = true;
        }

        // prep for the harder stuff
        // ?page=1&perPage=25&orderAscending=false

        // load possible limit values in the following order
        // be sure to mark this as a paginated result set
        if ($request->get('limit', "string", null) != null) {
            $this->suppliedLimit = $request->get('limit', "string", null);
            $this->isPager = true;
        } elseif ($request->get('per_page', "string", null) != null) {
            $this->suppliedLimit = $request->get('per_page', "string", null);
            $this->isPager = true;
        } elseif ($request->get('perPage', "string", null) != null) {
            $this->suppliedLimit = $request->get('perPage', "string", null);
            $this->isPager = true;
        }

        // look for string that means to show all records
        if ($this->isPager) {
            if ($this->suppliedLimit == 'all') {
                $this->suppliedLimit = 9999999999;
            }
        }

        // load offset values in the following order
        // Notice that a page is treated differently than offset
        // $this->offset = ($offset != null) ? $offset : $this->offset;
        if ($request->get('offset', "int", null) != null) {
            $this->suppliedOffset = $request->get('offset', "int", null);
            $this->isPager = true;
        } elseif ($request->get('page', "int", null) != null) {
            $this->suppliedOffset = ($request->get('page', "int", null) - 1) * $this->suppliedLimit;
            $this->isPager = true;
        }

        // Check if we pass the count parameter with whatever value
        if ($request->has('count')) {
            $this->isCount = true;
        }

        // http://jsonapi.org/format/#fetching
        $this->parseSearchParameters($request);
    }
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;
    }