Esempio n. 1
0
 /**
  * @param \Zend\Uri\Uri $uri
  *
  * @return mixed False if service or namespace nofound
  */
 public function analyse(Uri $uri)
 {
     $service = $this->serviceManager->searchService($uri->toString());
     if (false === $service) {
         return false;
     }
     $namespace = $this->serviceManager->getServiceNamespace($service);
     if (null === $namespace || $namespace === '') {
         return false;
     }
     $clear = $namespace::clearUri($uri);
     if (false === $clear) {
         return false;
     }
     $keyCache = $uri->toString();
     // cache because the analyse process requires a lot of resources
     $analyser = $this->cache->get($keyCache);
     if (null !== $analyser) {
         return $analyser;
     }
     // analyse process
     $analyser = new $namespace();
     $analyser->parse($uri);
     return $this->cache->set($keyCache, $analyser);
 }
Esempio n. 2
0
 public function open($timeOut = null)
 {
     /**
      * @var $that self
      */
     $that = new FullAccessWrapper($this);
     $uri = new Uri($this->url);
     $isSecured = 'wss' === $uri->getScheme();
     $defaultPort = $isSecured ? 443 : 80;
     $connector = new Connector($this->loop, $this->dns, $this->streamOptions);
     if ($isSecured) {
         $connector = new \React\SocketClient\SecureConnector($connector, $this->loop);
     }
     $deferred = new Deferred();
     $connector->create($uri->getHost(), $uri->getPort() ?: $defaultPort)->then(function (\React\Stream\Stream $stream) use($that, $uri, $deferred, $timeOut) {
         if ($timeOut) {
             $timeOutTimer = $that->loop->addTimer($timeOut, function () use($promise, $stream, $that) {
                 $stream->close();
                 $that->logger->notice("Timeout occured, closing connection");
                 $that->emit("error");
                 $promise->reject("Timeout occured");
             });
         } else {
             $timeOutTimer = null;
         }
         $transport = new WebSocketTransportHybi($stream);
         $transport->setLogger($that->logger);
         $that->transport = $transport;
         $that->stream = $stream;
         $stream->on("close", function () use($that) {
             $that->isClosing = false;
             $that->state = WebSocket::STATE_CLOSED;
         });
         // Give the chance to change request
         $transport->on("request", function (Request $handshake) use($that) {
             $that->emit("request", func_get_args());
         });
         $transport->on("handshake", function (Handshake $handshake) use($that) {
             $that->request = $handshake->getRequest();
             $that->response = $handshake->getRequest();
             $that->emit("handshake", array($handshake));
         });
         $transport->on("connect", function () use(&$state, $that, $transport, $timeOutTimer, $deferred) {
             if ($timeOutTimer) {
                 $timeOutTimer->cancel();
             }
             $deferred->resolve($transport);
             $that->state = WebSocket::STATE_CONNECTED;
             $that->emit("connect");
         });
         $transport->on('message', function ($message) use($that, $transport) {
             $that->emit("message", array("message" => $message));
         });
         $transport->initiateHandshake($uri);
         $that->state = WebSocket::STATE_HANDSHAKE_SENT;
     }, function ($reason) use($that) {
         $that->logger->err($reason);
     });
     return $deferred->promise();
 }
Esempio n. 3
0
    /**
     * Create a URI from a string
     *
     * @param  string $uriString
     * @param  string $defaultScheme
     * @throws Exception\InvalidArgumentException
     * @return \Zend\Uri\Uri
     */
    static public function factory($uriString, $defaultScheme = null)
    {
        if (!is_string($uriString)) {
            throw new Exception\InvalidArgumentException(sprintf(
                'Expecting a string, received "%s"',
                (is_object($uriString) ? get_class($uriString) : gettype($uriString))
            ));
        }

        $uri    = new Uri($uriString);
        $scheme = strtolower($uri->getScheme());
        if (!$scheme && $defaultScheme) {
            $scheme = $defaultScheme;
        }

        if ($scheme && isset(static::$schemeClasses[$scheme])) {
            $class = static::$schemeClasses[$scheme];
            $uri = new $class($uri);
            if (! $uri instanceof Uri) {
                throw new Exception\InvalidArgumentException(sprintf(
                    'class "%s" registered for scheme "%s" is not a subclass of Zend\Uri\Uri',
                    $class,
                    $scheme
                ));
            }
        }

        return $uri;
    }
 protected function getDomain($uriString = null)
 {
     if ($uriString == null) {
         $uriString = $this->getRequest()->getUri();
     }
     $uri = new Uri($uriString);
     return $uri->getHost();
 }
 protected function constructRedirectUri($uri = null, array $query = array())
 {
     $uri = new Uri($uri);
     if (!empty($query)) {
         $query = $uri->getQueryAsArray() + $query;
         $uri->setQuery($query);
     }
     return $uri;
 }
