Esempio n. 1
0
    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;
    }
Esempio n. 2
0
 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;
 }
Esempio n. 3
0
 /**
  * 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());
     }
 }
Esempio n. 4
0
File: Mock.php Progetto: seytar/psx
 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);
 }
Esempio n. 5
0
 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;
 }
Esempio n. 6
0
 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;
 }
Esempio n. 7
0
 public function request(RequestInterface $request, Options $options)
 {
     // check whether scheme is supported
     $supportedWrappers = array_intersect(array('http', 'https'), stream_get_wrappers());
     if (!in_array($request->getUri()->getScheme(), $supportedWrappers)) {
         throw new HandlerException('Unsupported stream wrapper');
     }
     // create context
     $context = stream_context_create();
     // assign http context parameters
     self::assignHttpContext($context, $request, $options);
     // disable follow location if not available
     if (!$this->hasFollowLocation) {
         stream_context_set_option($context, 'http', 'follow_location', 0);
     }
     // set ssl
     if ($options->getSsl() !== false && ($options->getSsl() === true || strcasecmp($request->getUri()->getScheme(), 'https') === 0)) {
         self::assignSslContext($context, $options);
     }
     // callback
     $callback = $options->getCallback();
     if (!empty($callback)) {
         call_user_func_array($callback, array($context, $request));
     }
     // open socket
     set_error_handler(__CLASS__ . '::handleError');
     $handle = fopen($request->getUri()->toString(), 'r', false, $context);
     restore_error_handler();
     // build response
     $response = ResponseParser::buildResponseFromHeader($http_response_header);
     if ($request->getMethod() != 'HEAD') {
         $response->setBody(new TempStream($handle));
     } else {
         $response->setBody(new StringStream());
     }
     return $response;
 }
Esempio n. 8
0
 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);
     }
 }
Esempio n. 9
0
 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);
     }
 }
Esempio n. 10
0
File: Socks.php Progetto: seytar/psx
 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');
     }
 }
Esempio n. 11
0
 /**
  * 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;
 }
Esempio n. 12
0
File: Curl.php Progetto: seytar/psx
 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;
 }