Prints out HTTP response to the client

@return Response
@throws Exception
558010
public function send()
    {
        if ($this->sent === false) {
            $this->sendHeaders();
            $this->sendCookies();

            $content = (string)$this->getBody();
            if (!empty($content)) {
                echo $content;
            } else {
                if (is_string($this->file)) {
                    if (!file_exists($this->file)) {
                        throw new Exception('The requested file was not found');
                    }
                    $handle = fopen($this->file, 'r');

                    if ($handle !== false) {
                        fpassthru($handle);
                        fclose($handle);
                    }
                }
            }

            $this->sent = true;

            return $this;
        }

        throw new Exception('Response was already sent');
    }
1253926
public function handleRequest()
    {
        try {
            $this->response = parent::handleRequest();
        } catch (HttpException $ex) {
            $this->config->set('page_title', 'Error');

            $view = new View('exception');
            $view->exception = $ex;

            $this->response->setResponseCode($ex->getErrorCode());
            $this->response->setContent($view->render());
        } catch (\Exception $ex) {
            $this->config->set('page_title', 'Error');

            $view = new View('exception');
            $view->exception = $ex;

            $this->response->setResponseCode(500);
            $this->response->setContent($view->render());
        }

        if ($this->response->hasLayout() && $this->controller->layout) {
            $this->setLayoutVariables($this->controller->layout);

            $this->controller->layout->content  = $this->response->getContent();
            $this->response->setContent($this->controller->layout->render());
        }

        return $this->response;
    }
1276468
public function index(): HTTPResponse
    {
        $body = null;
        $contentType = $this->getRequest()->getHeader('Content-Type');

        if ($contentType === 'application/json') {
            $body = json_decode($this->getRequest()->getBody(), true);
        } else {
            $body = $this->getRequest()->postVars();
        }

        if (empty($body)) {
            return $this->getErrorResponse(
                'No parameters could be found in request body. Did you correctly set the Content-Type header?',
                500
            );
        }

        // request needs parsed body
        $psrRequest = (new HttpRequestAdapter())->toPsr7($this->getRequest())
            ->withParsedBody($body);
        $psrResponse = new Response();

        $authServer = $this->serverGenerator->getServer();

        try {
            return (new HttpResponseAdapter())
                ->fromPsr7($authServer->respondToAccessTokenRequest($psrRequest, $psrResponse));
        } catch (OAuthServerException $e) {
            return $this->convertResponse($e->generateHttpResponse(new Response()));
        } catch (Exception $e) {
            return $this->getErrorResponse($e->getMessage());
        }
    }
833590
public function getResponseData(): Response
    {
        $connectionResponse = new ConnectionResponseImpl();
        $errorResponse = $this->streamSocket->read();
        if ($errorResponse !== null) {
            $this->getLogger()->error('Send error: ' . $errorResponse);
            $this->streamSocket->disconnect();
            $response = @unpack('Ccommand/Cstatus/Nidentifier', $errorResponse);
            if (!empty($response)) {
                $connectionResponse->setErrorResponse($response);
            } else {
                $connectionResponse->setErrorResponse(null);
            }
        }

        return $connectionResponse;
    }
1240773
public function toResponse(): Response
    {
        return new Response(
            $this->status,
            $this->headers,
            $this->body,
            $this->httpVersion,
            $this->reason
        );
    }
550070
protected function sendRequest()
    {
        $context = stream_context_create($this->request);
        $response = trim(file_get_contents($this->endpoint, FALSE, $context));
        $this->response = new Response($http_response_header, $response, $this->request);

        return $this->response;
    }
607664
public function output() {
		$arguments = func_get_args();
		$this->pager->page();
		$result = [];

		if (count($arguments) == 1) {
			$headers = $arguments[0];
			$fields = $arguments[0];
		} elseif (count($arguments == 2)) {
			$headers = $arguments[0];
			$fields = $arguments[1];
			if (count($headers) != count($fields)) {
				throw new \Exception('If headers and fields are given, both should have an equal amount of values');
			}
		} else {
			throw new \Exception('This function requires 1 or 2 arrays as parameter: The first is the header, second are the field names or closures.');
		}


		foreach ($this->pager->items as $item) {
			$row = [];
			foreach ($headers as $key => $header) {
				if (is_callable($fields[$key])) {
					$row[$header] = $fields[$key]($item);
				} else {
					$row[$header] = \Skeleton\Pager\Util::object_get_attribute($item, $fields[$key]);
				}
			}
			$result[] = $row;
		}

		$this->output_array($headers, $result);

	}