Esempio n. 6
0
 protected function getFirstSegmentInPath(Uri $uri, $base = null)
 {
     $path = $uri->getPath();
     if ($base) {
         $path = substr($path, strlen($base));
     }
     $parts = explode('/', trim($path, '/'));
     $locale = array_shift($parts);
     return $locale;
 }
 /**
  * {@inheritdoc}
  */
 public function configureUri(Uri $baseUri, $name, $id = null)
 {
     $basePath = $baseUri->getPath();
     $resourcePath = rtrim($basePath, '/') . '/' . $name;
     if ($id) {
         $resourcePath .= '/' . $id;
     }
     $baseUri->setPath($resourcePath);
     return $baseUri;
 }
Esempio n. 8
0
 /**
  * Get a list of thumbs from a URI
  * @param string $uri
  * @param integer $limit
  * @return array
  */
 public function getThumbs($uri, $limit = 5)
 {
     $validator = new \Zend\Validator\Uri(array('allowRelative' => false));
     $return = array();
     if ($validator->isValid($uri)) {
         $parseInfo = parent::parse($uri);
         switch ($parseInfo->host) {
             // Youtube.com
             case "www.youtube.com":
                 $queryArray = array();
                 parse_str($parseInfo->query, $queryArray);
                 if (isset($queryArray['v'])) {
                     $return = array("http://img.youtube.com/vi/" . $queryArray['v'] . "/0.jpg", "http://img.youtube.com/vi/" . $queryArray['v'] . "/1.jpg", "http://img.youtube.com/vi/" . $queryArray['v'] . "/2.jpg", "http://img.youtube.com/vi/" . $queryArray['v'] . "/3.jpg");
                 }
                 break;
                 // Dailymotion.com
             // Dailymotion.com
             case "www.dailymotion.com":
                 if (strpos($parseInfo->path, "/video") !== false) {
                     $return = array('http://www.dailymotion.com/thumbnail' . $parseInfo->path);
                 }
                 break;
                 // Vimeo.com
             // Vimeo.com
             case "vimeo.com":
                 $id = str_replace("/", "", $parseInfo->path);
                 $data = \Zend\Json\Json::decode(file_get_contents("http://vimeo.com/api/v2/video/{$id}.json"));
                 $return = array($data[0]->thumbnail_medium);
                 break;
                 // others webpage
             // others webpage
             default:
                 /**
                  * Credit to http://www.bitrepository.com
                  * http://www.bitrepository.com/extract-images-from-an-url.html
                  */
                 // Fetch page
                 $string = $this->fetchPage($uri);
                 $out = array();
                 // Regex for SRC Value
                 $image_regex_src_url = '/<img[^>]*' . 'src=[\\"|\'](.*)[\\"|\']/Ui';
                 preg_match_all($image_regex_src_url, $string, $out, PREG_PATTERN_ORDER);
                 $return = $out[1];
                 for ($i = 0; $i < count($return); $i++) {
                     $tUri = new Uri();
                     $parseInfoThumb = $tUri->parse($return[$i]);
                     if (!$parseInfoThumb->isAbsolute()) {
                         $return[$i] = $parseInfo->scheme . "://" . $parseInfo->host . "" . $return[$i];
                     }
                 }
         }
     }
     // check && return
     return array_slice($return, 0, $limit);
 }
