Takes a curl result and generates a Response from it
@return Response
556754
public function buildResponse($result) {
        if ($result === false) {
            if ($curlErrorNumber = curl_errno($this->_ch)) {
                $curlErrorString = curl_error($this->_ch);
                $this->_error($curlErrorString);

                $exception = new ConnectionErrorException('Unable to connect to "'.$this->uri.'": '
                        . $curlErrorNumber . ' ' . $curlErrorString);

                $exception->setCurlErrorNumber($curlErrorNumber)
                    ->setCurlErrorString($curlErrorString);

                throw $exception;
            }

            $this->_error('Unable to connect to "'.$this->uri.'".');
            throw new ConnectionErrorException('Unable to connect to "'.$this->uri.'".');
        }

        $info = curl_getinfo($this->_ch);

        // Remove the "HTTP/1.x 200 Connection established" string and any other headers added by proxy
        $proxy_regex = "/HTTP\/1\.[01] 200 Connection established.*?\r\n\r\n/si";
        if ($this->hasProxy() && preg_match($proxy_regex, $result)) {
            $result = preg_replace($proxy_regex, '', $result);
        }

        $response = explode("\r\n\r\n", $result, 2 + $info['redirect_count']);

        $body = array_pop($response);
        $headers = array_pop($response);

        return new Response($body, $headers, $this, $info);
    }
1060258
public function exec(): Response
    {
        $url = $this->getUrl();

        $ch = curl_init($url);

        foreach ($this->getCurlOptions() as $option => $value) {
            // iterating it so we have all options applied in given order
            curl_setopt($ch, $option, $value);
        }

        $body = curl_exec($ch);

        if (curl_errno($ch)) {
            throw new HttpException(curl_error($ch));
        }

        return new Response($ch, $body, $this);
    }
789781
public function generateResponse(){
        // Create request
        $this->startTimeline("request.create");

        $request    = $this->container->get("app.request")
            ->withAttribute("app.debug", $this->debug)
        ;

        $this->endTimeline("request.create");

        // Create response
        $this->startTimeline("response.create");

        $response   = $this->container->newInstance(Response::class, [
            "handler"   => $this->generateHandler($request),
        ]);

        $this->endTimeline("response.create");

        return $response;
    }
365877
public function createResponse()
    {
        $response = $this->format();
        $response->headers->set('content-type', $this->getContentType());
        $response->setStatusCode($this->getStatusCode());
        $response->setCharset('UTF-8');

        return $response;
    }
716421
public function getResult()
    {
        $result = curl_getinfo($this->resource);

        if (curl_errno($this->resource)) {
            $result['error'] = curl_error($this->resource);
        }

        return [
            'url' => isset($result['url']) ? $result['url'] : null,
            'statusCode' => isset($result['http_code']) ? $result['http_code'] : null,
            'contentType' => isset($result['content_type']) ? $result['content_type'] : null,
            'info' => $result,
            'content' => $this->body,
            'headers' => $this->headers,
            'data' => $this->data,
        ];
    }
1359384
public function respond()
    {
        // Make sure there always is a response
        if (null === $this->result)
        {
            $this->result = new Result;
            $this->result->setResponse(new Error(500, "No output produced"));
        }
        
        // Close and log all script output that hasn't been cleaned yet
        $this->endAllOutputBuffers($this->target_ob_level);

        // Add Content-Type mime header
        $response = $this->result->getResponse();
        $mime = $response->getMimeTypes();
        if (empty($mime))
        {
            $mime = Request::cli() ? "text/plain" : "text/html";
        }
        elseif (is_array($mime))
        {
            $types = $mime;
            $mime = null;
            foreach ($types as $type)
            {
                if ($this->request->accepts($type))
                {
                    $mime = $type;
                    break;
                }
            }
        }

        // If mime is not accepted, return a 406 response
        if (empty($mime) || !$this->request->accepts($mime))
        {
            $mime = 'text/html';
            $this->result->setResponse(new Error(406, "Not Acceptable", 'No acceptable response can be offered'));
        }

        // Execute hooks
        $hook_params = [
            'responder' => $this,
            'request' => $this->request,
            'mime' => $mime,
        ];

        $hook_params = Hook::execute('Wedeto.HTTP.Responder.Respond', $hook_params);

        // Check if mime type was updated
        if (is_string($hook_params['mime']))
            $mime_charset = $hook_params['mime'];

        $mime_charset = $mime;
        $tp = new FileType('', $mime);
        if ($tp->isPlainText())
            $mime_charset .= '; charset=utf-8';

        // Set mime type
        $this->setHeader('Content-Type', $mime_charset);

        // Add headers from response to the final response
        foreach ($this->result->getAllHeaders() as $key => $value)
            $this->setHeader($key, $value);

        // Store the response code
        $this->setResponseCode($response->getStatusCode());

        // All preparational work is done, time to send stuff to the client
        $this->doOutput($mime);
    }
