/** * assemble(): defined by RouteInterface interface. * * @see BaseRoute::assemble() * @param array $params * @param array $options * @return mixed * @throws Exception\ExceptionInterface */ public function assemble(array $params = array(), array $options = array()) { if (!isset($options['name'])) { throw new Exception\InvalidArgumentException('Missing "name" option'); } $names = explode('/', $options['name'], 2); $route = $this->routes->get($names[0]); if (!$route) { throw new Exception\RuntimeException(sprintf('Route with name "%s" not found', $names[0])); } if (isset($names[1])) { $options['name'] = $names[1]; } else { unset($options['name']); } if (!isset($options['only_return_path']) || !$options['only_return_path']) { if (!isset($options['uri'])) { $uri = new HttpUri(); if (isset($options['force_canonical']) && $options['force_canonical']) { if ($this->requestUri === null) { throw new Exception\RuntimeException('Request URI has not been set'); } $uri->setScheme($this->requestUri->getScheme()) ->setHost($this->requestUri->getHost()) ->setPort($this->requestUri->getPort()); } $options['uri'] = $uri; } else { $uri = $options['uri']; } $path = $this->baseUrl . $route->assemble(array_merge($this->defaultParams, $params), $options); if ((isset($options['force_canonical']) && $options['force_canonical']) || $uri->getHost() !== null) { if ($uri->getScheme() === null) { if ($this->requestUri === null) { throw new Exception\RuntimeException('Request URI has not been set'); } $uri->setScheme($this->requestUri->getScheme()); } return $uri->setPath($path)->toString(); } elseif (!$uri->isAbsolute() && $uri->isValidRelative()) { return $uri->setPath($path)->toString(); } } return $this->baseUrl . $route->assemble(array_merge($this->defaultParams, $params), $options); }
/** * Send request to the proxy server with streaming support * * @param string $method * @param \Zend\Uri\Http $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.'; }
/** * Do request proxy method. * * @param CommonClient $client Actual SOAP client. * @param string $request The request body. * @param string $location The SOAP URI. * @param string $action The SOAP action to call. * @param integer $version The SOAP version to use. * @param integer $one_way (Optional) The number 1 if a response is not expected. * @return string The XML SOAP response. */ public function _doRequest(CommonClient $client, $request, $location, $action, $version, $one_way = null) { if (!$this->useNtlm) { return parent::_doRequest($client, $request, $location, $action, $version, $one_way); } $curlClient = $this->getCurlClient(); $headers = array('Content-Type' => 'text/xml; charset=utf-8', 'Method' => 'POST', 'SOAPAction' => '"' . $action . '"', 'User-Agent' => 'PHP-SOAP-CURL'); $uri = new HttpUri($location); $curlClient->setCurlOption(CURLOPT_HTTPAUTH, CURLAUTH_NTLM)->setCurlOption(CURLOPT_SSL_VERIFYHOST, false)->setCurlOption(CURLOPT_SSL_VERIFYPEER, false)->setCurlOption(CURLOPT_USERPWD, $this->options['login'] . ':' . $this->options['password']); // Perform the cURL request and get the response $curlClient->connect($uri->getHost(), $uri->getPort()); $curlClient->write('POST', $uri, 1.1, $headers, $request); $response = HttpResponse::fromString($curlClient->read()); $curlClient->close(); // Save headers $this->lastRequestHeaders = $this->flattenHeaders($headers); $this->lastResponseHeaders = $response->getHeaders()->toString(); // Return only the XML body return $response->getBody(); }
/** * Send request to the remote server with streaming support. * * @param string $method * @param \Zend\Uri\Http $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.'; }
/** * assemble(): defined by Route interface. * * @see BaseRoute::assemble() * @param array $params * @param array $options * @return mixed */ public function assemble(array $params = array(), array $options = array()) { if (!isset($options['name'])) { throw new Exception\InvalidArgumentException('Missing "name" option'); } $names = explode('/', $options['name'], 2); $route = $this->routes->get($names[0]); if (!$route) { throw new Exception\RuntimeException(sprintf('Route with name "%s" not found', $names[0])); } if (isset($names[1])) { $options['name'] = $names[1]; } else { unset($options['name']); } if (!isset($options['uri'])) { $uri = new HttpUri(); if (isset($options['absolute']) && $options['absolute']) { if ($this->requestUri === null) { throw new Exception\RuntimeException('Request URI has not been set'); } $uri->setScheme($this->requestUri->getScheme())->setHost($this->requestUri->getHost())->setPort($this->requestUri->getPort()); } $options['uri'] = $uri; } $path = $this->baseUrl . $route->assemble($params, $options); if (isset($uri)) { if (isset($options['absolute']) && $options['absolute']) { return $uri->setPath($path)->toString(); } elseif ($uri->getHost() !== null) { if ($uri->scheme !== null) { if ($this->requestUri === null) { throw new Exception\RuntimeException('Request URI has not been set'); } $uri->setScheme($this->requestUri->getScheme()); } return $uri->setPath($path)->toString(); } } return $path; }
/** * Check if ssl is forced or not * * @param EventInterface $event Mvc event * * @return null|Zend\Http\PhpEnvironment\Response */ public function check(EventInterface $event) { $coreConfig = $event->getApplication()->getServiceManager()->get('CoreConfig'); $matchedRouteName = $event->getRouteMatch()->getMatchedRouteName(); $request = $event->getRequest(); $uri = $request->getUri(); if ($matchedRouteName === 'cms') { if ($uri->getScheme() === 'https' or $coreConfig->getValue('force_frontend_ssl')) { $newUri = new Uri($coreConfig->getValue('secure_frontend_base_path')); $newUri->setScheme('https'); } else { $newUri = new Uri($coreConfig->getValue('unsecure_frontend_base_path')); } } else { if ($uri->getScheme() === 'https' or $coreConfig->getValue('force_backend_ssl')) { $newUri = new Uri($coreConfig->getValue('secure_backend_base_path')); $newUri->setScheme('https'); } else { $newUri = new Uri($coreConfig->getValue('unsecure_backend_base_path')); } } if (!empty($newUri) and $newUri->isValid() and ($newUri->getHost() != '' and $uri->getHost() != $newUri->getHost()) or $newUri->getScheme() != '' and $uri->getScheme() != $newUri->getScheme()) { $uri->setPort($newUri->getPort()); if ($newUri->getHost() != '') { $uri->setHost($newUri->getHost()); } if ($newUri->getScheme() != '') { $uri->setScheme($newUri->getScheme()); } $response = $event->getResponse(); $response->setStatusCode(302); $response->getHeaders()->addHeaderLine('Location', $request->getUri()); $event->stopPropagation(); return $response; } }
public function testGetPortDoesntModifyUrlHttps() { $origUri = 'https://www.example.com/foo'; $uri = new HttpUri($origUri); $uri->getPort(); $this->assertEquals($origUri, $uri->toString()); }
/** * assemble(): defined by Route interface. * * @see Route::assemble() * * @param array $params * @param array $options * * @throws \RuntimeException * @throws \InvalidArgumentException * @return string */ public function assemble(array $params = array(), array $options = array()) { if (!isset($options['name'])) { throw new Exception\InvalidArgumentException('Missing "name" option'); } $names = explode('/', $options['name'], 2); $route = $this->routes->get($names[0]); /**#@+ * Load extra routes if called route not found in current route list */ if (!$route) { $route = $this->extraRoute($names[0]); } /**#@-**/ if (!$route) { throw new Exception\RuntimeException(sprintf('Route with name "%s" not found', $names[0])); } if (isset($names[1])) { if (!$route instanceof TreeRouteStack) { throw new Exception\RuntimeException(sprintf('Route with name "%s" does not have child routes', $names[0])); } $options['name'] = $names[1]; } else { unset($options['name']); } if (isset($options['only_return_path']) && $options['only_return_path']) { return $this->baseUrl . $route->assemble(array_merge($this->defaultParams, $params), $options); } if (!isset($options['uri'])) { $uri = new HttpUri(); if (isset($options['force_canonical']) && $options['force_canonical']) { if ($this->requestUri === null) { throw new Exception\RuntimeException('Request URI has not been set'); } $uri->setScheme($this->requestUri->getScheme())->setHost($this->requestUri->getHost())->setPort($this->requestUri->getPort()); } $options['uri'] = $uri; } else { $uri = $options['uri']; } $path = $this->baseUrl . $route->assemble(array_merge($this->defaultParams, $params), $options); if (isset($options['query'])) { $uri->setQuery($options['query']); } if (isset($options['fragment'])) { $uri->setFragment($options['fragment']); } if (isset($options['force_canonical']) && $options['force_canonical'] || $uri->getHost() !== null || $uri->getScheme() !== null) { if (($uri->getHost() === null || $uri->getScheme() === null) && $this->requestUri === null) { throw new Exception\RuntimeException('Request URI has not been set'); } if ($uri->getHost() === null) { $uri->setHost($this->requestUri->getHost()); } if ($uri->getScheme() === null) { $uri->setScheme($this->requestUri->getScheme()); } return $uri->setPath($path)->normalize()->toString(); } elseif (!$uri->isAbsolute() && $uri->isValidRelative()) { return $uri->setPath($path)->normalize()->toString(); } return $path; }
/** * Separating this from send method allows subclasses to wrap * the interaction with the adapter * * @param Http $uri * @param string $method * @param bool $secure * @param array $headers * @param string $body * @return string the raw response * @throws Exception\RuntimeException */ protected function doRequest(Http $uri, $method, $secure = false, $headers = array(), $body = '') { // Open the connection, send the request and read the response $this->adapter->connect($uri->getHost(), $uri->getPort(), $secure); if ($this->config['outputstream']) { if ($this->adapter instanceof Client\Adapter\StreamInterface) { $stream = $this->openTempStream(); $this->adapter->setOutputStream($stream); } else { throw new Exception\RuntimeException('Adapter does not support streaming'); } } // HTTP connection $this->lastRawRequest = $this->adapter->write($method, $uri, $this->config['httpversion'], $headers, $body); return $this->adapter->read(); }
/** * Send HTTP request * * @param Request $request * @return Response */ public function send(Request $request = null) { if ($request !== null) { $this->setRequest($request); } $this->redirectCounter = 0; $response = null; // Make sure the adapter is loaded if ($this->adapter == null) { $this->setAdapter($this->config['adapter']); } // Send the first request. If redirected, continue. do { // uri $uri = $this->getUri(); // query $query = $this->getRequest()->query(); if (!empty($query)) { $queryArray = $query->toArray(); if (!empty($queryArray)) { $newUri = $uri->toString(); $queryString = http_build_query($query); if ($this->config['rfc3986strict']) { $queryString = str_replace('+', '%20', $queryString); } if (strpos($newUri, '?') !== false) { $newUri .= '&' . $queryString; } else { $newUri .= '?' . $queryString; } $uri = new \Zend\Uri\Http($newUri); } } // If we have no ports, set the defaults if (!$uri->getPort()) { $uri->setPort($uri->getScheme() == 'https' ? 443 : 80); } // method $method = $this->getRequest()->getMethod(); // body $body = $this->prepareBody(); // headers $headers = $this->prepareHeaders($body, $uri); $secure = $uri->getScheme() == 'https' ? true : false; // cookies $cookie = $this->prepareCookies($uri->getHost(), $uri->getPath(), $secure); if ($cookie->getFieldValue()) { $headers['Cookie'] = $cookie->getFieldValue(); } // check that adapter supports streaming before using it if (is_resource($body) && !$this->adapter instanceof Client\Adapter\Stream) { throw new Client\Exception\RuntimeException('Adapter does not support streaming'); } // Open the connection, send the request and read the response $this->adapter->connect($uri->getHost(), $uri->getPort(), $secure); if ($this->config['outputstream']) { if ($this->adapter instanceof Client\Adapter\Stream) { $stream = $this->openTempStream(); $this->adapter->setOutputStream($stream); } else { throw new Exception\RuntimeException('Adapter does not support streaming'); } } // HTTP connection $this->lastRawRequest = $this->adapter->write($method, $uri, $this->config['httpversion'], $headers, $body); $response = $this->adapter->read(); if (!$response) { throw new Exception\RuntimeException('Unable to read response, or response is empty'); } if ($this->config['storeresponse']) { $this->lastRawResponse = $response; } else { $this->lastRawResponse = null; } if ($this->config['outputstream']) { $streamMetaData = stream_get_meta_data($stream); if ($streamMetaData['seekable']) { rewind($stream); } // cleanup the adapter $this->adapter->setOutputStream(null); $response = Response\Stream::fromStream($response, $stream); $response->setStreamName($this->streamName); if (!is_string($this->config['outputstream'])) { // we used temp name, will need to clean up $response->setCleanup(true); } } else { $response = Response::fromString($response); } // Get the cookies from response (if any) $setCookie = $response->cookie(); if (!empty($setCookie)) { $this->addCookie($setCookie); } // If we got redirected, look for the Location header if ($response->isRedirect() && $response->headers()->has('Location')) { // Avoid problems with buggy servers that add whitespace at the // end of some headers $location = trim($response->headers()->get('Location')->getFieldValue()); // Check whether we send the exact same request again, or drop the parameters // and send a GET request if ($response->getStatusCode() == 303 || !$this->config['strictredirects'] && ($response->getStatusCode() == 302 || $response->getStatusCode() == 301)) { $this->resetParameters(); $this->setMethod(Request::METHOD_GET); } // If we got a well formed absolute URI if (($scheme = substr($location, 0, 6)) && ($scheme == 'http:/' || $scheme == 'https:')) { $this->setUri($location); } else { // Split into path and query and set the query if (strpos($location, '?') !== false) { list($location, $query) = explode('?', $location, 2); } else { $query = ''; } $this->getUri()->setQuery($query); // Else, if we got just an absolute path, set it if (strpos($location, '/') === 0) { $this->getUri()->setPath($location); // Else, assume we have a relative path } else { // Get the current path directory, removing any trailing slashes $path = $this->getUri()->getPath(); $path = rtrim(substr($path, 0, strrpos($path, '/')), "/"); $this->getUri()->setPath($path . '/' . $location); } } ++$this->redirectCounter; } else { // If we didn't get any location, stop redirecting break; } } while ($this->redirectCounter < $this->config['maxredirects']); $this->response = $response; return $response; }
/** * Separating this from send method allows subclasses to wrap * the interaction with the adapter * * @param Http $uri * @param string $method * @param bool $secure * @param array $headers * @param string $body * @return string the raw response * @throws Exception\RuntimeException */ protected function doRequest(Http $uri, $method, $secure = false, $headers = array(), $body = '') { // Open the connection, send the request and read the response $this->adapter->connect($uri->getHost(), $uri->getPort(), $secure); if ($this->config['outputstream']) { if ($this->adapter instanceof ZendClient\Adapter\StreamInterface) { $stream = $this->openTempStream(); $this->adapter->setOutputStream($stream); } else { throw new Exception\RuntimeException('Adapter does not support streaming'); } } // HTTP connection $uri->setPath('/ZendServer/test.php'); $headers['Content-Length'] = strlen($body) + $this->filesContentLength(); $this->lastRawRequest = $this->adapter->write($method, $uri, $this->config['httpversion'], $headers, ''); $this->writeChunk($body); // Encode files foreach ($this->getRequest()->getFiles()->toArray() as $key => $file) { $this->writeFile($key, $file['formname']); } $this->writeChunk("--" . $this->boundary . "--\r\n"); $this->writeChunk(''); return $this->adapter->read(); }
/** * Send HTTP request * * @param Request $request * @return Response * @throws Exception\RuntimeException * @throws Client\Exception\RuntimeException */ public function send(Request $request = null) { if ($request !== null) { $this->setRequest($request); } if (!count($this->getRequest()->getFiles())) { return parent::send($request); } $this->redirectCounter = 0; $response = null; // Make sure the adapter is loaded if ($this->adapter == null) { $this->setAdapter($this->config['adapter']); } if (!$this->adapter instanceof Adapter\DirectWriteInterface) { throw new ZendClient\Exception\RuntimeException('Adapter must implement DirectWriteInterface'); } // Send the first request. If redirected, continue. do { // uri $uri = $this->getUri(); // query $query = $this->getRequest()->getQuery(); if (!empty($query)) { $queryArray = $query->toArray(); if (!empty($queryArray)) { $newUri = $uri->toString(); $queryString = http_build_query($query, null, $this->getArgSeparator()); if ($this->config['rfc3986strict']) { $queryString = str_replace('+', '%20', $queryString); } if (strpos($newUri, '?') !== false) { $newUri .= $this->getArgSeparator() . $queryString; } else { $newUri .= '?' . $queryString; } $uri = new Http($newUri); } } // If we have no ports, set the defaults if (!$uri->getPort()) { $uri->setPort($uri->getScheme() == 'https' ? 443 : 80); } // method $method = $this->getRequest()->getMethod(); // headers $headers = $this->prepareHeaders(null, $uri); $secure = $uri->getScheme() == 'https'; if (isset($this->config['debug']) && $this->config['debug']) { $debugCookies = "debug_host=127.0.0.1&debug_port=10137&start_debug=1&send_debug_header=1&send_sess_end=1&debug_jit=1&debug_stop=1&use_remote=0&debug_session_id=1212593"; $cookies = array(); parse_str($debugCookies, $cookies); foreach ($cookies as $name => $value) { $this->addCookie($name, $value); } } // cookies $cookie = $this->prepareCookies($uri->getHost(), $uri->getPath(), $secure); if ($cookie->getFieldValue()) { $headers['Cookie'] = $cookie->getFieldValue(); } $body = $this->prepareBody(); if ($this->boundary) { $headers['Content-Type'] .= "; boundary=" . $this->boundary; } // calling protected method to allow extending classes // to wrap the interaction with the adapter $response = $this->doRequest($uri, $method, $secure, $headers, $body); if (!$response) { throw new Exception\RuntimeException('Unable to read response, or response is empty'); } if ($this->config['storeresponse']) { $this->lastRawResponse = $response; } else { $this->lastRawResponse = null; } if ($this->config['outputstream']) { $stream = $this->getStream(); if (!is_resource($stream) && is_string($stream)) { $stream = fopen($stream, 'r'); } $streamMetaData = stream_get_meta_data($stream); if ($streamMetaData['seekable']) { rewind($stream); } // cleanup the adapter $this->adapter->setOutputStream(null); $response = Response\Stream::fromStream($response, $stream); $response->setStreamName($this->streamName); if (!is_string($this->config['outputstream'])) { // we used temp name, will need to clean up $response->setCleanup(true); } } else { $response = Response::fromString($response); } // Get the cookies from response (if any) $setCookies = $response->getCookie(); if (!empty($setCookies)) { $this->addCookie($setCookies); } // If we got redirected, look for the Location header if ($response->isRedirect() && $response->getHeaders()->has('Location')) { // Avoid problems with buggy servers that add whitespace at the // end of some headers $location = trim($response->getHeaders()->get('Location')->getFieldValue()); // Check whether we send the exact same request again, or drop the parameters // and send a GET request if ($response->getStatusCode() == 303 || !$this->config['strictredirects'] && ($response->getStatusCode() == 302 || $response->getStatusCode() == 301)) { $this->resetParameters(false, false); $this->setMethod(Request::METHOD_GET); } // If we got a well formed absolute URI if (($scheme = substr($location, 0, 6)) && ($scheme == 'http:/' || $scheme == 'https:')) { // setURI() clears parameters if host changed, see #4215 $this->setUri($location); } else { // Split into path and query and set the query if (strpos($location, '?') !== false) { list($location, $query) = explode('?', $location, 2); } else { $query = ''; } $this->getUri()->setQuery($query); // Else, if we got just an absolute path, set it if (strpos($location, '/') === 0) { $this->getUri()->setPath($location); // Else, assume we have a relative path } else { // Get the current path directory, removing any trailing slashes $path = $this->getUri()->getPath(); $path = rtrim(substr($path, 0, strrpos($path, '/')), "/"); $this->getUri()->setPath($path . '/' . $location); } } ++$this->redirectCounter; } else { // If we didn't get any location, stop redirecting break; } } while ($this->redirectCounter <= $this->config['maxredirects']); $this->response = $response; return $response; }