Ejemplo n.º 1
0
 /**
  * @param HttpRequest $request
  */
 public function handle(HttpRequest $request)
 {
     if ($request->isPost() && $request->getUrl()->getFirstComponent() == 'containers') {
         return $this->writer->registerContainer();
     }
     if ($request->isGet() && $request->getUrl()->getFirstComponent() == 'containers') {
         $location = $this->reader->locateContainer(ContainerTrackingNumber::fromString($request->getUrl()->getSecondComponent()));
         $jsonLocation = JsonLocation::fromLocation($location);
         return $jsonLocation->json();
     }
 }
Ejemplo n.º 2
0
 /**
  * Return the Url of the request regardless of the server
  *
  * @return  HttpUrl A HttpUrl object
  */
 public function getUrl()
 {
     $url = parent::getUrl();
     //Add the query to the URL
     $url->setQuery($this->getQuery()->toArray());
     return $url;
 }
Ejemplo n.º 3
0
 function __construct(array $macros, IRouter $router, HttpRequest $req, I18n $i18n)
 {
     $this->router = $router;
     $this->url = $req->getUrl();
     $this->i18n = $i18n;
     $this->macros = $this->macros + $macros;
 }
Ejemplo n.º 4
0
 /**
  * @inheritdoc
  */
 public function format(HttpRequest $request)
 {
     $data = (array) $request->getData();
     $content = http_build_query($data, '', '&', $this->encodingType);
     if (strcasecmp('get', $request->getMethod()) === 0) {
         if (!empty($content)) {
             $url = $request->getUrl();
             $url .= strpos($url, '?') === false ? '?' : '&';
             $url .= $content;
             $request->setUrl($url);
         }
         return $request;
     }
     $request->addHeader('Content-Type', 'application/x-www-form-urlencoded');
     $request->setContent($content);
     return $request;
 }
Ejemplo n.º 5
0
 /**
  * Executes an HTTP transaction and returns the response.
  *
  * @param HttpRequest $request
  * @return HttpResponse
  */
 public function getResponse(HttpRequest $request)
 {
     $uri = $request->getUrl();
     $headers = $request->getHeaders();
     $flatHeaders = [];
     foreach ($headers as $key => $value) {
         $flatHeaders[] = $key . ": " . $value;
     }
     $flatHeaders[] = 'Connection: Keep-Alive';
     $flatHeaders[] = 'Expect:';
     $flatHeaders[] = 'Accept-Language: en-GB';
     $flatHeaders[] = 'Cache-Control: no-cache';
     $flatHeaders[] = 'User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)';
     $curl = curl_init($uri);
     curl_setopt($curl, CURLOPT_HEADER, false);
     $payload = $request->getPayload();
     switch ($request->getMethod()) {
         case "head":
             curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "HEAD");
             break;
         case "delete":
             curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
             break;
         case "post":
             curl_setopt($curl, CURLOPT_POST, true);
             curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
             break;
         case "put":
             curl_setopt($curl, CURLOPT_POST, true);
             curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
             curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
             break;
     }
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($curl, CURLOPT_HTTPHEADER, $flatHeaders);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     $response = curl_exec($curl);
     $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
     curl_close($curl);
     $httpResponse = new HttpResponse();
     $httpResponse->setResponseBody($response);
     $httpResponse->setResponseCode($responseCode);
     return $httpResponse;
 }