397047
public function processResponse($curlResponse, $curlInfo, $curlError)
    {
        // print "\n" . $curlResponse;
        switch ($curlInfo['http_code']) {
            case '200':
                $responseObject = $this->_XML2Array($curlResponse);
                $ver = "Ver1.0";
                return $responseObject->$ver;
                break;
            case '500':
                $faultString = $this->_XMLFault2String($curlResponse);
                throw new HpsException($faultString);
                break;
            default:
                throw new HpsException('Unexpected response');
                break;
        }
    }
763798
protected function createCurl() {
        $ch = curl_init();

        // Add the body first so we can calculate a content length.
        $body = '';
        if ($this->method === self::METHOD_HEAD) {
            curl_setopt($ch, CURLOPT_NOBODY, true);
        } elseif ($this->method !== self::METHOD_GET) {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method);

            $body = $this->makeCurlBody();
            if ($body) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
            }
        }

        // Decode the headers.
        $headers = [];
        foreach ($this->getHeaders() as $key => $values) {
            foreach ($values as $line) {
                $headers[] = "$key: $line";
            }
        }

        if (is_string($body) && !$this->hasHeader('Content-Length')) {
            $headers[] = 'Content-Length: '.strlen($body);
        }

        if (!$this->hasHeader('Expect')) {
            $headers[] = 'Expect:';
        }

        curl_setopt(
            $ch,
            CURLOPT_HTTP_VERSION,
            $this->getProtocolVersion() == '1.0' ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1
        );

        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->getTimeout());
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verifyPeer);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this->verifyPeer ? 2 : 0);
        curl_setopt($ch, CURLOPT_ENCODING, ''); //"utf-8");
        curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);

        if (!empty($this->auth)) {
            curl_setopt($ch, CURLOPT_USERPWD, $this->auth[0].":".((empty($this->auth[1])) ? "" : $this->auth[1]));
        }

        return $ch;
    }
1350061
public function request()
    {
        $data = $this->prepareData();

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->apiHost . '/api');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
        $this->checkResult($result);

        return $result;
    }
561498
protected function curl_execute()
    {
        $ch = curl_init();

        curl_setopt_array($ch, $this->getOptions());

        $this->_content = curl_exec($ch);

        $this->_errorCode = curl_errno($ch);

        $this->_info = curl_getinfo($ch);

        if ($this->_errorCode) {
            $this->_errorMessage = curl_error($ch);
        }
        curl_close($ch);
        return $this->isHttpOK();
    }
336264
public function fromCurl ($response, $curl)
		{
			$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
			$this->_body = substr($response, $headerSize);

			$headers = substr($response, 0, $headerSize);
			$headers = str_replace("\r", "", $headers);
			$headers = str_replace("\n\n", "\n", $headers);
			$headers = trim($headers, "\n");
			$this->_headers = explode("\n", $headers);

			return $this;
		}
758145
public function getResponse()
    {
        $curl = curl_init();

        $this->addParameters()->addHeaders();
        $this->options[CURLOPT_RETURNTRANSFER] = true;
        curl_setopt_array($curl, $this->options);

        $response = curl_exec($curl);

        $this->meta = array(
            'info'             => curl_getinfo($curl, CURLINFO_HTTP_CODE),
            'error_message'    => curl_errno($curl),
            'error_code'    => curl_error($curl));

        curl_close($curl);
        unset($curl);

        return $response;
    }
925059
public function getResponse()
    {
        $this->execute();
        
        switch ($this->def['dataType']) {
            case 'array':
                $result = static::toArray();
                break;
            case 'object':
            case 'json':
                $result = static::toJson();
                break;
            default:
                $result = $this->getErrorString() ? : $this->responseText;
        }
        
        return $result;
    }
603769
public function call()
    {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $this->getApiUrl().'?'.http_build_query($this->getOptions()),
            CURLOPT_HEADER         => 0,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => $this->timeout,
        ]);
        $this->response = curl_exec($ch);
        curl_close($ch);

        return $this;
    }
503619
public function parse(CurlResponse $curlResponse)
    {
        $responseBody = $curlResponse->getBody();

        $contentType = $curlResponse->info()->getContentType();
        $responseType = $this->getResponseType($contentType);
        $responseCharset = $this->getResponseCharset($contentType);

        $httpCode = $curlResponse->info()->getHttpCode();
        $httpMessage = $this->responseCodes->getMessage($httpCode);

        return new Response($responseBody, $responseType, $responseCharset, $httpCode, $httpMessage);
    }
188267
public function generateResponse()
    {
        $data = $this->getData();

        if ($data instanceof \Closure) {
            $data = $data();
        }

        $encoders = [new XmlEncoder(), new JsonEncoder()];
        $normalizers = [new GetSetMethodNormalizer()];
        $serializer = new Serializer($normalizers, $encoders);

        $response = new Response();
        $response->headers->set('Content-Type', 'application/'.$this->getFormat());
        $response->setContent($serializer->serialize($data, $this->getFormat()));

        return $response;
    }