Esempio n. 9
0
 /**
  * Constructor
  *
  * @param OAuth\Consumer $consumer
  * @param string $url
  * @param string $method
  * @param array $params
  */
 public function __construct($consumer, $url, $method, $params = array())
 {
     $this->_consumer = $consumer;
     $this->_method = $method;
     //normalize the uri: remove the query params
     //and store them alonside the oauth and user params
     $this->_uri = new \MediaCore\Uri($url);
     $this->_unencodedQueryParams = $this->_uri->getQueryAsArray(true);
     $this->_uri->setQuery('');
     $this->_params = $params;
 }
 private function validateUrl($config, $name, $base = '')
 {
     if (!isset($config['idp_url'][$name])) {
         throw new \InvalidArgumentException('universibo_sso.idp_url.' . $name . ' is not set!');
     }
     try {
         $uri = new Uri($base . $config['idp_url'][$name]);
         return $uri->toString();
     } catch (\Exception $e) {
         throw new \InvalidArgumentException('universibo_sso.idp_url.' . $name . ' is not valid!');
     }
 }
Esempio n. 11
0
 /**
  * @param                    $method
  * @param                    $uri
  * @param array              $options
  * @param null|bool|\Closure $successCallback
  * @param null|bool|\Closure $failCallback
  *
  * @return bool|null|\StdClass
  * @throws Exception
  */
 public function request($method, $uri, $options = [], $successCallback = null, $failCallback = null)
 {
     if (!$successCallback && !$failCallback) {
         $json = null;
         // If there's no callbacks defined we assume this is a RESTful request
         Logger::getInstance()->debug($method . ' ' . $uri . ' ' . json_encode($options));
         $options = array_merge($this->defaultOptions, $options);
         $guzzle = new GuzzleHttp\Client(['base_uri' => self::BASE_URL_REST]);
         $res = $guzzle->request($method, $uri, $options);
         if ($res->getHeader('content-type')[0] == 'application/json') {
             $contents = $res->getBody()->getContents();
             Logger::getInstance()->debug($contents);
             $json = json_decode($contents);
         } else {
             throw new Exception("Server did not send JSON. Response was \"{$res->getBody()->getContents()}\"");
         }
         return $json;
     } else {
         // Use the STREAM API end point
         $Uri = new Uri(self::BASE_URL_STREAM);
         $Uri->setUserInfo($this->defaultOptions['auth'][0] . ':' . $this->defaultOptions['auth'][1]);
         $Uri->setPath($uri);
         if (isset($options['query'])) {
             $Uri->setQuery($options['query']);
         }
         $WSClient = new WebSocket\Client($Uri);
         Logger::getInstance()->debug($Uri);
         if (!$successCallback instanceof \Closure) {
             $successCallback = function ($response) {
                 $info = json_decode($response);
                 if (property_exists($info, 'output')) {
                     Logger::getInstance()->info(json_decode($response)->output);
                 } elseif ($info->type == 'error') {
                     // output error info
                     Logger::getInstance()->info($info->message);
                 }
             };
         }
         if (!$failCallback instanceof \Closure) {
             $failCallback = function (\Exception $exception) {
                 Logger::getInstance()->info($exception->getMessage());
             };
         }
         try {
             while ($response = $WSClient->receive()) {
                 $successCallback($response);
             }
         } catch (\Exception $e) {
             $failCallback($e);
         }
         return true;
     }
 }
 /**
  * Send request to the proxy server with streaming support
  *
  * @param string        $method
  * @param \Zend\Uri\Uri $uri
  * @param string        $http_ver
  * @param array         $headers
  * @param string        $body
  * @return string Request as string
  */
 public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
 {
     // If no proxy is set, throw an error
     if (!$this->config['proxy_host']) {
         throw new Adapter\Exception('No proxy host set!');
     }
     // Make sure we're properly connected
     if (!$this->socket) {
         throw new Adapter\Exception('Trying to write but we are not connected');
     }
     $host = $this->config['proxy_host'];
     $port = $this->config['proxy_port'];
     if ($this->connected_to[0] != $host || $this->connected_to[1] != $port) {
         throw new Adapter\Exception('Trying to write but we are connected to the wrong proxy ' . 'server');
     }
     // Add Proxy-Authorization header
     if ($this->config['proxy_user'] && !isset($headers['proxy-authorization'])) {
         $headers['proxy-authorization'] = \Zend\Http\Client::encodeAuthHeader($this->config['proxy_user'], $this->config['proxy_pass'], $this->config['proxy_auth']);
     }
     // if we are proxying HTTPS, preform CONNECT handshake with the proxy
     if ($uri->getScheme() == 'https' && !$this->negotiated) {
         $this->connectHandshake($uri->getHost(), $uri->getPort(), $http_ver, $headers);
         $this->negotiated = true;
     }
     // Save request method for later
     $this->method = $method;
     // Build request headers
     $request = "{$method} {$uri->toString()} HTTP/{$http_ver}\r\n";
     // Add all headers to the request string
     foreach ($headers as $k => $v) {
         if (is_string($k)) {
             $v = "{$k}: {$v}";
         }
         $request .= "{$v}\r\n";
     }
     $request .= "\r\n";
     // Send the request headers
     if (!@fwrite($this->socket, $request)) {
         throw new Adapter\Exception('Error writing request to proxy server');
     }
     //read from $body, write to socket
     while ($body->hasData()) {
         if (!@fwrite($this->socket, $body->read(self::CHUNK_SIZE))) {
             throw new Adapter\Exception('Error writing request to server');
         }
     }
     return 'Large upload, request is not cached.';
 }