Ejemplo n.º 6
0
 public function sendRequest(HttpRequest $request)
 {
     if (!$this->client) {
         throw new Exception\TwitchException('Client was not set');
     }
     $apiurl = rtrim($this->client->getApiUrl(), '/');
     $url = sprintf('%s/%s', $apiurl, $request->getUrl());
     $url = rtrim($url, '/');
     $this->getAdapter()->open();
     $data = $this->getAdapter()->send($url, $request->getRequestMethod(), $request->getRequestHeaders(), $request->getPostBody());
     $status_code = $this->getAdapter()->getHttpStatusCode();
     $data = json_decode($data);
     $this->getAdapter()->close();
     // TODO we need to return more info
     if ($status_code !== 200) {
         throw new Exception\TwitchException($data->error, $data->status);
     }
     return $data;
 }
 /**
  * Sends a request
  *
  * @param   peer.http.HttpRequest request
  * @param   int timeout default 60
  * @param   float connecttimeout default 2.0
  * @return  peer.http.HttpResponse response object
  */
 public function send(HttpRequest $request, $timeout = 60, $connecttimeout = 2.0)
 {
     // Use proxy socket and Modify target if a proxy is to be used for this request,
     // a proxy wants "GET http://example.com/ HTTP/X.X"
     if ($this->proxy && !$this->proxy->isExcluded($url = $request->getUrl())) {
         $request->setTarget(sprintf('%s://%s%s%s', $url->getScheme(), $url->getHost(), $url->getPort() ? ':' . $url->getPort() : '', $url->getPath('/')));
         $s = $this->proxySocket;
     } else {
         $s = $this->socket;
     }
     // Socket still open from last request. This is the case when unread
     // data is left on the socket (by not reading the body, e.g.), so do
     // it the quick & dirty way: Close and reopen!
     $s->isConnected() && $s->close();
     $s->setTimeout($timeout);
     $s->connect($connecttimeout);
     $s->write($request->getRequestString());
     return new HttpResponse(new SocketInputStream($s));
 }
 /**
  * Sends a request
  *
  * @param   peer.http.HttpRequest request
  * @param   int timeout default 60
  * @param   float connecttimeout default 2.0
  * @return  peer.http.HttpResponse response object
  */
 public function send(HttpRequest $request, $timeout = 60, $connecttimeout = 2.0)
 {
     $curl = curl_copy_handle($this->handle);
     curl_setopt($curl, CURLOPT_URL, $request->url->getCanonicalURL());
     curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getRequestString());
     curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
     if ($this->proxy && !$this->proxy->isExcluded($request->getUrl())) {
         curl_setopt($curl, CURLOPT_PROXY, $this->proxy->host);
         curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy->port);
     }
     $response = curl_exec($curl);
     if (FALSE === $response) {
         $errno = curl_errno($curl);
         $error = curl_error($curl);
         curl_close($curl);
         throw new IOException(sprintf('%d: %s', $errno, $error));
     }
     // ensure handle is closed
     curl_close($curl);
     return new HttpResponse(new MemoryInputStream($response));
 }
