/** * Out of the box, the handler "CurrentForm" value, which will return the rendered form. * Non-Ajax calls will redirect back. * * @param HTTPRequest $request * @param array $extraCallbacks List of anonymous functions or callables returning either a string * or HTTPResponse, keyed by their fragment identifier. The 'default' key can * be used as a fallback for non-ajax responses. * @return HTTPResponse * @throws HTTPResponse_Exception */ public function respond(HTTPRequest $request, $extraCallbacks = array()) { // Prepare the default options and combine with the others $callbacks = array_merge($this->callbacks, $extraCallbacks); $response = $this->getResponse(); $responseParts = array(); if (isset($this->fragmentOverride)) { $fragments = $this->fragmentOverride; } elseif ($fragmentStr = $request->getHeader('X-Pjax')) { $fragments = explode(',', $fragmentStr); } else { if ($request->isAjax()) { throw new HTTPResponse_Exception("Ajax requests to this URL require an X-Pjax header.", 400); } elseif (empty($callbacks['default'])) { throw new HTTPResponse_Exception("Missing default response handler for this URL", 400); } $response->setBody(call_user_func($callbacks['default'])); return $response; } // Execute the fragment callbacks and build the response. foreach ($fragments as $fragment) { if (isset($callbacks[$fragment])) { $res = call_user_func($callbacks[$fragment]); $responseParts[$fragment] = $res ? (string) $res : $res; } else { throw new HTTPResponse_Exception("X-Pjax = '{$fragment}' not supported for this URL.", 400); } } $response->setBody(Convert::raw2json($responseParts)); $response->addHeader('Content-Type', 'text/json'); return $response; }
/** * REST endpoint to get a campaign. * * @param HTTPRequest $request * * @return HTTPResponse */ public function readCampaign(HTTPRequest $request) { $response = new HTTPResponse(); if ($request->getHeader('Accept') == 'text/json') { $response->addHeader('Content-Type', 'application/json'); if (!$request->param('Name')) { return new HTTPResponse(null, 400); } /** @var ChangeSet $changeSet */ $changeSet = ChangeSet::get()->byID($request->param('ID')); if (!$changeSet) { return new HTTPResponse(null, 404); } if (!$changeSet->canView()) { return new HTTPResponse(null, 403); } $body = Convert::raw2json($this->getChangeSetResource($changeSet)); return (new HTTPResponse($body, 200))->addHeader('Content-Type', 'application/json'); } else { return $this->index($request); } }
/** * Get security token from request * * @param HTTPRequest $request * @return string */ protected function getRequestToken($request) { $name = $this->getName(); $header = 'X-' . ucwords(strtolower($name)); if ($token = $request->getHeader($header)) { return $token; } // Get from request var return $request->requestVar($name); }