389915
protected function send_response() {

        //Check that the returned values are valid
        try {
            if ($this->function->returns_desc != null) {
                $validatedvalues = external_api::clean_returnvalue($this->function->returns_desc, $this->returns);
            } else {
                $validatedvalues = null;
            }
        } catch (Exception $ex) {
            $exception = $ex;
        }

        if (!empty($exception)) {
            $response =  $this->generate_error($exception);
        } else {
            //We can now convert the response to the requested REST format
            if ($this->restformat == 'json') {
                $response = json_encode($validatedvalues);
            } else {
                $response = '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
                $response .= '<RESPONSE>'."\n";
                $response .= self::xmlize_result($validatedvalues, $this->function->returns_desc);
                $response .= '</RESPONSE>'."\n";
            }
        }

        $this->send_headers();
        echo $response;
    }
1054455
protected function sendRequest()
    {
        try {
            $this->response = $this->client->send($this->request);
        } catch (RequestException $e) {
            $this->response = $e->getResponse();

            if (null === $this->response) {
                if ($this->throwsRequestException) {
                    throw $e;
                }
            }

            if ($this->throwsRequestException) {
                throw new \Exception((string)$this->response->getBody());
            }
        }
    }
137474
public function getResponse()
    {
        if (!$this->dataSource instanceof ServerSideInterface) {
            throw new Exception('You must call this method when use server side data source.');
        }

        $response = new Response();
        $request = new Request();

        $this->dataSource->getResponse($response, $request);

        return $response;
    }
420102
public function output()
    {
        // Check that the method for this HTTP request method exists.
        $methodName = 'http_' . $this->request->httpMethod();
        if (method_exists($this, $methodName)) {
            // Execute the requested Resource instance's method that 
            // corresponds with the requested HTTP method.
            return $this->$methodName();
        } else {
            // The Resource instance didn't define a method for the request's 
            // HTTP method - return a 405.
            return $this->response->send(
                    405,
                    'The requested resource does not support the HTTP method'.
                    ' "' . $this->request->httpMethod() . '".'
            );
        }   
    }
954105
function sendHeaders()
    {
        if ($this->isHeadersSent())
            throw new \Exception('Headers was sent.');

        $response = $this->getMessageObject();

        // Step 1: Send the "status line".
        $statusLine = sprintf('HTTP/%s %s %s'
            , $response->getProtocolVersion()
            , $response->getStatusCode()
            , $response->getReasonPhrase()
        );
        header($statusLine, true); /* The header replaces a previous similar header. */


        // Step 2: Send the response headers from the headers list.
        foreach ($response->getHeaders() as $name => $values) {
            $responseHeader = sprintf('%s: %s'
                , $name
                , $response->getHeaderLine($name)
            );
            header($responseHeader, false); /* The header doesn't replace a previous similar header. */
        }

        $this->isHeadersSent = true;
        return $this;
    }
699487
public function processResponse()
    {

        // Results that will be returned
        $results = [ ];

        // Get the length of the server code so we can figure out how much to read later
        $serverCodeLength = strlen($this->server_code);

        // We need to pre-sort these for split packets so we can do extra work where needed
        foreach ($this->packets_response as $response) {
            // Make new buffer
            $buffer = new Buffer($response);

            // Check the header, should be SAMP
            if (($header = $buffer->read(4)) !== 'SAMP') {
                throw new Exception(__METHOD__ . " header response '{$header}' is not valid");
            }

            // Check to make sure the server response code matches what we sent
            if ($buffer->read($serverCodeLength) !== $this->server_code) {
                throw new Exception(__METHOD__ . " code check failed.");
            }

            // Figure out what packet response this is for
            $response_type = $buffer->read(1);

            // Figure out which packet response this is
            if (!array_key_exists($response_type, $this->responses)) {
                throw new Exception(__METHOD__ . " response type '{$response_type}' is not valid");
            }

            // Now we need to call the proper method
            $results = array_merge(
                $results,
                call_user_func_array([ $this, $this->responses[$response_type] ], [ $buffer ])
            );

            unset($buffer);
        }

        return $results;
    }
