Send response to the browser
@param $response
336647
public function sendResponse($response)
    {
        // clean any previous output from buffer. Not effective in some cases
        while (ob_get_level() > 0) {
            ob_end_clean();
        }

        // console //

        if ($response instanceof ConsoleResponse) {
            echo $response->getContent();
            $errorLevel = (int) $response->getErrorLevel();
            exit($errorLevel);
        }


        // http //

        // send headers
        foreach ($response->getHeaders() as $header) {
            header($header->toString());
        }

        // send status
        $status = $response->renderStatusLine();
        header($status);

        // send content
        echo $response->getContent();
        exit(1);
    }
197246
private function send(RequestInterface $request, ResponseInterface $response)
    {
        // Send headers if no headers has been sent before this
        if (!headers_sent()) {
            // Send headers
            $this->sendHeaders($response);
        }

        // Check if we have any content to flush
        if (ob_get_level() > 1) {
            // Flush (send) the buffer that contains output that the application has generated
            while (ob_get_level() >= $this->outputBufferLevel) {
                ob_end_flush();
            }
        }

        // Set buffer level to null
        $this->outputBufferLevel = null;

        // Make sure it wasn't a HEAD request
        if ($request->getMethod() !== 'HEAD') {
            // Send the body to the client by echoing it
            echo $response->getBody();
        }
    }
405726
protected function afterDispatch($response)
    {
        if (!$response instanceof Response) {
            $response = RequestContext::getResponse()->auto($response);
        }

        // Handle Response
        $response->send();

        // Release system resources
        App::trigger(AppEvent::RESOURCE_RELEASE);

        // Trigger 'After Request' event
        App::trigger(HttpServerEvent::AFTER_REQUEST);
    }
983726
private function parseResponse($response) {
        $response = trim($response);
        $this->responseStatus = (int) substr($response, 0, 3);
        $this->response = substr($response, 4);
    }
1069472
private function handleResponse($response)
    {
        if ($this->client->newFormatModeEnabled === true) {
            return $response;
        }

        return $this->client->handleHttpResponse($response);
    }
468866
function process_response($request, $response)
    {
        if (! $request->user->isAnonymous()) {
            $request->session->setData($this->session_key, $request->user->id);
        }
        return $response;
    }
998967
public function send(DispatcherResponseInterface $response)
    {
        $request  = $response->getRequest();

        if($response->isStreamable())
        {
            //Explicitly set the Accept Ranges header to bytes to inform client we accept range requests
            $response->headers->set('Accept-Ranges', 'bytes');

            if($request->isStreaming())
            {
                if($response->isSuccess())
                {
                    if(ini_get('zlib.output_compression')) {
                        @ini_set('zlib.output_compression', 'Off');
                    }

                    //Fix for IE7/8
                    if(function_exists('apache_setenv')) {
                        @apache_setenv('no-gzip', '1');
                    }

                    //Remove PHP time limit
                    if(!ini_get('safe_mode')) {
                        @set_time_limit(0);
                    }

                    //Default Content-Type Header
                    if(!$response->headers->has('Content-Type')) {
                        $response->headers->set('Content-Type', 'application/octet-stream');
                    }

                    //Content Range Headers
                    $offset = $this->getOffset($response);
                    $range  = $this->getRange($response);
                    $size   = $this->getFileSize($response);

                    $response->setStatus(HttpResponse::PARTIAL_CONTENT);
                    $response->headers->set('Content-Length', $range - $offset + 1);
                    $response->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $offset, $range, $size));
                }

                if($response->isError())
                {
                    /**
                     * A server sending a response with status code 416 (Requested range not satisfiable) SHOULD include a
                     * Content-Range field with a byte-range- resp-spec of "*". The instance-length specifies the current
                     * length of the selected resource.
                     *
                     * @see : http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16
                     */
                    if($response->getStatusCode() == HttpResponse::REQUESTED_RANGE_NOT_SATISFIED)
                    {
                        $size = $this->getFileSize($response);
                        $response->headers->set('Content-Range', sprintf('bytes */%s', $size));
                    }
                }
            }
        }

        return parent::send($response);
    }