Esempio n. 13
0
 /**
  * Method call overload
  *
  * Allows calling REST actions as object methods; however, you must
  * follow-up by chaining the request with a request to an HTTP request
  * method (post, get, delete, put):
  * <code>
  * $response = $rest->sayHello('Foo', 'Manchu')->get();
  * </code>
  *
  * Or use them together, but in sequential calls:
  * <code>
  * $rest->sayHello('Foo', 'Manchu');
  * $response = $rest->get();
  * </code>
  *
  * @param string $method Method name
  * @param array $args Method args
  * @return \Zend\Rest\Client\RestClient_Result|\Zend\Rest\Client\RestClient \Zend\Rest\Client\RestClient if using
  * a remote method, Zend_Rest_Client_Result if using an HTTP request method
  */
 public function __call($method, $args)
 {
     $methods = array('post', 'get', 'delete', 'put');
     if (in_array(strtolower($method), $methods)) {
         if (!isset($args[0])) {
             $args[0] = $this->_uri->getPath();
         }
         $this->_data['rest'] = 1;
         $data = array_slice($args, 1) + $this->_data;
         $response = $this->{'rest' . $method}($args[0], $data);
         $this->_data = array();
         //Initializes for next Rest method.
         return new Result($response->getBody());
     } else {
         // More than one arg means it's definitely a Zend_Rest_Server
         if (count($args) == 1) {
             // Uses first called function name as method name
             if (!isset($this->_data['method'])) {
                 $this->_data['method'] = $method;
                 $this->_data['arg1'] = $args[0];
             }
             $this->_data[$method] = $args[0];
         } else {
             $this->_data['method'] = $method;
             if (count($args) > 0) {
                 foreach ($args as $key => $arg) {
                     $key = 'arg' . $key;
                     $this->_data[$key] = $arg;
                 }
             }
         }
         return $this;
     }
 }
 public static function isDocumentHref($href)
 {
     if (empty($href) || stripos($href, 'mail') !== false || stripos($href, '.pdf') !== false || stripos($href, '.ppt') !== false || substr($href, 0, 10) === 'javascript' || substr($href, 0, 1) === '#') {
         return false;
     }
     foreach (['%20', '='] as $c) {
         if (stripos($href, $c . 'http://') !== false) {
             return false;
         }
     }
     $zendUri = new Uri($href);
     if ($zendUri->isValid()) {
         return true;
     }
     return false;
 }
