public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { $authorization = $request->getHeader('Authorization'); if (!empty($authorization)) { $parts = explode(' ', $authorization, 2); $type = isset($parts[0]) ? $parts[0] : null; $data = isset($parts[1]) ? $parts[1] : null; if ($type == 'Basic' && !empty($data)) { $data = base64_decode($data); $parts = explode(':', $data, 2); $username = isset($parts[0]) ? $parts[0] : null; $password = isset($parts[1]) ? $parts[1] : null; $result = call_user_func_array($this->isValidCallback, array($username, $password)); if ($result === true) { $this->callSuccess($response); $filterChain->handle($request, $response); } else { $this->callFailure($response); } } else { $this->callMissing($response); } } else { $this->callMissing($response); } }
public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { $signature = null; if ($request->hasHeader('Cookie')) { $cookies = Cookie::parseList($request->getHeader('Cookie')); foreach ($cookies as $cookie) { if ($cookie->getName() == self::COOKIE_NAME) { $data = $cookie->getValue(); $parts = explode('.', $data, 2); $payload = isset($parts[0]) ? $parts[0] : null; $signature = isset($parts[1]) ? $parts[1] : null; if (strcmp($signature, $this->generateSignature($payload)) === 0) { $request->setAttribute(self::COOKIE_NAME, $this->unserializeData($payload)); } else { // invalid signature } break; } } } $filterChain->handle($request, $response); $data = $request->getAttribute(self::COOKIE_NAME); if (!empty($data)) { $payload = $this->serializeData($data); $newSignature = $this->generateSignature($payload); // send only a new cookie if the data has changed if ($newSignature != $signature) { $response->addHeader('Set-Cookie', self::COOKIE_NAME . '=' . $payload . '.' . $newSignature); } } }
public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { $this->controller->onLoad(); switch ($request->getMethod()) { case 'DELETE': $this->controller->onDelete(); break; case 'GET': $this->controller->onGet(); break; case 'HEAD': $this->controller->onHead(); break; case 'OPTIONS': $this->controller->onOptions(); break; case 'POST': $this->controller->onPost(); break; case 'PUT': $this->controller->onPut(); break; case 'TRACE': $this->controller->onTrace(); break; } $method = $this->context->get(Context::KEY_METHOD); if (!empty($method) && is_callable([$this->controller, $method])) { call_user_func_array([$this->controller, $method], array()); } $this->controller->processResponse(); $filterChain->handle($request, $response); }
public function resolve(RequestInterface $request, Context $context) { $sql = 'SELECT id, methods, path, controller, config FROM fusio_routes WHERE status = 1 AND methods LIKE :method'; $method = $request->getMethod(); $pathMatcher = new PathMatcher($request->getUri()->getPath()); $result = $this->connection->fetchAll($sql, array('method' => '%' . $method . '%')); foreach ($result as $row) { $parameters = array(); if (in_array($method, explode('|', $row['methods'])) && $pathMatcher->match($row['path'], $parameters)) { $config = $row['config']; $config = !empty($config) ? unserialize($config) : null; $context->set(Context::KEY_FRAGMENT, $parameters); $context->set(Context::KEY_PATH, $row['path']); $context->set(Context::KEY_SOURCE, $row['controller']); $context->set('fusio.config', $config); $context->set('fusio.routeId', $row['id']); return $request; } } return null; }
public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { if (in_array($request->getMethod(), $this->requestMethods)) { $this->filter->handle($request, $response, $filterChain); } else { $filterChain->handle($request, $response); } }
protected function getBodyAsString(RequestInterface $request) { $body = Util::toString($request->getBody()); if (empty($body)) { $body = null; } return $body; }
public static function createRequest(RequestInterface $request) { $psrRequest = ServerRequestFactory::fromGlobals()->withUri($request->getUri())->withMethod($request->getMethod())->withBody($request->getBody()); foreach ($request->getHeaders() as $name => $values) { $psrRequest = $psrRequest->withHeader($name, $values); } return $psrRequest; }
public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { $userAgent = $request->getHeader('User-Agent'); if (!empty($userAgent)) { $filterChain->handle($request, $response); } else { throw new BadRequestException('Request must contain an User-Agent header'); } }
public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { $accept = $request->getHeader('Accept'); if (stripos($accept, 'text/html') !== false && is_file($this->file)) { $response->setHeader('Content-Type', 'text/html'); $response->getBody()->write(file_get_contents($this->file)); } else { $filterChain->handle($request, $response); } }
public function request(RequestInterface $request, Options $options) { $url = $request->getUri(); foreach ($this->resources as $resource) { $resourceUrl = new Url($resource['url']); if ($resource['method'] == $request->getMethod() && $resourceUrl->getHost() == $url->getHost() && $resourceUrl->getPath() == $url->getPath() && $resourceUrl->getQuery() == $url->getQuery()) { $response = $resource['handler']($request); return ResponseParser::convert($response); } } throw new Exception('Resource not available ' . $request->getMethod() . ' ' . $url); }
public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { $authorization = $request->getHeader('Authorization'); if (!empty($authorization)) { $parts = explode(' ', $authorization, 2); $type = isset($parts[0]) ? $parts[0] : null; $data = isset($parts[1]) ? $parts[1] : null; if ($type == 'OAuth' && !empty($data)) { $params = Authentication::decodeParameters($data); $params = array_map(array('\\PSX\\Oauth', 'urlDecode'), $params); // realm is not used in the base string unset($params['realm']); if (!isset($params['oauth_consumer_key'])) { throw new BadRequestException('Consumer key not set'); } if (!isset($params['oauth_token'])) { throw new BadRequestException('Token not set'); } if (!isset($params['oauth_signature_method'])) { throw new BadRequestException('Signature method not set'); } if (!isset($params['oauth_signature'])) { throw new BadRequestException('Signature not set'); } $consumer = call_user_func_array($this->consumerCallback, array($params['oauth_consumer_key'], $params['oauth_token'])); if ($consumer instanceof Consumer) { $signature = Oauth::getSignature($params['oauth_signature_method']); $method = $request->getMethod(); $url = $request->getUri(); $params = array_merge($params, $request->getUri()->getParameters()); if (strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) { $body = (string) $request->getBody(); $data = array(); parse_str($body, $data); $params = array_merge($params, $data); } $baseString = Oauth::buildBasestring($method, $url, $params); if ($signature->verify($baseString, $consumer->getConsumerSecret(), $consumer->getTokenSecret(), $params['oauth_signature']) !== false) { $this->callSuccess($response); $filterChain->handle($request, $response); } else { $this->callFailure($response); } } else { $this->callFailure($response); } } else { $this->callMissing($response); } } else { $this->callMissing($response); } }
public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { if ($request->hasHeader('Accept-Encoding')) { $acceptEncoding = $request->getHeader('Accept-Encoding'); if (strpos($acceptEncoding, 'gzip') !== false) { // the sender will compress the response if the content encoding // header is available $response->setHeader('Content-Encoding', 'gzip'); } } $filterChain->handle($request, $response); }
public function resolve(RequestInterface $request, Context $context) { $sql = 'SELECT id, methods, path, controller FROM fusio_routes WHERE status = :status '; $paths = ['backend', 'consumer', 'authorization', 'export', 'doc']; $found = false; $path = $request->getUri()->getPath(); $params = ['status' => TableRoutes::STATUS_ACTIVE]; // check whether we have a known system path foreach ($paths as $systemPath) { if (strpos($path, '/' . $systemPath) === 0) { $found = true; $sql .= 'AND path LIKE :path'; $params['path'] = '/' . $systemPath . '%'; break; } } // if not we only want to search the user routes and exclude all system // paths if (!$found) { foreach ($paths as $index => $systemPath) { $key = 'path_' . $index; $sql .= 'AND path NOT LIKE :' . $key . ' '; $params[$key] = '/' . $systemPath . '%'; } } $method = $request->getMethod(); $pathMatcher = new PathMatcher($path); $result = $this->connection->fetchAll($sql, $params); foreach ($result as $row) { $parameters = array(); if (in_array($method, explode('|', $row['methods'])) && $pathMatcher->match($row['path'], $parameters)) { $context->set(Context::KEY_FRAGMENT, $parameters); $context->set(Context::KEY_PATH, $row['path']); $context->set(Context::KEY_SOURCE, $row['controller']); $context->set('fusio.routeId', $row['id']); return $request; } } return null; }
/** * Returns the writer wich gets used if no writer was explicit selected * * @return \PSX\Data\WriterInterface */ private function getPreferredWriter() { $parameters = $this->request->getUri()->getParameters(); $format = isset($parameters['format']) ? $parameters['format'] : null; if (!empty($format)) { return $this->writerFactory->getWriterByFormat($format, $this->getSupportedWriter()); } else { return $this->writerFactory->getWriterByContentType($this->request->getHeader('Accept'), $this->getSupportedWriter()); } }
public function resolve(RequestInterface $request, Context $context) { $routingCollection = $this->routingParser->getCollection(); $method = $request->getMethod(); $pathMatcher = new PathMatcher($request->getUri()->getPath()); foreach ($routingCollection as $routing) { $parameters = array(); if (in_array($method, $routing[RoutingCollection::ROUTING_METHODS]) && $pathMatcher->match($routing[RoutingCollection::ROUTING_PATH], $parameters)) { $source = $routing[RoutingCollection::ROUTING_SOURCE]; if ($source[0] == '~') { $request->setUri(new Uri(substr($source, 1))); return $this->resolve($request, $context); } $context->set(Context::KEY_PATH, $routing[RoutingCollection::ROUTING_PATH]); $context->set(Context::KEY_FRAGMENT, $parameters); $context->set(Context::KEY_SOURCE, $source); return $request; } } return null; }
public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { $authorization = $request->getHeader('Authorization'); if (!empty($authorization)) { $parts = explode(' ', $authorization, 2); $type = isset($parts[0]) ? $parts[0] : null; $accessToken = isset($parts[1]) ? $parts[1] : null; if ($type == 'Bearer' && !empty($accessToken)) { $result = call_user_func_array($this->accessCallback, array($accessToken)); if ($result === true) { $this->callSuccess($response); $filterChain->handle($request, $response); } else { $this->callFailure($response); } } else { $this->callMissing($response); } } else { $this->callMissing($response); } }
public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { $authorization = $request->getHeader('Authorization'); if (!empty($authorization)) { $parts = explode(' ', $authorization, 2); $type = isset($parts[0]) ? $parts[0] : null; $data = isset($parts[1]) ? $parts[1] : null; if ($type == 'Digest' && !empty($data)) { $params = Authentication::decodeParameters($data); $algo = isset($params['algorithm']) ? $params['algorithm'] : 'MD5'; $qop = isset($params['qop']) ? $params['qop'] : 'auth'; if (!$this->digest instanceof Digest) { throw new BadRequestException('Digest not available'); } if ($this->digest->getOpaque() != $params['opaque']) { throw new BadRequestException('Invalid opaque'); } // build ha1 $ha1 = call_user_func_array($this->ha1Callback, array($params['username'])); if ($algo == 'MD5-sess') { $ha1 = md5($ha1 . ':' . $this->digest->getNonce() . ':' . $params['cnonce']); } // build ha2 if ($qop == 'auth-int') { $ha2 = md5($request->getMethod() . ':' . $request->getUri()->getPath() . ':' . md5($request->getBody())); } else { $ha2 = md5($request->getMethod() . ':' . $request->getUri()->getPath()); } // build response if ($qop == 'auth' || $qop == 'auth-int') { $hash = md5($ha1 . ':' . $this->digest->getNonce() . ':' . $params['nc'] . ':' . $params['cnonce'] . ':' . $qop . ':' . $ha2); } else { $hash = md5($ha1 . ':' . $this->digest->getNonce() . ':' . $ha2); } if (strcmp($hash, $params['response']) === 0) { $this->callSuccess($response, $hash); $filterChain->handle($request, $response); } else { $this->callFailure($response); } } else { $this->callMissing($response); } } else { $this->callMissing($response); } }
/** * Returns an string which gets used by the cache as key. You can provide a * custom key generator function in the constructor to override this * behaviour * * @param \PSX\Http\RequestInterface $request * @return string */ protected function getKeyDefaultImpl(RequestInterface $request) { $url = $request->getUri(); $query = $url->getQuery(); $fragment = $url->getFragment(); if (empty($query) && empty($fragment)) { // we cache the request only if we have no query or fragment values return md5($url->getPath()); } return null; }
public static function assignHttpContext($context, RequestInterface $request, Options $options = null) { stream_context_set_option($context, 'http', 'method', $request->getMethod()); stream_context_set_option($context, 'http', 'protocol_version', $request->getProtocolVersion() ?: 1.1); // until chunked transfer encoding if fully implemented we remove the // header if ($request->hasHeader('Transfer-Encoding')) { $request->removeHeader('Transfer-Encoding'); } // set header $headers = implode(Http::$newLine, ResponseParser::buildHeaderFromMessage($request)); stream_context_set_option($context, 'http', 'header', $headers); // set body $body = $request->getBody(); if ($body !== null && !in_array($request->getMethod(), array('HEAD', 'GET'))) { stream_context_set_option($context, 'http', 'content', (string) $body); } if ($options !== null) { // set proxy $proxy = $options->getProxy(); if (!empty($proxy)) { stream_context_set_option($context, 'http', 'proxy', $proxy); } // set follow location stream_context_set_option($context, 'http', 'follow_location', (int) $options->getFollowLocation()); stream_context_set_option($context, 'http', 'max_redirects', $options->getMaxRedirects()); // set timeout $timeout = $options->getTimeout(); if (!empty($timeout)) { stream_context_set_option($context, 'http', 'timeout', $timeout); } } }
/** * @param \PSX\Http\RequestInterface $request * @return string */ public static function buildStatusLine(RequestInterface $request) { $method = $request->getMethod(); $target = $request->getRequestTarget(); $protocol = $request->getProtocolVersion(); if (empty($target)) { throw new Exception('Target not set'); } $method = !empty($method) ? $method : 'GET'; $protocol = !empty($protocol) ? $protocol : 'HTTP/1.1'; return $method . ' ' . $target . ' ' . $protocol; }
/** * @param string $name * @return null|string */ public function getHeader($name) { return $this->request->getHeader($name); }
public function request(RequestInterface $request, Options $options) { $context = stream_context_create(); // ssl $scheme = null; if ($options->getSsl() !== false && ($options->getSsl() === true || strcasecmp($request->getUri()->getScheme(), 'https') === 0)) { $transports = stream_get_transports(); if (in_array('tls', $transports)) { $scheme = 'tls'; } elseif (in_array('ssl', $transports)) { $scheme = 'ssl'; } else { throw new NotSupportedException('https is not supported'); } Stream::assignSslContext($context, $options); } else { $scheme = 'tcp'; } // port $port = $request->getUri()->getPort(); if (empty($port)) { $port = getservbyname($request->getUri()->getScheme(), 'tcp'); } // open socket set_error_handler(__CLASS__ . '::handleError'); $timeout = ini_get('default_socket_timeout'); $handle = stream_socket_client($scheme . '://' . $request->getUri()->getHost() . ':' . $port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context); restore_error_handler(); if ($handle !== false) { // timeout $timeout = $options->getTimeout(); if (!empty($timeout)) { stream_set_timeout($handle, $timeout); } // callback $callback = $options->getCallback(); if (!empty($callback)) { call_user_func_array($callback, array($handle, $request)); } // write header $headers = ResponseParser::buildHeaderFromMessage($request); fwrite($handle, Http\RequestParser::buildStatusLine($request) . Http::$newLine); foreach ($headers as $header) { fwrite($handle, $header . Http::$newLine); } fwrite($handle, Http::$newLine); fflush($handle); // write body $body = $request->getBody(); if ($body !== null && !in_array($request->getMethod(), array('HEAD', 'GET'))) { if ($request->getHeader('Transfer-Encoding') == 'chunked') { while (!$body->eof()) { $chunk = $body->read($this->chunkSize); $len = strlen($chunk); if ($len > 0) { fwrite($handle, dechex($len) . Http::$newLine . $chunk . Http::$newLine); fflush($handle); } } fwrite($handle, '0' . Http::$newLine . Http::$newLine); fflush($handle); } else { fwrite($handle, (string) $body); fflush($handle); } } // read header $headers = array(); do { $header = trim(fgets($handle)); if (!empty($header)) { $headers[] = $header; } } while (!empty($header)); // check for timeout $meta = stream_get_meta_data($handle); if ($meta['timed_out']) { throw new HandlerException('Connection timeout'); } // build response $response = ResponseParser::buildResponseFromHeader($headers); // create stream $contentLength = (int) $response->getHeader('Content-Length'); $chunkedEncoding = $response->getHeader('Transfer-Encoding') == 'chunked'; if ($request->getMethod() != 'HEAD') { $response->setBody(new SocksStream($handle, $contentLength, $chunkedEncoding)); } else { fclose($handle); $response->setBody(new StringStream()); } return $response; } else { throw new HandlerException(!empty($errstr) ? $errstr : 'Could not open socket'); } }
public function request(RequestInterface $request, Options $options) { $this->header = array(); $this->body = fopen('php://temp', 'r+'); $handle = curl_init($request->getUri()->toString()); curl_setopt($handle, CURLOPT_HEADER, false); curl_setopt($handle, CURLOPT_RETURNTRANSFER, false); curl_setopt($handle, CURLOPT_HEADERFUNCTION, array($this, 'header')); curl_setopt($handle, CURLOPT_WRITEFUNCTION, array($this, 'write')); curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $request->getMethod()); // set header $headers = ResponseParser::buildHeaderFromMessage($request); if (!empty($headers)) { if (!$request->hasHeader('Expect')) { $headers[] = 'Expect:'; } curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); } // set body $body = $request->getBody(); if ($body !== null && !in_array($request->getMethod(), array('HEAD', 'GET'))) { if ($request->getHeader('Transfer-Encoding') == 'chunked') { curl_setopt($handle, CURLOPT_UPLOAD, true); curl_setopt($handle, CURLOPT_READFUNCTION, function ($handle, $fd, $length) use($body) { return $body->read($length); }); } else { curl_setopt($handle, CURLOPT_POSTFIELDS, (string) $body); } } // set proxy $proxy = $options->getProxy(); if (!empty($proxy)) { curl_setopt($handle, CURLOPT_PROXY, $proxy); } // set follow location curl_setopt($handle, CURLOPT_FOLLOWLOCATION, $options->getFollowLocation() && $this->hasFollowLocation); curl_setopt($handle, CURLOPT_MAXREDIRS, $options->getMaxRedirects()); // set ssl if ($options->getSsl() !== false && ($options->getSsl() === true || strcasecmp($request->getUri()->getScheme(), 'https') === 0)) { $caPath = $options->getCaPath(); if (!empty($caPath)) { curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 2); if (is_file($caPath)) { curl_setopt($handle, CURLOPT_CAINFO, $caPath); } elseif (is_dir($caPath)) { curl_setopt($handle, CURLOPT_CAPATH, $caPath); } } else { curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0); } } // set timeout $timeout = $options->getTimeout(); if (!empty($timeout)) { curl_setopt($handle, CURLOPT_TIMEOUT, $timeout); } // callback $callback = $options->getCallback(); if (!empty($callback)) { call_user_func_array($callback, array($handle, $request)); } curl_exec($handle); // if follow location is active modify the header since all headers from // each redirection are included if ($options->getFollowLocation() && $this->hasFollowLocation) { $positions = array(); foreach ($this->header as $key => $header) { if (substr($header, 0, 5) == 'HTTP/') { $positions[] = $key; } } if (count($positions) > 1) { $this->header = array_slice($this->header, end($positions) - 1); } } if (curl_errno($handle)) { throw new HandlerException('Curl error: ' . curl_error($handle)); } curl_close($handle); // build response rewind($this->body); $response = ResponseParser::buildResponseFromHeader($this->header); if ($request->getMethod() != 'HEAD') { $response->setBody(new TempStream($this->body)); } else { $response->setBody(new StringStream()); } return $response; }