Ejemplo n.º 9
0
 /**
  * Signs request with signature v3
  *
  * @param   \HttpRequest   $request    Http request
  * @param   string         $subdomain  optional A subdomain
  */
 protected function signRequestV3($request, $subdomain = null)
 {
     $time = time();
     //Gets the http method name
     $httpMethod = self::$httpMethods[$request->getMethod()];
     $components = parse_url($request->getUrl());
     //Retrieves headers from request
     $options = $request->getHeaders();
     //Adding timestamp
     if (!isset($options['Date'])) {
         $options['Date'] = gmdate('r', $time);
         $request->addHeaders(['Date' => $options['Date']]);
     }
     //This also includes a mock objects which look like "Mock_S3QueryClient_d65a1dc1".
     if (preg_match('#(?<=[_\\\\])S3QueryClient(?=_|$)#', get_class($this))) {
         $amzHeaders = [];
         foreach ($options as $key => $val) {
             if (preg_match('/^x-amz-/i', $key)) {
                 //Saves amz headers which are used to sign the request
                 $amzHeaders[strtolower($key)] = $val;
             }
         }
         //S3 Client has a special Authorization string
         $canonicalizedAmzHeaders = '';
         if (!empty($amzHeaders)) {
             ksort($amzHeaders);
             foreach ($amzHeaders as $k => $v) {
                 $canonicalizedAmzHeaders .= $k . ':' . trim(preg_replace('/#( *[\\r\\n]+ *)+#/', ' ', $v)) . "\n";
             }
         }
         //Note that in case of multiple sub-resources, sub-resources must be lexicographically sorted
         //by sub-resource name and separated by '&'. e.g. ?acl&versionId=value.
         if (!empty($components['query'])) {
             $canonPath = $components['path'] . '?';
             parse_str($components['query'], $subresources);
             ksort($subresources);
             $allowed = $this->getAllowedSubResources();
             foreach ($subresources as $k => $v) {
                 if (in_array($k, $allowed)) {
                     $canonPath .= $k . ($v !== '' ? '=' . $v : '') . '&';
                 }
             }
             $canonPath = substr($canonPath, 0, -1);
         }
         $canonicalizedResource = (isset($subdomain) ? '/' . strtolower($subdomain) : '') . (isset($canonPath) ? $canonPath : $components['path'] . (!empty($components['query']) ? '?' . $components['query'] : '') . (!empty($components['fragment']) ? '#' . $components['fragment'] : ''));
         $stringToSign = $httpMethod . "\n" . (!empty($options['Content-Md5']) ? $options['Content-Md5'] . '' : '') . "\n" . (!empty($options['Content-Type']) ? $options['Content-Type'] . '' : '') . "\n" . (isset($amzHeaders['x-amz-date']) ? '' : $options['Date'] . "\n") . $canonicalizedAmzHeaders . $canonicalizedResource;
         $options['Authorization'] = "AWS " . $this->awsAccessKeyId . ":" . base64_encode(hash_hmac('sha1', $stringToSign, $this->secretAccessKey, 1));
     } else {
         $options['Authorization'] = "AWS " . $this->awsAccessKeyId . ":" . base64_encode(hash_hmac('sha1', $options['Date'], $this->secretAccessKey, 1));
     }
     $request->addHeaders(['Authorization' => $options['Authorization']]);
 }
 /**
  * Sign the given request; ie. add an Authorization: Digest header
  * and increase the internal nonce counter.
  *
  * @param  peer.http.HttpRequest $request
  */
 public function sign(HttpRequest $request)
 {
     $url = $request->target;
     $params = array();
     if (is_array($request->parameters)) {
         $params = array_merge($params, $request->parameters);
     }
     if ($request->getUrl()->hasParams()) {
         $params = array_merge($params, $request->getUrl()->getParams());
     }
     if (sizeof($params)) {
         $url .= '?';
         foreach ($params as $k => $v) {
             $url .= $k . '=' . $v . '&';
         }
         $url = substr($url, 0, -1);
     }
     $request->setHeader('Authorization', new Header('Authorization', $this->getValueRepresentation($request->method, $url)));
     // Increase internal counter
     $this->counter++;
 }
Ejemplo n.º 11
0
 protected function handleResponse(HttpRequest $r)
 {
     if ($r->getResponseCode() != 304) {
         if ($r->getResponseCode() != 200) {
             throw new Exception("Unexpected response code " . $r->getResponseCode());
         }
         if (!strlen($body = $r->getResponseBody())) {
             throw new Exception("Received empty feed from " . $r->getUrl());
         }
         $this->saveFeed($this->url2name($r->getUrl()), $body);
     }
 }