Esempio n. 15
0
 /**
  * Get clear uri.
  *
  * @static
  *
  * @param \Zend\Uri\Uri $uri
  *
  * @return boolean|\Zend\Uri\Uri False if uri is not auhorized
  */
 public static function clearUri(Uri $uri)
 {
     if ($uri->getScheme() !== 'http') {
         return false;
     }
     $query = $uri->getQueryAsArray();
     if (empty($query['v'])) {
         return false;
     }
     $uri->setQuery(array('v' => $query['v']));
     $uri->setHost('www.youtube.com');
     $uri->setPath('/watch');
     // clear
     $uri->setPort(0);
     $uri->setUserInfo('');
     $uri->setFragment('');
     return $uri;
 }
 /**
  * Generates an URI representing the authorization request.
  *
  * @param Request $request
  * @return string
  */
 public function createAuthorizationRequestUri(Request $request)
 {
     /* @var $clientInfo \InoOicClient\Client\ClientInfo */
     $clientInfo = $request->getClientInfo();
     if (!$clientInfo) {
         throw new \RuntimeException('Missing client info in request');
     }
     if (($endpointUri = $clientInfo->getAuthorizationEndpoint()) === null) {
         throw new Exception\MissingEndpointException('No endpoint specified');
     }
     $uri = new Uri($endpointUri);
     $params = array(Param::CLIENT_ID => $clientInfo->getClientId(), Param::REDIRECT_URI => $clientInfo->getRedirectUri(), Param::RESPONSE_TYPE => $this->arrayToSpaceDelimited($request->getResponseType()), Param::SCOPE => $this->arrayToSpaceDelimited($request->getScope()), Param::STATE => $request->getState());
     foreach ($params as $name => $value) {
         if (in_array($name, $this->requiredParams) && empty($value)) {
             throw new Exception\MissingFieldException($name);
         }
     }
     $uri->setQuery($params);
     return $uri->toString();
 }
Esempio n. 17
0
 /**
  * Get clear uri.
  *
  * @static
  *
  * @param \Zend\Uri\Uri $uri
  *
  * @return boolean|\Zend\Uri\Uri False if uri is not auhorized
  */
 public static function clearUri(Uri $uri)
 {
     if ($uri->getScheme() !== 'http') {
         return false;
     }
     $uri->setHost('www.vimeo.com');
     // clear
     $uri->setPort(0);
     $uri->setUserInfo('');
     $uri->setQuery('');
     $uri->setFragment('');
     return $uri;
 }
Esempio n. 18
0
 /**
  * Get Url
  *
  * @return string
  */
 public function getUrl()
 {
     if ($this->uri instanceof Uri) {
         $url = array('href' => $this->uri->toString());
         $query = $this->uri->getQueryAsArray();
         if (sizeof($query) > 0) {
             $url['query'] = $query;
         }
         return $url;
     }
     return;
 }
Esempio n. 19
0
 /**
  * Get clear uri.
  *
  * @static
  *
  * @param \Zend\Uri\Uri $uri
  *
  * @return boolean|\Zend\Uri\Uri False if uri is not auhorized
  */
 public static function clearUri(Uri $uri)
 {
     if ($uri->getScheme() !== 'http') {
         return false;
     }
     $paths = explode('/', $uri->getPath());
     $pathsCount = count($paths);
     if ($pathsCount < 2) {
         return false;
     }
     $type = $paths[$pathsCount - 2];
     if (!in_array($type, self::$typesAuthorized)) {
         return false;
     }
     $uri->setHost('www.deezer.com');
     // clear
     $uri->setPort(0);
     $uri->setUserInfo('');
     $uri->setQuery('');
     $uri->setFragment('');
     return $uri;
 }
Esempio n. 20
0
 /**
  * Execute geocoding
  * 
  * @param  Request $request
  * @return Response
  */
 public function geocode(Request $request)
 {
     if (null === $request) {
         throw new Exception\InvalidArgumentException('request');
     }
     $uri = new Uri();
     $uri->setHost(self::GOOGLE_MAPS_APIS_URL);
     $uri->setPath(self::GOOGLE_GEOCODING_API_PATH);
     $urlParameters = $request->getUrlParameters();
     if (null === $urlParameters) {
         throw new Exception\RuntimeException('Invalid URL parameters');
     }
     $uri->setQuery($urlParameters);
     $client = $this->getHttpClient();
     $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl');
     $client->resetParameters();
     $uri->setScheme("https");
     $client->setUri($uri->toString());
     $stream = $client->send();
     $body = Json::decode($stream->getBody(), Json::TYPE_ARRAY);
     $hydrator = new ArraySerializable();
     $response = new Response();
     $response->setRawBody($body);
     if (!isset($body['status'])) {
         throw new Exception\RuntimeException('Invalid status');
     }
     $response->setStatus($body['status']);
     if (!isset($body['results'])) {
         throw new Exception\RuntimeException('Invalid results');
     }
     $resultSet = new ResultSet();
     foreach ($body['results'] as $data) {
         $result = new Result();
         $hydrator->hydrate($data, $result);
         $resultSet->addElement($result);
     }
     $response->setResults($resultSet);
     return $response;
 }
