Injects the web debug toolbar into the given Response.

@param Response $response A Response instance
332451
protected function injectToolbar(Response $response, $profile, $renderer)
    {
        $content = $response->getContent();
        $pos = strripos($content, '</body>');

        if (false !== $pos) {
            $bb_dir = $renderer->getApplication()->getBBDir();
            $toolbar = "\n".str_replace("\n", '', $renderer->partial(
                $bb_dir.'/Resources/scripts/Profiler/toolbar.html.twig',
                array(
                    'profile'   => $profile,
                    'templates' => $this->loadTemplates(),
                )
            ))."\n";

            $content = substr($content, 0, $pos).$toolbar.substr($content, $pos);
            $response->setContent($content);
        }
    }
375583
public function respond($response = array(), $replaceResponse = false)
    {
        // Set any final data
        $this->set($response, $replaceResponse);

        // Make sure it only responds once
        if ($this->hasResponded()) {
            return;
        }

        // Clear anything that may have snuck in
        $this->cleanBuffer();

        if (self::$code == 204) {
            // No-body response
            $this->responseSent = true;
            return;
        }

        if (!empty($this->apiResponseCallback) && is_callable($this->apiResponseCallback)) {
            $callback = &$this->apiResponseCallback;
            $callback($this->response);
        }

        // Format for specific output type
        if ($this->responseFormat == 'JSON') {
            if ($this->jsonCallbackWrap) {
                echo $this->jsonCallbackWrap . '(';
            }

            echo json_encode($this->response);

            if ($this->jsonCallbackWrap) {
                echo ');';
            }
        } else {
            throw new \Exception('Invalid response format: '. $this->responseFormat);
        }

        // Indicate the response as already sent
        $this->responseSent = true;
    }
1114847
public function execute(Request $request, Response $response, ...$params)
    {
        if (defined('FOCUS_DEBUG') && FOCUS_DEBUG) {
            $this->getLogger()->debug('404 - Not Found');
        }

        $response->header('HTTP/1.1 404 Not Found');
        if (!empty($params)) {
            $response->write(...$params);
        } else {
            $response->write('Not Found.');
        }
    }
669314
public function processResponse(Response $response) {
		if ($this->logCode) {
			$response->headers->set('C-Code-For-Logger', $this->logCode);
		}
	}
530801
protected function injectToolbar(Response $response, Request $request)
    {
        $content = $response->getContent();
        $pos = strripos($content, '</body>');

        if (false !== $pos) {
            $toolbar = "\n".str_replace(
                    "\n",
                    '',
                    $this->twig->render(
                        '@KunstmaanAdmin/Toolbar/toolbar.html.twig',
                        ['collectors' => $this->dataCollector->getDataCollectors()]
                    )
                )."\n";
            $content = substr($content, 0, $pos).$toolbar.substr($content, $pos);
            $response->setContent($content);
        }
    }
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);
    }
803866
private static void debug(String header, HttpResponse response) {
	if (logger.isTraceEnabled()) {
	    logger.trace(header);
	    logger.trace(response.toString());
	}
    }
1300320
protected function debugResponse($url, $payload, array $headers)
    {
        if ($this->debug)
        {
            // debug for xterm-compliant cli
            if (php_sapi_name() === 'cli')
            {
                echo PHP_EOL;
                echo "\e[1;33m<<<\e[0;33m [{$url}] \e[1;33m<<<\e[00m" . PHP_EOL;
                foreach ($headers as $key => $value)
                {
                    echo "\e[1;34m{$key}: \e[0;34m{$value}\e[00m" . PHP_EOL;
                }
                echo PHP_EOL;
                echo ($json = json_decode($payload, true)) == NULL ? $payload : json_encode($json, JSON_PRETTY_PRINT);
                echo PHP_EOL;
            }
            // debug for the rest
            else
            {
                echo "<<< [{$url}] <<<" . PHP_EOL;
                print_r(($json = json_decode($payload)) == NULL ? $payload : $json);
                echo PHP_EOL;
            }
        }
    }
973863
public static function create_debug_view(HTTPRequest $request = null)
    {
        $service = static::supportsHTML($request)
            ? DebugView::class
            : CliDebugView::class;
        return Injector::inst()->get($service);
    }
