public function respond(ResponseBuilder $response)
{
$response_type = $this->parseContext();
$response = $this->hooks->trigger('response', $response_type, $response, $response);
if (!$response instanceof ResponseBuilder) {
throw new InvalidParameterException("Handlers for 'response','{$response_type}' plugin hook must " . "return an instanceof " . ResponseBuilder::class);
}
if ($response->isNotModified()) {
return $this->send($this->prepareResponse('', ELGG_HTTP_NOT_MODIFIED));
}
$is_xhr = $this->request->isXmlHttpRequest();
$is_action = false;
if (0 === strpos($response_type, 'action:')) {
$is_action = true;
}
if ($is_action && $response->getForwardURL() === null) {
// actions must always set a redirect url
$response->setForwardURL(REFERRER);
}
if ($response->getForwardURL() === REFERRER) {
$response->setForwardURL($this->request->headers->get('Referer'));
}
if ($response->getForwardURL() !== null && !$is_xhr) {
// non-xhr requests should issue a forward if redirect url is set
// unless it's an error, in which case we serve an error page
if ($this->isAction() || !$response->isClientError() && !$response->isServerError()) {
$response->setStatusCode(ELGG_HTTP_FOUND);
}
}
if ($is_xhr && $is_action && !$this->ajax->isAjax2Request()) {
// xhr actions using legacy ajax API should return 200 with wrapped data
$response->setStatusCode(ELGG_HTTP_OK);
$response->setContent($this->wrapLegacyAjaxResponse($response->getContent(), $response->getForwardURL()));
}
if ($is_xhr && $is_action) {
// Actions always respond with JSON on xhr calls
$headers = $response->getHeaders();
$headers['Content-Type'] = 'application/json; charset=UTF-8';
$response->setHeaders($headers);
}
$content = $this->stringify($response->getContent());
$status_code = $response->getStatusCode();
$headers = $response->getHeaders();
if ($response->isRedirection()) {
$redirect_url = $response->getForwardURL();
return $this->redirect($redirect_url, $status_code);
}
if ($this->ajax->isReady() && $response->isSuccessful()) {
return $this->respondFromContent($content, $status_code, $headers);
}
if ($response->isClientError() || $response->isServerError() || $response instanceof ErrorResponse) {
return $this->respondWithError($content, $status_code, $headers);
}
return $this->respondFromContent($content, $status_code, $headers);
}