Esempio n. 21
0
 /**
  * 
  * @param string $uri
  * @return string
  */
 public function getType($uri)
 {
     $validator = new \Zend\Validator\Uri(array('allowRelative' => false));
     if ($validator->isValid($uri)) {
         $parseInfo = parent::parse($uri);
         switch ($parseInfo->host) {
             // Youtube.com
             case "www.youtube.com":
                 $queryArray = array();
                 parse_str($parseInfo->query, $queryArray);
                 if (isset($queryArray['v'])) {
                     return self::TYPE_VIDEO_YOUTUBE;
                 }
                 break;
                 // Dailymotion.com
             // Dailymotion.com
             case "www.dailymotion.com":
                 if (strpos($parseInfo->path, "/video") !== false) {
                     return self::TYPE_VIDEO_DAILYMOTION;
                 }
                 break;
                 // Vimeo.com
             // Vimeo.com
             case "vimeo.com":
                 if (is_int($parseInfo->path)) {
                     return self::TYPE_VIDEO_VIMEO;
                 }
                 break;
         }
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $uri);
         curl_setopt($ch, CURLOPT_HEADER, TRUE);
         curl_setopt($ch, CURLOPT_NOBODY, TRUE);
         // remove body
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
         $head = curl_exec($ch);
         $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
         curl_close($ch);
         if (strpos($contentType, "image") !== false) {
             return self::TYPE_IMAGE;
         } else {
             if ($contentType == "application/x-shockwave-flash") {
                 return self::TYPE_SWF;
             }
         }
         return self::TYPE_WEBPAGE;
     } else {
         return "";
     }
 }
Esempio n. 22
0
 /**
  * Validates if a string is valid as a sitemap location
  *
  * @link http://www.sitemaps.org/protocol.php#locdef <loc>
  *
  * @param  string  $value  value to validate
  * @return boolean
  */
 public function isValid($value)
 {
     if (!is_string($value)) {
         $this->_error(self::INVALID);
         return false;
     }
     $this->_setValue($value);
     $result = \Zend\Uri\Uri::check($value);
     if ($result !== true) {
         $this->_error(self::NOT_VALID);
         return false;
     }
     return true;
 }
Esempio n. 23
0
 /**
  * @param $price
  * @return FilterValue|null
  * @throws UnparseableValueException
  */
 public function getValueForPrice($price)
 {
     $values = $this->getFilterValues();
     foreach ($values as $value) {
         $url = $value->getLink();
         $uri = new Uri($url);
         $parts = $uri->getQueryAsArray();
         if (isset($parts['price'])) {
             $priceParts = explode('-', $parts['price']);
             if (!$priceParts[0]) {
                 $priceParts[0] = -1;
             }
             if (!$priceParts[1]) {
                 $priceParts[1] = PHP_INT_MAX;
             }
             // term 0, price filters seem to use less than
             if ($price >= $priceParts[0] & $price < $priceParts[1]) {
                 return $value;
             }
         }
     }
     return null;
 }
