/**
  * Creates a new response
  *
  * @param   peer.http.HttpResponse response
  * @param   webservices.rest.ResponseReader reader
  * @param   var type (Deprecated)
  */
 public function __construct(HttpResponse $response, ResponseReader $reader = NULL, $type = NULL)
 {
     $this->response = $response;
     $this->reader = $reader;
     $this->type = $type;
     $this->input = $response->getInputStream();
 }
Example #2
0
 public function testGetters()
 {
     $response = new HttpResponse(200, array('Age: 42'), 'Hey');
     $this->assertEquals(200, $response->getStatus());
     $this->assertEquals(array('Age: 42'), $response->getHeaders());
     $this->assertEquals('Hey', $response->getBody());
 }
 public static function post($url, $params, $auth)
 {
     try {
         if (!function_exists("curl_init") && !function_exists("curl_setopt") && !function_exists("curl_exec") && !function_exists("curl_close")) {
             throw new Exception('CURL is required.');
         }
         $data = array("data" => $params->getJSONEncode(), "version" => Config::version);
         $httpResponse = new HttpResponse();
         ob_start();
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, self::get_furl($url));
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '0');
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '0');
         curl_setopt($ch, CURLOPT_HTTPHEADER, $auth);
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, Config::timeout);
         curl_exec($ch);
         $httpResponse->setResponse(urldecode(ob_get_contents()));
         $httpResponse->setCode(curl_getinfo($ch, CURLINFO_HTTP_CODE));
         ob_end_clean();
         if (curl_errno($ch)) {
             curl_close($ch);
             throw new Exception(curl_error($ch));
         }
         curl_close($ch);
         return $httpResponse;
     } catch (Exception $e) {
         curl_close($ch);
         throw new HttpException($e->getMessage());
     }
 }
Example #4
0
 /**
  * @param string
  * @param array
  * @return HttpRequest
  */
 public function render($template, $context)
 {
     $render = $this->get('render');
     $response = new HttpResponse();
     $response->setData($render->render($template, $context));
     return $response;
 }
 /**
  * Creates a new response
  *
  * @param   peer.http.HttpResponse response
  * @param   webservices.rest.RestDeserializer deserializer
  * @param   lang.Type type
  */
 public function __construct(HttpResponse $response, RestDeserializer $deserializer = NULL, Type $type = NULL)
 {
     $this->response = $response;
     $this->deserializer = $deserializer;
     $this->type = $type;
     $this->input = $response->getInputStream();
 }
Example #6
0
 public function dispatch(Request $request, Response $response = null)
 {
     if (!$response) {
         $response = new HttpResponse();
     }
     $response->setContent(__METHOD__);
     return $response;
 }
