/** * Redirect to the installation page of the application. * This method does not send the response. * * @param Response $response HTTP response. * @param Request $request HTTP request. * @return void */ static function redirectToInstall(Response $response, Request $request) { list($dirname) = Uri\split($request->getUrl()); $response->setStatus(307); $response->setHeader('Location', $dirname . '/install.php'); $response->setBody('The application is not installed. ' . 'You are going to be redirected to the installation page.'); }
function testRequireLogin() { $response = new Response(); $bearer = new Bearer('Dagger', new Request(), $response); $bearer->requireLogin(); $this->assertEquals('Bearer realm="Dagger"', $response->getHeader('WWW-Authenticate')); $this->assertEquals(401, $response->getStatus()); }
/** * Log exception * */ public function logException(\Exception $ex) { $exceptionClass = get_class($ex); $level = \OCP\Util::FATAL; if (isset($this->nonFatalExceptions[$exceptionClass])) { $level = \OCP\Util::DEBUG; } $message = $ex->getMessage(); if ($ex instanceof Exception) { if (empty($message)) { $response = new Response($ex->getHTTPCode()); $message = $response->getStatusText(); } $message = "HTTP/1.1 {$ex->getHTTPCode()} {$message}"; } $exception = ['Message' => $message, 'Code' => $ex->getCode(), 'Trace' => $ex->getTraceAsString(), 'File' => $ex->getFile(), 'Line' => $ex->getLine()]; $this->logger->log($level, 'Exception: ' . json_encode($exception), ['app' => $this->appName]); }
/** * @param \Sabre\HTTP\Response $response * @return void */ public function sendResponse(Response $response) { // we need to copy the body since we close the source stream $copyStream = fopen('php://temp', 'r+'); if (is_string($response->getBody())) { fwrite($copyStream, $response->getBody()); } else { if (is_resource($response->getBody())) { stream_copy_to_stream($response->getBody(), $copyStream); } } rewind($copyStream); $this->response = new Response($response->getStatus(), $response->getHeaders(), $copyStream); }
/** * @param Request $request * @param SabreResponse $response * @param string $responseBody */ private function logIt(Request $request, SabreResponse $response, $responseBody) { $this->get('logger')->info('------------------------ METHOD -------------------------'); $this->get('logger')->info($request->getMethod()); $this->get('logger')->info('------------------------ REQUEST ------------------------'); foreach ($request->headers->all() as $key => $value) { if (is_array($value)) { $this->get('logger')->info($key . ' => ' . implode(', ', $value)); } else { $this->get('logger')->info($key . ' => ' . $value); } } $this->get('logger')->info('------------------------ RESPONSE -----------------------'); $this->get('logger')->info($response->__toString()); $this->get('logger')->info($responseBody); $this->get('logger')->info('------------------------ END ----------------------------'); }
private function getServerTokens($qop = Digest::QOP_AUTH) { $this->auth->requireLogin(); switch ($qop) { case Digest::QOP_AUTH: $qopstr = 'auth'; break; case Digest::QOP_AUTHINT: $qopstr = 'auth-int'; break; default: $qopstr = 'auth,auth-int'; break; } $test = preg_match('/Digest realm="' . self::REALM . '",qop="' . $qopstr . '",nonce="([0-9a-f]*)",opaque="([0-9a-f]*)"/', $this->response->getHeader('WWW-Authenticate'), $matches); $this->assertTrue($test == true, 'The WWW-Authenticate response didn\'t match our pattern. We received: ' . $this->response->getHeader('WWW-Authenticate')); $nonce = $matches[1]; $opaque = $matches[2]; // Reset our environment $this->setUp(); $this->auth->setQOP($qop); return array($nonce, $opaque); }
/** * Creates the response object * * @param string|int $status * @param array $headers * @param resource $body * @return void */ function __construct($status = null, array $headers = null, $body = null) { parent::__construct($status, $headers, $body); // a JMAP response is always application/json $this->setHeader('Content-Type', 'application/json'); }
/** * Constructor. * * @param StreamedResponse $response */ public function __construct(StreamedResponse $response) { parent::__construct($response->getStatusCode(), $response->headers->all()); $this->response = $response; }
/** * This simple example shows the capability of Request and Response objects to * serialize themselves as strings. * * This is mainly useful for debugging purposes. * * @copyright Copyright (C) 2009-2015 fruux GmbH (https://fruux.com/). * @author Evert Pot (http://evertpot.com/) * @license http://sabre.io/license/ Modified BSD License */ use Sabre\HTTP\Request; use Sabre\HTTP\Response; // Find the autoloader $paths = [__DIR__ . '/../vendor/autoload.php', __DIR__ . '/../../../autoload.php', __DIR__ . '/vendor/autoload.php']; foreach ($paths as $path) { if (file_exists($path)) { include $path; break; } } $request = new Request('POST', '/foo'); $request->setHeaders(['Host' => 'example.org', 'Content-Type' => 'application/json']); $request->setBody(json_encode(['foo' => 'bar'])); echo $request; echo "\r\n\r\n"; $response = new Response(424); $response->setHeaders(['Content-Type' => 'text/plain', 'Connection' => 'close']); $response->setBody("ABORT! ABORT!"); echo $response; echo "\r\n";
public function __construct() { parent::__construct(); static::setStatus(200); }
use Sabre\Katana\Server\Installer; use Sabre\Katana\Configuration; use Sabre\HTTP; use Hoa\Router; use Hoa\Dispatcher; use Hoa\Eventsource; use Hoa\File; /** * This file aims at installing the application. * * @copyright Copyright (C) 2015 fruux GmbH (https://fruux.com/). * @author Ivan Enderlin * @license GNU Affero General Public License, Version 3. */ $request = HTTP\Sapi::getRequest(); $response = new HTTP\Response(); /** * If the application has already been installed, redirect to the index. */ if (true === Installer::isInstalled()) { echo file_get_contents(SABRE_KATANA_PREFIX . '/resource/view/install_done.html'); return; } /** * If dependencies have not been installed, we print a specific message. */ if (true === Installer::isDirectoryEmpty(SABRE_KATANA_PREFIX . '/public/static/vendor/')) { echo file_get_contents(SABRE_KATANA_PREFIX . '/resource/view/install_bower.html'); return; } /**
<?php use Sabre\HTTP; require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../bootstrap/bootstrap.php'; if (file_exists(app_path() . '/' . request()->getPath() . '.php')) { require_once app_path() . '/' . request()->getPath() . '.php'; } elseif (file_exists(app_path() . '/' . request()->getPath() . '/index.php')) { require_once app_path() . '/' . request()->getPath() . '/index.php'; } else { $response = new HTTP\Response(); $response->setStatus(404); $response->setBody('Page not found'); HTTP\Sapi::sendResponse($response); }
/** * Parses the result of a curl call in a format that's a bit more * convenient to work with. * * The method returns an array with the following elements: * * status - one of the 3 STATUS constants. * * curl_errno - A curl error number. Only set if status is * STATUS_CURLERROR. * * curl_errmsg - A current error message. Only set if status is * STATUS_CURLERROR. * * response - Response object. Only set if status is STATUS_SUCCESS, or * STATUS_HTTPERROR. * * http_code - HTTP status code, as an int. Only set if Only set if * status is STATUS_SUCCESS, or STATUS_HTTPERROR * * @param string $response * @param resource $curlHandle * @return Response */ protected function parseCurlResult($response, $curlHandle) { list($curlInfo, $curlErrNo, $curlErrMsg) = $this->curlStuff($curlHandle); if ($curlErrNo) { return ['status' => self::STATUS_CURLERROR, 'curl_errno' => $curlErrNo, 'curl_errmsg' => $curlErrMsg]; } $headerBlob = substr($response, 0, $curlInfo['header_size']); // In the case of 204 No Content, strlen($response) == $curlInfo['header_size]. // This will cause substr($response, $curlInfo['header_size']) return FALSE instead of NULL // An exception will be thrown when calling getBodyAsString then $responseBody = substr($response, $curlInfo['header_size']) ?: null; unset($response); // In the case of 100 Continue, or redirects we'll have multiple lists // // of headers for each separate HTTP response. We can easily split this // because they are separated by \r\n\r\n $headerBlob = explode("\r\n\r\n", trim($headerBlob, "\r\n")); // We only care about the last set of headers $headerBlob = $headerBlob[count($headerBlob) - 1]; // Splitting headers $headerBlob = explode("\r\n", $headerBlob); $response = new Response(); $response->setStatus($curlInfo['http_code']); foreach ($headerBlob as $header) { $parts = explode(':', $header, 2); if (count($parts) == 2) { $response->addHeader(trim($parts[0]), trim($parts[1])); } } $response->setBody($responseBody); $httpCode = intval($response->getStatus()); return ['status' => $httpCode >= 400 ? self::STATUS_HTTPERROR : self::STATUS_SUCCESS, 'response' => $response, 'http_code' => $httpCode]; }
/** * */ protected function sendAuthSuccess(Response $response, $accessToken = null) { // mandatory JMAP API endpoints $routes = ['apiUrl' => '!undefined', 'uploadUrl' => '!undefined', 'downloadUrl' => '!undefined', 'eventSourceUrl' => '!undefined']; // collect service endpoint routes for the registered processors foreach ($this->ctrl->processors as $processor) { $routes = array_merge($routes, $processor->getJmapRoutes()); } // send service endpoint URLs $result = []; foreach ($routes as $key => $route) { $result[$key] = $this->ctrl->url($route, true); } if (!empty($accessToken)) { $result['accessToken'] = $accessToken; } if ($this->session && $this->session->get('Auth\\identity')) { $result['username'] = $this->session->get('Auth\\identity')->username; } $status = $accessToken ? 201 : 200; $this->ctrl->emit('jmap:auth:success', [['result' => &$result, 'status' => &$status, 'processor' => $this]]); $response->setBody(json_encode($result)); $response->setStatus($status); }
* @copyright Copyright (C) 2009-2015 fruux GmbH (https://fruux.com/). * @author Evert Pot (http://evertpot.com/) * @license http://sabre.io/license/ Modified BSD License */ $userList = ["user1" => "password", "user2" => "password"]; use Sabre\HTTP\Sapi; use Sabre\HTTP\Response; use Sabre\HTTP\Auth; // Find the autoloader $paths = [__DIR__ . '/../vendor/autoload.php', __DIR__ . '/../../../autoload.php', __DIR__ . '/vendor/autoload.php']; foreach ($paths as $path) { if (file_exists($path)) { include $path; break; } } $request = Sapi::getRequest(); $response = new Response(); $basicAuth = new Auth\Basic("Locked down area", $request, $response); if (!($userPass = $basicAuth->getCredentials())) { // No username or password given $basicAuth->requireLogin(); } elseif (!isset($userList[$userPass[0]]) || $userList[$userPass[0]] !== $userPass[1]) { // Username or password are incorrect $basicAuth->requireLogin(); } else { // Success ! $response->setBody('You are logged in!'); } // Sending the response Sapi::sendResponse($response);
function test401() { $this->auth->requireLogin(); $test = preg_match('/^AWS$/', $this->response->getHeader('WWW-Authenticate'), $matches); $this->assertTrue($test == true, 'The WWW-Authenticate response didn\'t match our pattern'); }
/** * Sends compiled view * @param string $tpl_name Name of the template (in "dot" notation) * @param array $data Array containing your data; empty by default * @param integer $status_code HTTP status code for the response; 200 by default */ function view($tpl_name, $data = [], $status_code = 200) { $response = new HTTP\Response(); $response->setStatus($status_code); $response->setBody(twig()->render($tpl_name, $data)); HTTP\Sapi::sendResponse($response); }
/** * * @throws ProcessorException */ public function processPOST(Request $request, Response $response) { // check authentication status $auth_status = Auth::checkJmapAuth($request, $identity); if ($auth_status !== 200) { return $response->setStatus($auth_status); } // set authenticated identity to controller $this->ctrl->identity = $identity; // replace response object with a JMAP response $response = new \Roundcube\JMAP\Response($response->getStatus(), $response->getHeaders()); $this->ctrl->httpResponse = $response; // decode JMAP request data $json_input = json_decode($request->getBodyAsString(), true); if ($json_input === null) { throw new ProcessorException(400, "Invalid JSON request body"); } $this->ctrl->emit('jmap:query', [['query' => $json_input, 'auth' => &$this->ctrl->identity]]); // dispatch each query command to the registered providers foreach ($json_input as $cmd) { list($method, $args, $id) = $cmd; if (isset($this->methodmap[$method])) { foreach ($this->invokeProviders($method, $args) as $res) { $this->ctrl->emit('jmap:response', [['method' => $method, 'args' => $args, 'result' => &$res]]); $this->ctrl->emit('jmap:response:' . $method, [['args' => $args, 'result' => &$res]]); $response->addResponse($res[0], $res[1], $id); } } else { $res = ['error', ['type' => 'unknownMethod']]; $this->ctrl->emit('jmap:error', [['method' => $method, 'args' => $args, 'result' => &$res]]); $response->addResponse($res[0], $res[1], $id); } } $response->setStatus(200); }