Esempio n. 24
0
 public static function fromString($headerLine)
 {
     $header = new static();
     list($name, $value) = explode(': ', $headerLine, 2);
     // check to ensure proper header type for this factory
     if (strtolower($name) !== 'location') {
         throw new Exception\InvalidArgumentException('Invalid header line for Location string: "' . $name . '"');
     }
     if (!Uri::validateHost($value)) {
         throw new Exception\InvalidArgumentException('Invalid URI value for Location: "' . $value . '"');
     }
     // @todo implementation details
     $header->value = $value;
     return $header;
 }
    /**
     * Send request to the remote server with streaming support.
     *
     * @param string        $method
     * @param \Zend\Uri\Uri $uri
     * @param string        $http_ver
     * @param array         $headers
     * @param string        $body
     * @return string Request as string
     */
    public function write($method, $uri, $http_ver = '1.1', $headers = array(),
        $body = '')
    {
        // Make sure we're properly connected
        if (! $this->socket) {
            throw new Adapter\Exception(
                'Trying to write but we are not connected');
        }

        $host = $uri->getHost();
        $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
        if ($this->connected_to[0] != $host || $this->connected_to[1] != $uri->getPort()) {
            throw new Adapter\Exception(
                'Trying to write but we are connected to the wrong host');
        }

        // Save request method for later
        $this->method = $method;

        // Build request headers
        $path = $uri->getPath();
        if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
        $request = "{$method} {$path} HTTP/{$http_ver}\r\n";
        foreach ($headers as $k => $v) {
            if (is_string($k)) $v = ucfirst($k) . ": $v";
            $request .= "$v\r\n";
        }

        // Send the headers over
        $request .= "\r\n";
        if (! @fwrite($this->socket, $request)) {
            throw new Adapter\Exception(
                'Error writing request to server');
        }


        //read from $body, write to socket
        $chunk = $body->read(self::CHUNK_SIZE);
        while ($chunk !== FALSE) {
            if (! @fwrite($this->socket, $chunk)) {
                throw new Adapter\Exception(
                    'Error writing request to server');
            }
            $chunk = $body->read(self::CHUNK_SIZE);
        }
        $body->closeFileHandle();
        return 'Large upload, request is not cached.';
    }
Esempio n. 26
0
 /**
  * Handle incoming messages.
  *
  * Must be implemented by all extending classes
  *
  * @param $url
  * @param \React\EventLoop\LoopInterface $loop
  * @param \Zend\Log\LoggerInterface $logger
  * @throws \InvalidArgumentException
  */
 public function __construct($url, LoopInterface $loop, LoggerInterface $logger)
 {
     $uri = new Uri($url);
     if ($uri->getScheme() == 'ws') {
         $uri->setScheme('tcp');
     } elseif ($uri->getScheme() == 'wss') {
         $uri->setScheme('ssl');
     }
     if ($uri->getScheme() != 'tcp' && $uri->getScheme() != 'ssl') {
         throw new \InvalidArgumentException("Uri scheme must be one of: tcp, ssl, ws, wss");
     }
     $this->uri = $uri;
     $this->loop = $loop;
     $this->_streams = new SplObjectStorage();
     $this->_connections = new SplObjectStorage();
     $this->_context = stream_context_create();
     $this->_logger = $logger;
 }
Esempio n. 27
0
 public function getRedirect($urlString, $stayLocal = true, $preserveHttps = true)
 {
     /**
      * Check that the URL has the correct format expected of a valid HTTP
      * or HTTPS URL. If so, normalize the URL.
      */
     $valid = false;
     $url = new Uri();
     try {
         $url->parse($urlString);
         if ($url->isValid() && $url->isAbsolute()) {
             $url->normalize();
             $valid = true;
         }
     } catch (\Exception $e) {
     }
     if (false === $valid) {
         throw new Exception\InvalidArgumentException("Given value was not a valid absolute HTTP(S) URL: " . $url);
     }
     /**
      * Make sure we don't redirect from HTTPS to HTTP unless flagged by
      * the user. Using a Strict-Transport-Security header helps too!
      */
     if (true === (bool) $preserveHttps && HttpsDetector::isHttpsRequest()) {
         if (!$this->isHttps($url)) {
             throw new Exception\InvalidArgumentException("Given value was not a HTTPS URL as expected: " . $url);
         }
     }
     /**
      * Check if the URL meets the local host restriction unless disabled
      */
     if (true === $stayLocal && !$this->isLocal($url)) {
         throw new Exception\InvalidArgumentException("Given value was not a local HTTP(S) URL: " . $url);
     }
     /**
      * Check if the URL host exists on a whitelist of allowed hosts
      */
     $whitelist = $this->getWhitelist();
     if (!empty($whitelist) && !$this->isWhitelisted($url)) {
         throw new Exception\InvalidArgumentException("Given value was not a whitelisted URL as expected: " . $url);
     }
     /**
      * Get URL string after URL encoding checks and return a Location header
      * object.
      */
     $header = new Header\Location(array('url' => $url->toString(), 'status_code' => 302));
     return $header;
 }