1023112
private function send(Response $response, Request $request = null): \Generator
    {
        \assert($this->client, "The driver has not been setup; call setup first");

        if ($this->lastWrite) {
            yield $this->lastWrite; // Prevent writing another response until the first is finished.
        }

        $shouldClose = false;

        $protocol = $request !== null ? $request->getProtocolVersion() : "1.0";

        $status = $response->getStatus();
        $reason = $response->getReason();

        $headers = $this->filter($response, $protocol, $request ? $request->getHeaderArray("connection") : []);

        $chunked = !isset($headers["content-length"])
            && $protocol === "1.1"
            && $status >= Status::OK;

        if (!empty($headers["connection"])) {
            foreach ($headers["connection"] as $connection) {
                if (\strcasecmp($connection, "close") === 0) {
                    $chunked = false;
                    $shouldClose = true;
                }
            }
        }

        if ($chunked) {
            $headers["transfer-encoding"] = ["chunked"];
        }

        $buffer = "HTTP/{$protocol} {$status} {$reason}\r\n";
        $buffer .= Rfc7230::formatHeaders($headers);
        $buffer .= "\r\n";

        if ($request !== null && $request->getMethod() === "HEAD") {
            ($this->write)($buffer, $shouldClose);
            return;
        }

        $chunk = ""; // Required for the finally, not directly overwritten, even if your IDE says otherwise.
        $body = $response->getBody();
        $streamThreshold = $this->options->getStreamThreshold();

        try {
            while (null !== $chunk = yield $body->read()) {
                if (!($length = \strlen($chunk))) {
                    continue;
                }

                if ($chunked) {
                    $chunk = \sprintf("%x\r\n%s\r\n", $length, $chunk);
                }

                if (\strlen($buffer) < $streamThreshold) {
                    $buffer .= $chunk;
                    continue;
                }

                // Initially the buffer won't be empty and contains the headers.
                // We save a separate write or the headers here.
                $promise = ($this->write)($buffer);

                $buffer = $chunk;
                $chunk = ""; // Don't use null here, because of the finally

                yield $promise;
            }

            if ($buffer !== "" || $chunked || $shouldClose) {
                yield ($this->write)($chunked ? "{$buffer}0\r\n\r\n" : $buffer, $shouldClose);
            }
        } catch (ClientException $exception) {
            return; // Client will be closed in finally.
        } finally {
            if ($chunk !== null) {
                $this->client->close();
            }
        }
    }
1214520
protected function sendSamlResponse(Response $response)
    {
        $bindingFactory = new \LightSaml\Binding\BindingFactory();
        $postBinding = $bindingFactory->create(\LightSaml\SamlConstants::BINDING_SAML2_HTTP_POST);
        $messageContext = new \LightSaml\Context\Profile\MessageContext();
        $messageContext->setMessage($response)->asResponse();
        /** @var \Symfony\Component\HttpFoundation\Response $httpResponse */
        $httpResponse = $postBinding->send($messageContext);
        print $httpResponse->getContent()."\n\n";
    }
346708
public function handleResponse(Response $response) : void
    {
        if ($this->id === null) {
            // The request was not associated with an existing session, and no session writes occurred.
            // Sending a session cookie is unnecessary.
            return;
        }

        // Note: we re-send the session cookie even if it was part of the request, to refresh the expiration time.

        $this->writeSessionId($response);
        $this->reset();
    }
724618
public function execute($response) {
        global $CFG, $DB;

        $params = $this->parse_template();
        $contextid = $params['context_id'];
        $itemid = $params['item_id'];
        if ($response->get_request_method() === 'GET') {
            $contenttype = $response->get_accept();
        } else {
            $contenttype = $response->get_content_type();
        }
        // We will receive typeid when working with LTI 1.x, if not then we are in LTI 2.
        $typeid = optional_param('type_id', null, PARAM_ALPHANUM);
        if (is_null($typeid)) {
            if (!$this->check_tool_proxy(null, $response->get_request_data())) {
                $response->set_code(403);
                $response->set_reason("Invalid tool proxy specified.");
                return;
            }
        } else {
            switch ($response->get_request_method()) {
                case self::HTTP_GET:
                    if (!$this->check_type($typeid, $contextid, 'LineItem.item:get', $response->get_request_data())) {
                        $response->set_code(403);
                        $response->set_reason("This resource does not support GET requests.");
                        return;
                    }
                    break;
                case self::HTTP_PUT:
                    if (!$this->check_type($typeid, $contextid, 'LineItem.item:put', $response->get_request_data())) {
                        $response->set_code(403);
                        $response->set_reason("This resource does not support PUT requests.");
                        return;
                    }
                    break;
                case self::HTTP_DELETE:
                    if (!$this->check_type($typeid, $contextid, 'LineItem.item:delete', $response->get_request_data())) {
                        $response->set_code(403);
                        $response->set_reason("This resource does not support DELETE requests.");
                        return;
                    }
                    break;
                default:  // Should not be possible.
                    $response->set_code(405);
                    return;
            }
        }
        if (empty($contextid) || (!empty($contenttype) && !in_array($contenttype, $this->formats))) {
            $response->set_code(400);
            $response->set_reason("Invalid request made.");
            return;
        }
        if (!$DB->record_exists('course', array('id' => $contextid))) {
            $response->set_code(404);
            $response->set_reason("Not Found: Course $contextid doesn't exist.");
            return;
        }
        if (!$DB->record_exists('grade_items', array('id' => $itemid))) {
            $response->set_code(404);
            $response->set_reason("Not Found: Grade item $itemid doesn't exist.");
            return;
        }
        $item = $this->get_service()->get_lineitem($contextid, $itemid, $typeid);
        if ($item === false) {
            $response->set_code(403);
            $response->set_reason("Line item does not exist.");
            return;
        }
        require_once($CFG->libdir.'/gradelib.php');
        switch ($response->get_request_method()) {
            case 'GET':
                $this->get_request($response, $item, $typeid);
                break;
            case 'PUT':
                $json = $this->process_put_request($response->get_request_data(), $item, $typeid);
                $response->set_body($json);
                $response->set_code(200);
                break;
            case 'DELETE':
                $this->process_delete_request($item);
                $response->set_code(204);
                break;
            default:  // Should not be possible.
                $response->set_code(405);
                $response->set_reason("Invalid request method specified.");
                return;
        }
    }