600742
public function execute($response) {

        $ok = $this->check_tool_proxy(null, $response->get_request_data());
        if ($ok) {
            $toolproxy = $this->get_service()->get_tool_proxy();
        } else {
            $toolproxy = null;
            $response->set_code(401);
        }
        $tools = array();

        // Ensure all required elements are present in the Tool Proxy.
        if ($ok) {
            $toolproxyjson = json_decode($response->get_request_data());
            $ok = !empty($toolproxyjson);
            if (!$ok) {
                debugging('Tool proxy is not properly formed JSON');
            } else {
                $ok = isset($toolproxyjson->tool_profile->product_instance->product_info->product_family->vendor->code);
                $ok = $ok && isset($toolproxyjson->security_contract->shared_secret);
                $ok = $ok && isset($toolproxyjson->tool_profile->resource_handler);
                if (!$ok) {
                    debugging('One or more missing elements from tool proxy: vendor code, shared secret or resource handlers');
                }
            }
        }

        // Check all capabilities requested were offered.
        if ($ok) {
            $offeredcapabilities = explode("\n", $toolproxy->capabilityoffered);
            $resources = $toolproxyjson->tool_profile->resource_handler;
            $errors = array();
            foreach ($resources as $resource) {
                if (isset($resource->message)) {
                    foreach ($resource->message as $message) {
                        if (!in_array($message->message_type, $offeredcapabilities)) {
                            $errors[] = $message->message_type;
                        } else if (isset($resource->parameter)) {
                            foreach ($message->parameter as $parameter) {
                                if (isset($parameter->variable) && !in_array($parameter->variable, $offeredcapabilities)) {
                                    $errors[] = $parameter->variable;
                                }
                            }
                        }
                    }
                }
            }
            if (count($errors) > 0) {
                $ok = false;
                debugging('Tool proxy contains capabilities which were not offered: ' . implode(', ', $errors));
            }
        }

        // Check all services requested were offered (only tool services currently supported).
        if ($ok && isset($toolproxyjson->security_contract->tool_service)) {
            $contexts = lti_get_contexts($toolproxyjson);
            $profileservice = lti_get_service_by_name('profile');
            $profileservice->set_tool_proxy($toolproxy);
            $context = $profileservice->get_service_path() . $profileservice->get_resources()[0]->get_path() . '#';
            $offeredservices = explode("\n", $toolproxy->serviceoffered);
            $services = lti_get_services();
            $tpservices = $toolproxyjson->security_contract->tool_service;
            $errors = array();
            foreach ($tpservices as $service) {
                $fqid = lti_get_fqid($contexts, $service->service);
                if (substr($fqid, 0, strlen($context)) !== $context) {
                    $errors[] = $service->service;
                } else {
                    $id = explode('#', $fqid, 2);
                    $aservice = lti_get_service_by_resource_id($services, $id[1]);
                    $classname = explode('\\', get_class($aservice));
                    if (empty($aservice) || !in_array($classname[count($classname) - 1], $offeredservices)) {
                        $errors[] = $service->service;
                    }
                }
            }
            if (count($errors) > 0) {
                $ok = false;
                debugging('Tool proxy contains services which were not offered: ' . implode(', ', $errors));
            }
        }

        // Extract all launchable tools from the resource handlers.
        if ($ok) {
            $resources = $toolproxyjson->tool_profile->resource_handler;
            $messagetypes = [
                'basic-lti-launch-request',
                'ContentItemSelectionRequest',
            ];
            foreach ($resources as $resource) {
                $launchable = false;
                $messages = array();
                $tool = new \stdClass();

                $iconinfo = null;
                if (is_array($resource->icon_info)) {
                    $iconinfo = $resource->icon_info[0];
                } else {
                    $iconinfo = $resource->icon_info;
                }
                if (isset($iconinfo) && isset($iconinfo->default_location) && isset($iconinfo->default_location->path)) {
                    $tool->iconpath = $iconinfo->default_location->path;
                }

                foreach ($resource->message as $message) {
                    if (in_array($message->message_type, $messagetypes)) {
                        $launchable = $launchable || ($message->message_type === 'basic-lti-launch-request');
                        $messages[$message->message_type] = $message;
                    }
                }
                if (!$launchable) {
                    continue;
                }
                $tool->name = $resource->resource_name->default_value;
                $tool->messages = $messages;
                $tools[] = $tool;
            }
            $ok = count($tools) > 0;
            if (!$ok) {
                debugging('No launchable messages found in tool proxy');
            }
        }

        // Add tools and custom parameters.
        if ($ok) {
            $baseurl = '';
            if (isset($toolproxyjson->tool_profile->base_url_choice[0]->default_base_url)) {
                $baseurl = $toolproxyjson->tool_profile->base_url_choice[0]->default_base_url;
            }
            $securebaseurl = '';
            if (isset($toolproxyjson->tool_profile->base_url_choice[0]->secure_base_url)) {
                $securebaseurl = $toolproxyjson->tool_profile->base_url_choice[0]->secure_base_url;
            }
            foreach ($tools as $tool) {
                $messages = $tool->messages;
                $launchrequest = $messages['basic-lti-launch-request'];
                $config = new \stdClass();
                $config->lti_toolurl = "{$baseurl}{$launchrequest->path}";
                $config->lti_typename = $tool->name;
                $config->lti_coursevisible = 1;
                $config->lti_forcessl = 0;
                if (isset($messages['ContentItemSelectionRequest'])) {
                    $contentitemrequest = $messages['ContentItemSelectionRequest'];
                    $config->lti_contentitem = 1;
                    if ($launchrequest->path !== $contentitemrequest->path) {
                        $config->lti_toolurl_ContentItemSelectionRequest = $baseurl . $contentitemrequest->path;
                    }
                    $contentitemcapabilities = implode("\n", $contentitemrequest->enabled_capability);
                    $config->lti_enabledcapability_ContentItemSelectionRequest = $contentitemcapabilities;
                    $contentitemparams = self::lti_extract_parameters($contentitemrequest->parameter);
                    $config->lti_parameter_ContentItemSelectionRequest = $contentitemparams;
                }

                $type = new \stdClass();
                $type->state = LTI_TOOL_STATE_PENDING;
                $type->toolproxyid = $toolproxy->id;
                $type->enabledcapability = implode("\n", $launchrequest->enabled_capability);
                $type->parameter = self::lti_extract_parameters($launchrequest->parameter);

                if (!empty($tool->iconpath)) {
                    $type->icon = "{$baseurl}{$tool->iconpath}";
                    if (!empty($securebaseurl)) {
                        $type->secureicon = "{$securebaseurl}{$tool->iconpath}";
                    }
                }

                $ok = $ok && (lti_add_type($type, $config) !== false);
            }
            if (isset($toolproxyjson->custom)) {
                lti_set_tool_settings($toolproxyjson->custom, $toolproxy->id);
            }
        }

        if (!empty($toolproxy)) {
            if ($ok) {
                // If all went OK accept the tool proxy.
                $toolproxy->state = LTI_TOOL_PROXY_STATE_ACCEPTED;
                $toolproxy->toolproxy = $response->get_request_data();
                $toolproxy->secret = $toolproxyjson->security_contract->shared_secret;
                $toolproxy->vendorcode = $toolproxyjson->tool_profile->product_instance->product_info->product_family->vendor->code;

                $url = $this->get_endpoint();
                $body = <<< EOD
{
  "@context" : "http://purl.imsglobal.org/ctx/lti/v2/ToolProxyId",
  "@type" : "ToolProxy",
  "@id" : "{$url}",
  "tool_proxy_guid" : "{$toolproxy->guid}"
}
EOD;
                $response->set_code(201);
                $response->set_content_type('application/vnd.ims.lti.v2.toolproxy.id+json');
                $response->set_body($body);
            } else {
                // Otherwise reject the tool proxy.
                $toolproxy->state = LTI_TOOL_PROXY_STATE_REJECTED;
                $response->set_code(400);
            }
            lti_update_tool_proxy($toolproxy);
        } else {
            $response->set_code(400);
        }
    }