850411
public function getResponse()
	{
		$query = '';
		if (sizeof($this->parameters) > 0)
		{
			$query = substr($this->uri, -1) !== '?' ? '?' : '&';
			foreach ($this->parameters as $var => $value)
				if ($value == null || $value == '') $query .= $var.'&';
				else $query .= $var.'='.rawurlencode($value).'&';
			$query = substr($query, 0, -1);
			$this->uri .= $query;

			if (array_key_exists('acl', $this->parameters) ||
			array_key_exists('location', $this->parameters) ||
			array_key_exists('torrent', $this->parameters) ||
			array_key_exists('website', $this->parameters) ||
			array_key_exists('logging', $this->parameters))
				$this->resource .= $query;
		}
		$url = (S3::$useSSL ? 'https://' : 'http://') . ($this->headers['Host'] !== '' ? $this->headers['Host'] : $this->endpoint) . $this->uri;

		//var_dump('bucket: ' . $this->bucket, 'uri: ' . $this->uri, 'resource: ' . $this->resource, 'url: ' . $url);

		// Basic setup
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');

		if (S3::$useSSL)
		{
			// Set protocol version
			curl_setopt($curl, CURLOPT_SSLVERSION, S3::$useSSLVersion);

			// SSL Validation can now be optional for those with broken OpenSSL installations
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, S3::$useSSLValidation ? 2 : 0);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, S3::$useSSLValidation ? 1 : 0);

			if (S3::$sslKey !== null) curl_setopt($curl, CURLOPT_SSLKEY, S3::$sslKey);
			if (S3::$sslCert !== null) curl_setopt($curl, CURLOPT_SSLCERT, S3::$sslCert);
			if (S3::$sslCACert !== null) curl_setopt($curl, CURLOPT_CAINFO, S3::$sslCACert);
		}

		curl_setopt($curl, CURLOPT_URL, $url);

		if (S3::$proxy != null && isset(S3::$proxy['host']))
		{
			curl_setopt($curl, CURLOPT_PROXY, S3::$proxy['host']);
			curl_setopt($curl, CURLOPT_PROXYTYPE, S3::$proxy['type']);
			if (isset(S3::$proxy['user'], S3::$proxy['pass']) && S3::$proxy['user'] != null && S3::$proxy['pass'] != null)
				curl_setopt($curl, CURLOPT_PROXYUSERPWD, sprintf('%s:%s', S3::$proxy['user'], S3::$proxy['pass']));
		}

		// Headers
		$headers = array(); $amz = array();
		foreach ($this->amzHeaders as $header => $value)
			if (strlen($value) > 0) $headers[] = $header.': '.$value;
		foreach ($this->headers as $header => $value)
			if (strlen($value) > 0) $headers[] = $header.': '.$value;

		// Collect AMZ headers for signature
		foreach ($this->amzHeaders as $header => $value)
			if (strlen($value) > 0) $amz[] = strtolower($header).':'.$value;

		// AMZ headers must be sorted
		if (sizeof($amz) > 0)
		{
			//sort($amz);
			usort($amz, array(&$this, '__sortMetaHeadersCmp'));
			$amz = "\n".implode("\n", $amz);
		} else $amz = '';

		if (S3::hasAuth())
		{
			// Authorization string (CloudFront stringToSign should only contain a date)
			if ($this->headers['Host'] == 'cloudfront.amazonaws.com')
				$headers[] = 'Authorization: ' . S3::__getSignature($this->headers['Date']);
			else
			{
				$headers[] = 'Authorization: ' . S3::__getSignature(
					$this->verb."\n".
					$this->headers['Content-MD5']."\n".
					$this->headers['Content-Type']."\n".
					$this->headers['Date'].$amz."\n".
					$this->resource
				);
			}
		}

		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
		curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
		curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

		// Request types
		switch ($this->verb)
		{
			case 'GET': break;
			case 'PUT': case 'POST': // POST only used for CloudFront
				if ($this->fp !== false)
				{
					curl_setopt($curl, CURLOPT_PUT, true);
					curl_setopt($curl, CURLOPT_INFILE, $this->fp);
					if ($this->size >= 0)
						curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
				}
				elseif ($this->data !== false)
				{
					curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
					curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
				}
				else
					curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
			break;
			case 'HEAD':
				curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
				curl_setopt($curl, CURLOPT_NOBODY, true);
			break;
			case 'DELETE':
				curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
			break;
			default: break;
		}

		// Execute, grab errors
		if (curl_exec($curl))
			$this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		else
			$this->response->error = array(
				'code' => curl_errno($curl),
				'message' => curl_error($curl),
				'resource' => $this->resource
			);

		@curl_close($curl);

		// Parse body into XML
		if ($this->response->error === false && isset($this->response->headers['type']) &&
		$this->response->headers['type'] == 'application/xml' && isset($this->response->body))
		{
			$this->response->body = simplexml_load_string($this->response->body);

			// Grab S3 errors
			if (!in_array($this->response->code, array(200, 204, 206)) &&
			isset($this->response->body->Code, $this->response->body->Message))
			{
				$this->response->error = array(
					'code' => (string)$this->response->body->Code,
					'message' => (string)$this->response->body->Message
				);
				if (isset($this->response->body->Resource))
					$this->response->error['resource'] = (string)$this->response->body->Resource;
				unset($this->response->body);
			}
		}

		// Clean up file resources
		if ($this->fp !== false && is_resource($this->fp)) fclose($this->fp);

		return $this->response;
	}