1047826
private function checkResponse($response)
    {
        $hasRequestError = false;
        if (preg_match('/4\d\d/', $response->getStatusCode())) {
            $this->log('error', "Invalid API key or password");
            $this->addError(self::ERROR_HTTP_AUTHENTICATION_ERROR, false);
            $hasRequestError = true;
        } elseif (preg_match('/5\d\d/', $response->getStatusCode())) {
            $this->log('error', "Gateway error - HTTP " . $response->getStatusCode());
            $this->addError(self::ERROR_HTTP_SERVER_ERROR);
            $hasRequestError = true;
        } elseif ($response->getError()) {
            $this->log('error', "Connection error: " . $response->getError());
            $this->addError(self::ERROR_CONNECTION_ERROR);
            $hasRequestError = true;
        }

        if ($hasRequestError) {
            throw new RequestException(sprintf("Last HTTP response status code: %s", $response->getStatusCode()));
        }
    }
847398
protected function sendHeaders(Response $response)
    {
        // Send HTTP status & reason-phrase
        header(
            sprintf(
                '%s %s %s',
                $this->getProtocolLine(),
                $response->getStatusCode(),
                $response->getReasonPhrase()
            ),
            true,
            $response->getStatusCode()
        );

        // Send headers
        $headers = $response->getHeaders();
        foreach ($headers as $name => $valueCollection) {
            foreach ($valueCollection as $value) {
                header(sprintf('%s: %s', $name, $value), false);
            }
        }
    }
194062
public function respond(ResponseInterface $response)
    {
        $this->httpClient->respond(
            $response->getStatusCode(),
            $response->getBody()->__toString(),
            $response->getHeaders()
        );
    }
888362
private function sendResponse(Auth_OpenID_ServerResponse $response) {

		SimpleSAML\Logger::debug('openidProvider::sendResponse');

		$webresponse = $this->server->encodeResponse($response);

		if ($webresponse->code !== 200) {
			header('HTTP/1.1 ' . $webresponse->code, TRUE, $webresponse->code);
		}

		foreach ($webresponse->headers as $k => $v) {
			header($k . ': ' . $v);
		}
		header('Connection: Close');

		print($webresponse->body);
		exit(0);
	}
328712
public function sendResponse(ResponseInterface $response): void
    {
        // Send all the headers
        \http_response_code($response->getStatusCode());
        foreach ($response->getHeaders() as $headerName => $headerValues) {
            /** @var string[] $headerValues */
            foreach ($headerValues as $headerValue) {
                \header("$headerName: $headerValue", false);
            }
        }

        // Get the body, rewind it if possible
        $body = $response->getBody();
        if ($body->isSeekable()) {
            $body->rewind();
        }

        // If the body is not readable do not send any body to the client
        if (!$body->isReadable()) {
            return;
        }

        // Send the body (by chunk if specified in the container using streamReadLength value)
        if (null === $this->streamReadLength) {
            echo $body->__toString();

            return;
        }

        while (!$body->eof()) {
            echo $body->read($this->streamReadLength);
        }
    }
395187
public function send(DispatcherResponseInterface $response)
    {
        if($response->isDownloadable())
        {
            $server = strtolower($_SERVER['SERVER_SOFTWARE']);

            //Apache
            if(strpos($server, 'apache') !== FALSE)
            {
                if(in_array('mod_xsendfile', apache_get_modules()))
                {
                    $path = $response->getStream()->getPath();

                    $response->headers->set('X-Sendfile', $path);
                    return parent::send($response);
                }
            }

            //Nginx
            if(strpos($server, 'nginx') !== FALSE)
            {
                $path = $response->getStream()->getPath();
                $path = preg_replace('/'.preg_quote(\Kodekit::getInstance()->getRootPath(), '/').'/', '', $path, 1);

                $response->headers->set('X-Accel-Redirect' , $path);
                return parent::send($response);
            }
        }
    }