1236532
protected function injectAlert(Response $response)
    {
        $content = $response->getContent();

        $pos = strripos($content, '<body>');
        if (false !== $pos) {
            $renderedContent = soda_cms_view('partials.draft-alert')->render();

            $content = substr($content, 0, $pos).$renderedContent.substr($content, $pos);

            // Update the new content and reset the content length
            $response->setContent($content);
            $response->headers->remove('Content-Length');
        }
    }
1043781
public function prepareForResponse(Response $response) {
	    if ('application/json' == $response->getRequest()->getAcceptRange()
	               ->bestMatch(['text/html', 'application/json'])) {
	        $this->jhtmlJsonPayload = new JhtmlJsonPayload($this->additionalAttrs);
	        $this->jhtmlJsonPayload->applyView($this->htmlView);
	        $this->jhtmlJsonPayload->prepareForResponse($response);
	        return;
	    }
	    
	    $this->jhtmlJsonPayload = null;
	    $this->htmlView->prepareForResponse($response);
	}
231674
protected function buildJsonpResponse(Response $response) {
		$content     = (string)$response->getBody();
		$contentType = $response->getHeaderLine('Content-Type');

		if (strpos($contentType, 'application/json') === false) {
			$content = '"' . $content . '"';
		}

		$callback = "{$this->callbackName}({$content});";

		$newResponse = new Response(200);
		$newResponse->getBody()->write($callback);

		return $newResponse->withHeader('Content-Type', 'application/javascript');
	}
125066
public function apply(\BearFramework\App\Response $response): void
    {
        $this->applyTheme($response);
        $this->process($response);
        $this->applyDefaults($response);
        $this->applyAdminUI($response);
    }
620411
protected function appendToResponse(Response $response)
    {
        $existingContent = $response->getContent();
        $closeBodyPosition = strripos($existingContent, '</body>');
        $appendedContent = "
            <script>
                window.open('".route('mail-debug', ['file' => $this->debug->preview()])."','width=680,height=800,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=0,top=0');
            </script>";

        if ($closeBodyPosition !== false) {
            $response->setContent(substr($existingContent, 0, $closeBodyPosition).$appendedContent.substr($existingContent, $closeBodyPosition));

            return;
        }

        $response->setContent($existingContent.$appendedContent);
    }
747638
public function onResponse(FilterResponseEvent $event)
    {
        $request = $event->getRequest();
        $debug = $request->query->get('debug');
        $response = $event->getResponse();

        //this is for debug purpose
        if ($response instanceof JsonResponse && $debug) {
            $new = new Response();
            $new->setContent('<body>'.$response->getContent().'</body>');
            $event->setResponse($new);
        }
    }
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;
        }
    }