Esempio n. 28
0
 /**
  * Send request to the remote server
  *
  * @param string        $method
  * @param \Zend\Uri\Uri $uri
  * @param string        $http_ver
  * @param array         $headers
  * @param string        $body
  * @return string Request as string
  */
 public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
 {
     $host = $uri->getHost();
     $host = strtolower($uri->getScheme()) == 'https' ? 'sslv2://' . $host : $host;
     // Build request headers
     $path = $uri->getPath();
     if (empty($path)) {
         $path = '/';
     }
     if ($uri->getQuery()) {
         $path .= '?' . $uri->getQuery();
     }
     $request = "{$method} {$path} HTTP/{$http_ver}\r\n";
     foreach ($headers as $k => $v) {
         if (is_string($k)) {
             $v = ucfirst($k) . ": {$v}";
         }
         $request .= "{$v}\r\n";
     }
     // Add the request body
     $request .= "\r\n" . $body;
     // Do nothing - just return the request as string
     return $request;
 }
Esempio n. 29
0
 /**
  * Send request to the remote server
  *
  * @param string        $method
  * @param \Zend\Uri\Uri $uri
  * @param string        $httpVer
  * @param array         $headers
  * @param string        $body
  * @throws AdapterException\RuntimeException
  * @return string Request as string
  */
 public function write($method, $uri, $httpVer = '1.1', $headers = array(), $body = '')
 {
     // Make sure we're properly connected
     if (!$this->socket) {
         throw new AdapterException\RuntimeException('Trying to write but we are not connected');
     }
     $host = $uri->getHost();
     $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
     if ($this->connectedTo[0] != $host || $this->connectedTo[1] != $uri->getPort()) {
         throw new AdapterException\RuntimeException('Trying to write but we are connected to the wrong host');
     }
     // Save request method for later
     $this->method = $method;
     // Build request headers
     $path = $uri->getPath();
     if ($uri->getQuery()) {
         $path .= '?' . $uri->getQuery();
     }
     $request = "{$method} {$path} HTTP/{$httpVer}\r\n";
     foreach ($headers as $k => $v) {
         if (is_string($k)) {
             $v = ucfirst($k) . ": {$v}";
         }
         $request .= "{$v}\r\n";
     }
     if (is_resource($body)) {
         $request .= "\r\n";
     } else {
         // Add the request body
         $request .= "\r\n" . $body;
     }
     // Send the request
     ErrorHandler::start();
     $test = fwrite($this->socket, $request);
     $error = ErrorHandler::stop();
     if (false === $test) {
         throw new AdapterException\RuntimeException('Error writing request to server', 0, $error);
     }
     if (is_resource($body)) {
         if (stream_copy_to_stream($body, $this->socket) == 0) {
             throw new AdapterException\RuntimeException('Error writing request to server');
         }
     }
     return $request;
 }
Esempio n. 30
0
 public function initiateHandshake(Uri $uri)
 {
     $challenge = self::randHybiKey();
     $request = new Request();
     $requestUri = $uri->getPath();
     if ($uri->getQuery()) {
         $requestUri .= "?" . $uri->getQuery();
     }
     $request->setUri($requestUri);
     $request->getHeaders()->addHeaderLine("Connection", "Upgrade");
     $request->getHeaders()->addHeaderLine("Host", $uri->getHost());
     $request->getHeaders()->addHeaderLine("Sec-WebSocket-Key", $challenge);
     $request->getHeaders()->addHeaderLine("Sec-WebSocket-Version", 13);
     $request->getHeaders()->addHeaderLine("Upgrade", "websocket");
     $this->setRequest($request);
     $this->emit("request", array($request));
     $this->_socket->write($request->toString());
     return $request;
 }