Example #7
0
 public function run()
 {
     if ($this->_isRequestMatching()) {
         $this->_controller = $this->_getControllerInstance();
         $this->_response->setBody($this->_callAction());
         $this->_response->send();
     }
 }
 function test_set_body_with_empty_string()
 {
     $response = new HttpResponse(200);
     $headers = array();
     $headers['content-encoding'] = 'gzip';
     $response->headers = $headers;
     $response->body = "";
     $this->assertTrue($response->is_success(), 'Should have handled empty body without causing error');
 }
 public static function makeRequest(HttpRequest $request)
 {
     $requestUri = $request->getRequestUri()->getUri();
     // if the request is towards a file URL, return the response constructed
     // from file
     if (0 === strpos($requestUri, "file:///")) {
         return HttpResponse::fromFile($requestUri);
     }
     $httpResponse = new HttpResponse();
     $curlChannel = curl_init();
     curl_setopt($curlChannel, CURLOPT_URL, $requestUri);
     curl_setopt($curlChannel, CURLOPT_FOLLOWLOCATION, 1);
     curl_setopt($curlChannel, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($curlChannel, CURLOPT_TIMEOUT, 10);
     if ($request->getRequestMethod() === "POST") {
         curl_setopt($curlChannel, CURLOPT_POST, 1);
         curl_setopt($curlChannel, CURLOPT_POSTFIELDS, $request->getContent());
     }
     $basicAuthUser = $request->getBasicAuthUser();
     $basicAuthPass = $request->getBasicAuthPass();
     if (NULL !== $basicAuthUser) {
         $request->setHeader("Authorization", "Basic " . base64_encode($basicAuthUser . ":" . $basicAuthPass));
     }
     // Including HTTP headers in request
     $headers = $request->getHeaders(TRUE);
     if (!empty($headers)) {
         curl_setopt($curlChannel, CURLOPT_HTTPHEADER, $headers);
     }
     // Connect to SSL/TLS server, validate certificate and host
     if ($request->getRequestUri()->getScheme() === "https") {
         curl_setopt($curlChannel, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($curlChannel, CURLOPT_SSL_VERIFYHOST, 2);
     }
     // Callback to extract all the HTTP headers from the response...
     // In order to really correctly parse HTTP headers one would have to look at RFC 2616...
     curl_setopt($curlChannel, CURLOPT_HEADERFUNCTION, function ($curlChannel, $header) use($httpResponse) {
         // Ignore Status-Line (RFC 2616, section 6.1)
         if (0 === preg_match('|^HTTP/\\d+.\\d+ [1-5]\\d\\d|', $header)) {
             // Only deal with header lines that contain a colon
             if (strpos($header, ":") !== FALSE) {
                 // Only deal with header lines that contain a colon
                 list($key, $value) = explode(":", trim($header));
                 $httpResponse->setHeader(trim($key), trim($value));
             }
         }
         return strlen($header);
     });
     $output = curl_exec($curlChannel);
     if ($errorNumber = curl_errno($curlChannel)) {
         throw new OutgoingHttpRequestException(curl_error($curlChannel));
     }
     $httpResponse->setStatusCode(curl_getinfo($curlChannel, CURLINFO_HTTP_CODE));
     $httpResponse->setContent($output);
     curl_close($curlChannel);
     return $httpResponse;
 }
Example #10
0
 /**
  * Construct the OAuth 2 error using a response object
  *
  * @param \HttpResponse $response The response object
  */
 public function __construct($response)
 {
     $response->error = $this;
     $this->response = $response;
     $parsedResponse = $response->parse();
     if (is_array($parsedResponse)) {
         $this->code = isset($parsedResponse['error']) ? $parsedResponse['error'] : 0;
         $this->message = isset($parsedResponse['error_description']) ? $parsedResponse['error_description'] : null;
     }
 }
Example #11
0
 public function send($url)
 {
     curl_setopt($this->handler, CURLOPT_URL, $url);
     $this->response_body = curl_exec($this->handler);
     $response = HttpResponse::separate($this->response_body, array('header_size' => curl_getinfo($this->handler, CURLINFO_HEADER_SIZE)));
     return $response;
 }
Example #12
0
 /**
  * Implement a virtual 'headers' class property to return their respective objects.
  *
  * @param   string $name  The property name.
  * @return  string $value The property value.
  */
 public function __get($name)
 {
     if ($name == 'headers') {
         return $this->getHeaders();
     }
     return parent::__get($name);
 }
Example #13
0
 function HttpServletResponse(&$servletcontext)
 {
     parent::HttpResponse();
     if (ServletContext::validClass($servletcontext)) {
         $this->context =& $servletcontext;
     }
 }
Example #14
0
 public function getRedirectResponse()
 {
     if (!$this->isRedirect()) {
         throw new RuntimeException('This response does not support redirection.');
     }
     $output = json_encode($this->getData());
     return HttpResponse::create($output);
 }
Example #15
0
 private function _getResponse($request)
 {
     $response = [];
     $request['httpStatus'] = "200";
     $request['httpReasonPhrase'] = "OK";
     $request['body'] = "";
     if (file_exists('.' . $request['uri']) === true) {
         $request['body'] = file_get_contents('.' . $request['uri']);
     } else {
         $request['httpStatus'] = "400";
         $request['httpReasonPhrase'] = "NOT FOUND";
     }
     $httpResponse = new HttpResponse($request);
     $response['header'] = $httpResponse->getResponseHeader();
     $response['body'] = $httpResponse->getResponseBody();
     return $response;
 }
/**
 * Test HttpResponse.
 */
function test_HttpResponse()
{
    HttpResponse::setCache(true);
    HttpResponse::setContentType('application/pdf');
    HttpResponse::setContentDisposition("test.pdf", false);
    HttpResponse::setFile('sheet.pdf');
    HttpResponse::send();
}
Example #17
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;
 }
Example #18
0
File: HTTP.php Project: jasny/Q
 /**
  * Redirect client to other URL.
  * This is done by issuing a "Location" header and exiting if wanted.
  * 
  * Returns true on succes (or exits) or false if headers have already been sent.
  * Will append output rewrite vars.
  * 
  * @param string  $url      URL where the redirect should go to.
  * @param array   $params   Associative array of query parameters
  * @param boolean $rewrite  Add URL rewrite variables (null is auto-detect) 
  * @param int     $status   HTTP status code to use for redirect, valid values are 301, 302, 303 and 307.
  * @return boolean 
  */
 public static function redirect($url, $params = array(), $rewrite = null, $status = 302)
 {
     if ($rewrite || $rewrite === null && strpos(':', $url) === false) {
         if (!is_array($params)) {
             $params = (array) $params;
         }
         $params += self::getUrlRewriteVars();
     }
     return parent::redirect($url, $params, false, $status);
 }
Example #19
0
function ajaxShutdown()
{
    $isError = false;
    if ($error = error_get_last()) {
        switch ($error['type']) {
            case E_ERROR:
            case E_CORE_ERROR:
            case E_COMPILE_ERROR:
            case E_USER_ERROR:
            case E_PARSE:
                $log_file = ini_get("error_log");
                if (file_exists($log_file)) {
                    $number_of_characters_to_get = 5000;
                    $bf = new BigFile($log_file);
                    $text = $bf->getFromEnd($number_of_characters_to_get);
                    $lines = array_reverse(explode("\n", $text));
                    $backtrace = "";
                    foreach ($lines as $i => $line) {
                        if (strstr($line, "Fatal")) {
                            for ($j = $i; $j > 0; $j--) {
                                $backtrace .= $lines[$j] . "\n";
                            }
                            break;
                        }
                    }
                    if ($backtrace == "") {
                        $backtrace = "No Fatal error found in the last {$number_of_characters_to_get} lines of {$log_file}";
                    }
                } else {
                    $backtrace = "No error log found at " . $log_file;
                }
                $isError = true;
                break;
        }
    }
    if ($isError) {
        send_http_error(new Exception("E_ERROR " . $error['message'] . "\n file: " . $error['file'] . " (" . $error['line'] . ")", E_FATAL_ERROR), "FATAL ERROR. shutdown function tried to restore backtrace from php error log ({$log_file}):\n" . $backtrace, true);
        $response = new HttpResponse();
        $response->setStatus("400 Bad Request");
        $response->write("E_ERROR " . $error['message'] . "\n file: " . $error['file'] . " (" . $error['line'] . ")");
        $response->flush();
    }
}
Example #20
0
 /**
  * @param \Blar\Curl\Curl $curl Curl.
  * @param \Blar\Http\HttpResponse $response Response.
  * @return $this
  */
 protected function configureCurl(Curl $curl, HttpResponse $response)
 {
     $curl->setMethod($this->getMethod());
     $curl->setUrl($this->getUrl());
     if ($this->getHeaders()) {
         $headers = $this->createHeadersArray($this->getHeaders());
         $curl->setOption(CURLOPT_HTTPHEADER, $headers);
     }
     if ($this->getBody()) {
         $curl->setBody($this->getBody());
     }
     $curl->setHeaderCallback(function ($header) use($response) {
         $response->setHeaderLine($header);
     });
     $curl->setWriteCallback(function ($part) use($response) {
         $response->addBodyPart($part);
     });
     return $this;
 }
Example #21
0
 function threadmain()
 {
     // Read request block
     $buf = "";
     while (true) {
         $rl = socket_read($this->sock, 4096, PHP_BINARY_READ);
         if (false == $rl) {
             socket_close($this->sock);
             return;
         } else {
             $buf = $buf . $rl;
         }
         if (strpos($buf, "\r\n\r\n")) {
             break;
         } else {
             console::writeLn('%s', $buf);
         }
     }
     $db = explode("\r\n\r\n", $buf);
     $data = $db[0];
     // Put back the rest of the buffer for posts etc
     $buf = join('', array_slice($db, 1));
     $request = new HttpRequest($data);
     // data
     $response = new HttpResponse();
     // Pop the header off the buffer
     $status = call_user_func_array($this->handler, array(&$request, &$response));
     if ($status == 0) {
         $status = 200;
     }
     $peer = "";
     $port = 0;
     socket_getpeername($this->sock, $peer, $port);
     console::writeLn("%s %s:%d %d %s", $request->getMethod(), $peer, $port, $status, $request->getUri());
     $response->writeHeaders($this->sock, 200);
     $response->writeContent($this->sock);
     socket_shutdown($this->sock, 2);
     usleep(50000);
     socket_close($this->sock);
 }
 /**
  * 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());
     $this->cat && $this->cat->info('>>>', $request->getHeaderString());
     $response = new HttpResponse(new SocketInputStream($s));
     $this->cat && $this->cat->info('<<<', $response->getHeaderString());
     return $response;
 }
Example #23
0
 public static function curl($url, $httpMethod = "GET", $postFields = null, $headers = null)
 {
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod);
     if (ENABLE_HTTP_PROXY) {
         curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
         curl_setopt($ch, CURLOPT_PROXY, HTTP_PROXY_IP);
         curl_setopt($ch, CURLOPT_PROXYPORT, HTTP_PROXY_PORT);
         curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
     }
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_FAILONERROR, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postFields) ? self::getPostHttpBody($postFields) : $postFields);
     if (self::$readTimeout) {
         curl_setopt($ch, CURLOPT_TIMEOUT, self::$readTimeout);
     }
     if (self::$connectTimeout) {
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout);
     }
     //https request
     if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     }
     if (is_array($headers) && 0 < count($headers)) {
         $httpHeaders = self::getHttpHearders($headers);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
     }
     $httpResponse = new HttpResponse();
     $httpResponse->setBody(curl_exec($ch));
     $httpResponse->setStatus(curl_getinfo($ch, CURLINFO_HTTP_CODE));
     if (curl_errno($ch)) {
         throw new ClientException("Speicified endpoint or uri is not valid.", "SDK.ServerUnreachable");
     }
     curl_close($ch);
     return $httpResponse;
 }
 /**
  * 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->excludes()->contains($request->getUrl())) {
         curl_setopt($curl, CURLOPT_PROXY, $this->proxy->host());
         curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy->port());
         $read = function ($transfer) {
             if (preg_match('#^HTTP/[0-9]\\.[0-9] [0-9]{3} .+\\r\\n\\r\\n#', $transfer, $matches)) {
                 // Strip "HTTP/x.x 200 Connection established" which is followed by
                 // the real HTTP message: headers and body
                 return substr($transfer, strlen($matches[0]));
             } else {
                 return $transfer;
             }
         };
     } else {
         $read = function ($transfer) {
             return $transfer;
         };
     }
     $return = curl_exec($curl);
     if (false === $return) {
         $errno = curl_errno($curl);
         $error = curl_error($curl);
         curl_close($curl);
         throw new \io\IOException(sprintf('%d: %s', $errno, $error));
     }
     // ensure handle is closed
     curl_close($curl);
     $this->cat && $this->cat->info('>>>', $request->getHeaderString());
     $response = new HttpResponse(new MemoryInputStream($read($return)), false);
     $this->cat && $this->cat->info('<<<', $response->getHeaderString());
     return $response;
 }
 /**
  * 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);
     $this->cat && $this->cat->info('>>>', $request->getHeaderString());
     $response = new HttpResponse(new MemoryInputStream($response));
     $this->cat && $this->cat->info('<<<', $response->getHeaderString());
     return $response;
 }
Example #26
0
 /**
  * Sends the response using the result
  * 
  * @param mixed $result Result
  * @return void
  */
 public function send($result = null)
 {
     if ($result instanceof HttpResponse) {
         $result->send();
         exit;
     }
     // Output the result
     if (!$result instanceof GenericResult) {
         $result = new SuccessResult($result);
     }
     $result = elgg_trigger_plugin_hook('result', 'graph', null, $result);
     $output = elgg_view('graph/output', array('result' => $result));
     if (elgg_get_viewtype() === 'default') {
         $layout = elgg_view_layout('one_column', array('content' => $output));
         $output = elgg_view_page('', $layout);
     }
     $this->response->setStatusCode($result->getStatusCode())->setContent($output)->prepare($this->request)->send();
     exit;
 }
 /**
  * Processes this batch. This sends the captured requests to the server as one batch.
  *
  * @throws ClientException
  * @return bool - true if processing of the batch was  or the HttpResponse object in case of a failure. A successful process just means that tha parts were processed. Each part has it's own response though and should be checked on its own.
  */
 public function process()
 {
     $this->stopCapture();
     $this->setBatchRequest(true);
     $data = '';
     $batchParts = $this->getBatchParts();
     if (count($batchParts) == 0) {
         throw new ClientException('Can\'t process empty batch.');
     }
     /** @var $partValue BatchPart */
     foreach ($batchParts as $partValue) {
         $data .= '--' . HttpHelper::MIME_BOUNDARY . HttpHelper::EOL;
         $data .= 'Content-Type: application/x-arango-batchpart' . HttpHelper::EOL;
         if (!is_null($partValue->getId())) {
             $data .= 'Content-Id: ' . (string) $partValue->getId() . HttpHelper::EOL . HttpHelper::EOL;
         } else {
             $data .= HttpHelper::EOL;
         }
         $data .= (string) $partValue->getRequest() . HttpHelper::EOL;
     }
     $data .= '--' . HttpHelper::MIME_BOUNDARY . '--' . HttpHelper::EOL . HttpHelper::EOL;
     $params = array();
     $url = UrlHelper::appendParamsUrl(Urls::URL_BATCH, $params);
     $this->_batchResponse = $this->_connection->post($url, $data);
     if ($this->_batchResponse->getHttpCode() !== 200) {
         return $this->_batchResponse;
     }
     $body = $this->_batchResponse->getBody();
     $body = trim($body, '--' . HttpHelper::MIME_BOUNDARY . '--');
     $batchParts = $this->splitWithContentIdKey('--' . HttpHelper::MIME_BOUNDARY . HttpHelper::EOL, $body);
     foreach ($batchParts as $partKey => $partValue) {
         $response = new HttpResponse($partValue);
         $body = $response->getBody();
         $response = new HttpResponse($body);
         $batchPartResponses[$partKey] = $response;
         $this->getPart($partKey)->setResponse($batchPartResponses[$partKey]);
     }
     return $this;
 }
Example #28
0
    function testGeneral()
    {
        $str = <<<EOF
HTTP/1.1 500 Server error
Host: localhost:8080
X-Powered-By: PHP/5.4.31
bc-param1: hello, world
Content-Type: text/plain

Exception: exception 'PDOException'
EOF;
        $res = new HttpResponse($str);
        $this->assertEquals(500, $res->code);
        $this->assertEquals("Server error", $res->message);
        $this->assertEquals("localhost:8080", $res->headers["HOST"]);
        $this->assertEquals("Exception: exception 'PDOException'", $res->body);
        $this->assertEquals("hello, world", $res->getHeader("bc-param1"));
        $this->assertEquals("hello, world", $res->getBCParam("param1"));
        $this->assertNull($res->getHeader("bc-param2"));
        $this->assertNull($res->getBCParam("param2"));
        $this->assertEquals($str, $res->toString());
    }
Example #29
0
 /**
  * Attempts to cache the sent entity by its last modification date
  * @param  int    last modified time as unix timestamp
  * @param  string strong entity tag validator
  * @param  int    optional expiration time
  * @return int    date of the client's cache version, if available
  * @throws TerminateException
  */
 public function lastModified($lastModified, $etag = NULL, $expire = NULL)
 {
     if (!Environment::isProduction()) {
         return NULL;
     }
     $httpResponse = $this->getHttpResponse();
     $match = FALSE;
     if ($lastModified > 0) {
         $httpResponse->setHeader('Last-Modified', HttpResponse::date($lastModified));
     }
     if ($etag != NULL) {
         // intentionally ==
         $etag = '"' . addslashes($etag) . '"';
         $httpResponse->setHeader('ETag', $etag);
     }
     if ($expire !== NULL) {
         $httpResponse->expire($expire);
     }
     $ifNoneMatch = $this->getHttpRequest()->getHeader('if-none-match');
     $ifModifiedSince = $this->getHttpRequest()->getHeader('if-modified-since');
     if ($ifModifiedSince !== NULL) {
         $ifModifiedSince = strtotime($ifModifiedSince);
     }
     if ($ifNoneMatch !== NULL) {
         if ($ifNoneMatch === '*') {
             $match = TRUE;
             // match, check if-modified-since
         } elseif ($etag == NULL || strpos(' ' . strtr($ifNoneMatch, ",\t", '  '), ' ' . $etag) === FALSE) {
             return $ifModifiedSince;
             // no match, ignore if-modified-since
         } else {
             $match = TRUE;
             // match, check if-modified-since
         }
     }
     if ($ifModifiedSince !== NULL) {
         if ($lastModified > 0 && $lastModified <= $ifModifiedSince) {
             $match = TRUE;
         } else {
             return $ifModifiedSince;
         }
     }
     if ($match) {
         $httpResponse->setCode(IHttpResponse::S304_NOT_MODIFIED);
         $httpResponse->setHeader('Content-Length', '0');
         $this->terminate();
     } else {
         return $ifModifiedSince;
     }
     return NULL;
 }
Example #30
0
 /**
  * Test's the init function of the http parser instance
  */
 public function testInitFunction()
 {
     $parser = $this->parser;
     // build up request
     $parser->parseStartLine('GET / HTTP/1.1');
     $parser->parseHeaderLine('Host: localhost');
     // build up response
     $parser->getResponse()->setStatus(200);
     $parser->getResponse()->appendBodyStream('Hello World');
     // get clean request and response objects
     $cleanRequest = new HttpRequest();
     $cleanResponse = new HttpResponse();
     // remove those resources to be able to compare them via php unit
     $cleanRequest->setBodyStream(null);
     $cleanResponse->setBodyStream(null);
     // finally init parser
     $parser->init();
     // remove those resources to be able to compare them via php unit
     $parser->getRequest()->setBodyStream(null);
     $parser->getResponse()->setBodyStream(null);
     $this->assertEquals($cleanRequest, $parser->getRequest());
     $this->assertEquals($cleanResponse, $parser->getResponse());
 }