Ejemplo n.º 12
0
 /**
  * Signs request with signature version 2
  *
  * Only POST http method is supported
  *
  * @param   \HttpRequest $request Http request object
  * @throws  QueryClientException
  */
 protected function signRequestV2($request)
 {
     $time = time();
     //Gets the http method name
     $httpMethod = self::$httpMethods[$request->getMethod()];
     //Gets both host and path from the url
     $components = parse_url($request->getUrl());
     $common = ['AWSAccessKeyId' => $this->awsAccessKeyId, 'SignatureVersion' => '2', 'SignatureMethod' => 'HmacSHA1', 'Timestamp' => gmdate('Y-m-d\\TH:i:s', $time) . "Z"];
     $request->addPostFields($common);
     //Gets adjusted options
     $options = $request->getPostFields();
     //Calculating canonicalized query string
     ksort($options);
     $canonicalizedQueryString = '';
     foreach ($options as $k => $v) {
         $canonicalizedQueryString .= '&' . rawurlencode($k) . '=' . rawurlencode($v);
     }
     $canonicalizedQueryString = ltrim($canonicalizedQueryString, '&');
     $stringToSign = $httpMethod . "\n" . strtolower($components['host']) . "\n" . $components['path'] . "\n" . $canonicalizedQueryString;
     switch ($common['SignatureMethod']) {
         case 'HmacSHA1':
         case 'HmacSHA256':
             $algo = strtolower(substr($common['SignatureMethod'], 4));
             break;
         default:
             throw new QueryClientException('Unknown SignatureMethod ' . $common['SignatureMethod']);
     }
     $request->addPostFields(['Signature' => base64_encode(hash_hmac($algo, $stringToSign, $this->secretAccessKey, 1))]);
     $request->addHeaders(['X-Amz-Date' => gmdate(\DateTime::ISO8601, $time)]);
 }
 protected function makeHandle(HttpRequest $request, CurlHttpResponse $response)
 {
     $handle = curl_init();
     Assert::isNotNull($request->getMethod());
     $options = array(CURLOPT_WRITEFUNCTION => array($response, 'writeBody'), CURLOPT_HEADERFUNCTION => array($response, 'writeHeader'), CURLOPT_URL => $request->getUrl()->toString(), CURLOPT_USERAGENT => 'onPHP::' . __CLASS__);
     if ($this->isPhp55()) {
         $options[CURLOPT_SAFE_UPLOAD] = true;
     }
     if ($this->noBody !== null) {
         $options[CURLOPT_NOBODY] = $this->noBody;
     }
     if ($this->followLocation !== null) {
         $options[CURLOPT_FOLLOWLOCATION] = $this->followLocation;
     }
     switch ($request->getMethod()->getId()) {
         case HttpMethod::GET:
             $options[CURLOPT_HTTPGET] = true;
             if ($request->getGet()) {
                 $options[CURLOPT_URL] .= ($request->getUrl()->getQuery() ? '&' : '?') . $this->argumentsToString($request->getGet());
             }
             break;
         case HttpMethod::POST:
             if ($request->getGet()) {
                 $options[CURLOPT_URL] .= ($request->getUrl()->getQuery() ? '&' : '?') . $this->argumentsToString($request->getGet());
             }
             $options[CURLOPT_POST] = true;
             $options[CURLOPT_POSTFIELDS] = $this->getPostFields($request);
             break;
         default:
             $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod()->getName();
             break;
     }
     $headers = array();
     foreach ($request->getHeaderList() as $headerName => $headerValue) {
         $headers[] = "{$headerName}: {$headerValue}";
     }
     if ($headers) {
         $options[CURLOPT_HTTPHEADER] = $headers;
     }
     if ($request->getCookie()) {
         $cookies = array();
         foreach ($request->getCookie() as $name => $value) {
             $cookies[] = $name . '=' . urlencode($value);
         }
         $options[CURLOPT_COOKIE] = implode('; ', $cookies);
     }
     foreach ($this->options as $key => $value) {
         $options[$key] = $value;
     }
     curl_setopt_array($handle, $options);
     return $handle;
 }
Ejemplo n.º 14
0
    // we have an image -- send response to client...
    $response->send();
    exit;
}
// Header handling
foreach (array('Content-Type') as $name) {
    $content = $response->getHeader($name);
    if ($content) {
        header("{$name}: {$content}");
    }
}
$debug = 0;
// debugging
if ($debug) {
    echo "DEBUGGING CALL TO <a href='{$url}'>{$url}</a>:\n<br>";
    echo 'Seen by pecl extension as:' . $request->getUrl();
    echo '<h2>Request</h2> <pre>' . $request->getRawRequestMessage() . '</pre>';
    echo '<h2>Response</h2> <pre>' . $request->getRawResponseMessage() . '</pre>';
    echo '<h2>Output headers</h2> <pre>';
    print_r(headers_list());
    print '</pre>';
    echo '<h2>Content</h2>';
    echo $response->getBody();
    exit;
}
// well, that's our body
$contents = $response->getBody();
// Take a short look if we got HTML (important for rewrite engine)
$is_html = stripos($response->getHeader('Content-Type'), 'html') !== false;
// rewrite the page...
$db->driver->rewrite_page($url, $contents, $is_html);