900455
public function httpGetForHtml()
    {
        $id = $this->getRequest()->getParameter('id');
        $view = $this->getRequest()->getParameter('view');

        if ($id) {
            $entity = $this->getEntity($id);
            if ($entity) {
                $response = $this->getViewResponse($entity);
            } else {
                throw new Exception('No entity found for identifier ' . $id);
            }
        } else {
            // Get the entities to be displayed.
            $entities = $this->getEntities($view);
            // Create a Response.
            $response = $this->getHtmlResponse();
            // Set the index template.
            $response->setTemplateId(sprintf(
                            '%s/index', $this->getCollectionName()
            ));
            // Load the entities' data into the response.
            $response->setData(
                    $this->getCollectionName(), $entities
            );
            // Append a descriptive title.
            $response->appendToTitle(ucfirst($this->getCollectionName()));
        }

        // Report which set of data is currently being shown.
        $response->setData('page', array('view', $view));

        return $response;
    }
1190167
public function send()
	{
		if( $this->method === 'POST' )
			$this->addHeaderPair( 'Content-Length', mb_strlen( $this->data ) );
		if( !$this->headers->getFieldsByName( 'connection' ) )
			$this->addHeaderPair( 'Connection', 'close' );

		$result	= "";
		$fp = fsockopen( $this->host, $this->port, $errno, $errstr, 2 );
		if( !$fp )
			throw new RuntimeException( $errstr.' ('.$errno.')' );

		$uri	= $this->uri/*.( $this->port ? ':'.$this->port : "" )*/;
		$lines	= array(
			$this->method." ".$uri." HTTP/".$this->version,
			$this->headers->render(),
		);
		if( $this->method === 'POST' )
			$lines[]	= $this->data;
		$lines	= join( "\r\n", $lines );
		fwrite( $fp, $lines );																		//  send Request
		while( !feof( $fp ) )																		//  receive Response
			$result .= fgets( $fp, 1024 );															//  collect Response chunks
		fclose( $fp );																				//  close Connection
		$response	= Net_HTTP_Response_Parser::fromString( $result );
		if( count( $response->getHeader( 'Location' ) ) ){
			$location	= array_shift( $response->getHeader( 'Location' ) );
			$this->host	= parse_url( $location->getValue(), PHP_URL_HOST );
			$this->setPort( parse_url( $location->getValue(), PHP_URL_PORT ) );
			$this->setUri( parse_url( $location->getValue(), PHP_URL_PATH ) );
			return $this->send();
		}
		return $response;
	}
1124061
protected function _render()
        {
            if (mb_strlen($this->_html, 'utf-8') === 0 && empty($this->_url))
                throw new Exception("HTML content or source URL not set.");

            if ($this->getUrl()) {
                $input = $this->getUrl();
            } else {
                File::put($this->getFilePath(), $this->getHtml());
                $input = $this->getFilePath();
            }

            $content = $this->_exec(repl('%input%', $input, $this->_getCommand()));

            if (strpos(i::lower($content['stderr']), 'error'))
                    throw new Exception("System error <pre>" . $content['stderr'] . "</pre>");

            if (mb_strlen($content['stdout'], 'utf-8') === 0)
                   throw new Exception("WKHTMLTOPDF didn't return any data.");

            if ((int)$content['return'] > 1)
                throw new Exception("Shell error, return code : " . (int)$content['return']);

            return $content['stdout'];
        }
421560
public function sendHeaders()
    {
        $codes = $this->getHttpResponseCodes();
        if (!array_key_exists($this->status, $codes)) {
            $this->status = 500;
            $string = 'HTTP/1.0 500 ' . $codes[500];
        } else {
            if ($this->isValidRedirectStatus()) {
                throw new \Exception(
                    'You cannot send a redirect using a regular response. Use $this->response->redirect(url, status);'
                );
            }
            $string = 'HTTP/1.0 ' . $this->status . ' ' . $codes[$this->status];
        }

        header($string);
        $this->outputHeaders();
    }