public function onRoute(MvcEvent $e)
 {
     $request = $e->getRequest();
     if (!$request instanceof HttpRequest) {
         return;
     }
     $application = $e->getApplication();
     $serviceLocator = $application->getServiceManager();
     // Load the configuration for maintenance mode
     if ($serviceLocator->has('MaintenanceConfig')) {
         $config = $serviceLocator->get('MaintenanceConfig');
     } else {
         $config = new Config();
     }
     if (!$config->isEnabled()) {
         // Maintenance mode is disabled.
         return;
     }
     // Check the white list
     if ($request instanceof PhpRequest) {
         $address = $request->getServer('REMOTE_ADDR', null);
     } else {
         $address = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
     }
     if (!empty($address)) {
         if (in_array($address, $config->getWhitelist())) {
             return;
         }
     }
     // Render the maintenance layout
     $renderer = new PhpRenderer();
     if ($serviceLocator->has('ViewHelperManager')) {
         $renderer->setHelperPluginManager($serviceLocator->get('ViewHelperManager'));
     }
     $resolver = new TemplateMapResolver();
     $resolver->add('maintenance', $config->getTemplate());
     $renderer->setResolver($resolver);
     $content = $renderer->render('maintenance');
     // Set the response
     $response = $e->getResponse();
     if (!$response instanceof HttpResponse) {
         $response = new HttpResponse();
     }
     $statusCode = $config->getStatusCode();
     $response->setStatusCode($statusCode);
     if ($statusCode === 503 && !$response->getHeaders()->has('Retry-After')) {
         $retryDate = $config->getRetryAfter();
         if ($retryDate instanceof DateTime) {
             $retryAfter = new RetryAfter();
             $retryAfter->setDate($retryDate);
             $response->getHeaders()->addHeader($retryAfter);
         }
     }
     $response->setContent($content);
     $e->setResponse($response);
     // Return the response
     return $response;
 }
예제 #2
1
파일: VCard.php 프로젝트: zource/zource
 public function vCardAction()
 {
     $contact = $this->contactService->find($this->params('id'));
     if (!$contact) {
         return $this->notFoundAction();
     }
     $builder = new VCardBuilder();
     switch (true) {
         case $contact instanceof Company:
             $vcard = $builder->buildCompany($contact);
             break;
         case $contact instanceof Person:
             $vcard = $builder->buildPerson($contact);
             break;
         default:
             throw new RuntimeException('Invalid type provided.');
     }
     $data = $vcard->serialize();
     $response = new Response();
     $response->setStatusCode(Response::STATUS_CODE_200);
     $response->setContent($data);
     $headers = $response->getHeaders();
     $headers->addHeaderLine('Content-Disposition', 'attachment; filename="' . $contact->getDisplayName() . '.vcf"');
     $headers->addHeaderLine('Content-Length', strlen($data));
     $headers->addHeaderLine('Content-Type', 'text/plain');
     return $response;
 }
예제 #3
0
function plugin_preview_action()
{
    global $vars;
    $page = isset($vars['page']) ? $vars['page'] : '';
    $modified = 0;
    $response = new Response();
    if (!empty($page)) {
        $wiki = Factory::Wiki($page);
        if ($wiki->isReadable()) {
            $source = $wiki->get();
            array_splice($source, 10);
            $response->setStatusCode(Response::STATUS_CODE_200);
            $response->setContent('<' . '?xml version="1.0" encoding="UTF-8"?' . ">\n" . RendererFactory::factory($source));
            $headers = Header::getHeaders('text/xml', $wiki->time());
        } else {
            $response->setStatusCode(Response::STATUS_CODE_404);
            $headers = Header::getHeaders('text/xml');
        }
    } else {
        $response->setStatusCode(Response::STATUS_CODE_404);
        $headers = Header::getHeaders('text/xml');
    }
    $response->getHeaders()->addHeaders($headers);
    header($response->renderStatusLine());
    foreach ($response->getHeaders() as $_header) {
        header($_header->toString());
    }
    echo $response->getBody();
    exit;
}
예제 #4
0
 protected function assertResponseNotInjected()
 {
     $content = $this->response->getContent();
     $headers = $this->response->getHeaders();
     $this->assertEmpty($content);
     $this->assertFalse($headers->has('content-type'));
 }
예제 #5
0
 /**
  * Encode data as JSON and set response header
  *
  * @param  mixed $data
  * @param  array $jsonOptions Options to pass to JsonFormatter::encode()
  * @return string|void
  */
 public function __invoke($data, array $jsonOptions = array())
 {
     $data = JsonFormatter::encode($data, null, $jsonOptions);
     if ($this->response instanceof Response) {
         $headers = $this->response->getHeaders();
         $headers->addHeaderLine('Content-Type', 'application/json');
     }
     return $data;
 }
 public function testSave()
 {
     $expectedDate = new \DateTime('2015-01-01');
     $request = new Request('GET', 'http://example.com');
     $response = new Response();
     $listener = new TimetableCookieListener($request, $response);
     $event = new TimetableManagerEvent();
     $event->setPointInTime($expectedDate);
     $listener->storeTime($event);
     $this->assertTrue($response->getHeaders()->has('Set-Cookie'));
     $cookie = current($response->getHeaders()->get('Set-Cookie'));
     $this->assertEquals($expectedDate, new \DateTime($cookie->getValue()));
 }
 /**
  * Parses the HTTP response from a userinfo request.
  * 
  * @param Http\Response $httpResponse
  * @throws HttpAuthenticateException
  * @throws HttpErrorStatusException
  * @throws InvalidResponseFormatException
  * @throws Exception\InvalidResponseException
  */
 public function handleResponse(Http\Response $httpResponse)
 {
     if (!$httpResponse->isSuccess()) {
         $statusCode = $httpResponse->getStatusCode();
         if (401 === $statusCode && ($authenticateHeader = $httpResponse->getHeaders()->get($this->wwwAuthenticateHeaderName)->current())) {
             $params = $this->parseAuthenticateHeaderValue($authenticateHeader->getFieldValue());
             if (isset($params['error'])) {
                 $this->setError($this->getErrorFactory()->createErrorFromArray($params));
                 return;
             }
             throw new HttpAuthenticateException(sprintf("Missing error information in WWW-Authenticate header: %s", $authenticateHeader->getFieldValue()));
         }
         throw new HttpErrorStatusException(sprintf("Error status response from server: %s", $statusCode));
     }
     try {
         $responseData = $this->getJsonCoder()->decode($httpResponse->getBody());
     } catch (\Exception $e) {
         throw new InvalidResponseFormatException('The HTTP response does not contain valid JSON', null, $e);
     }
     try {
         $this->response = $this->getResponseFactory()->createResponse($responseData);
     } catch (\Exception $e) {
         throw new Exception\InvalidResponseException(sprintf("Invalid response: [%s] %s", get_class($e), $e->getMessage()), null, $e);
     }
 }
예제 #8
0
 /**
  * @runInSeparateProcess
  */
 public function testSendHeadersTwoTimesSendsOnlyOnce()
 {
     if (!function_exists('xdebug_get_headers')) {
         $this->markTestSkipped('Xdebug extension needed, skipped test');
     }
     $headers = array('Content-Length: 2000', 'Transfer-Encoding: chunked');
     $response = new Response();
     $response->getHeaders()->addHeaders($headers);
     $mockSendResponseEvent = $this->getMock('Zend\\Mvc\\ResponseSender\\SendResponseEvent', array('getResponse'));
     $mockSendResponseEvent->expects($this->any())->method('getResponse')->will($this->returnValue($response));
     $responseSender = $this->getMockForAbstractClass('Zend\\Mvc\\ResponseSender\\AbstractResponseSender');
     $responseSender->sendHeaders($mockSendResponseEvent);
     $sentHeaders = xdebug_get_headers();
     $diff = array_diff($sentHeaders, $headers);
     if (count($diff)) {
         $header = array_shift($diff);
         $this->assertContains('XDEBUG_SESSION', $header);
         $this->assertEquals(0, count($diff));
     }
     $expected = array();
     if (version_compare(phpversion('xdebug'), '2.2.0', '>=')) {
         $expected = xdebug_get_headers();
     }
     $responseSender->sendHeaders($mockSendResponseEvent);
     $this->assertEquals($expected, xdebug_get_headers());
 }
    public function testInvokeForDigestAuthAddsAuthorizationHeader()
    {
        $httpAuth = new HttpAuth(array(
            'accept_schemes' => 'digest',
            'realm' => 'User Area',
            'digest_domains' => '/',
            'nonce_timeout' => 3600,
        ));
        $httpAuth->setDigestResolver(new HttpAuth\FileResolver(__DIR__ . '/../TestAsset/htdigest'));
        $this->listener->setHttpAdapter($httpAuth);

        $this->listener->__invoke($this->mvcAuthEvent);

        $authHeaders = $this->response->getHeaders()->get('WWW-Authenticate');
        $authHeader = $authHeaders[0];
        $this->assertInstanceOf('Zend\Http\Header\HeaderInterface', $authHeader);
        $this->assertRegexp(
            '#^Digest realm="User Area", domain="/", '
            . 'nonce="[a-f0-9]{32}", '
            . 'opaque="e66aa41ca5bf6992a5479102cc787bc9", '
            . 'algorithm="MD5", '
            . 'qop="auth"$#',
            $authHeader->getFieldValue()
        );
    }
예제 #10
0
 /**
  * Creates the response to be returned for a QR Code
  * @param $content
  * @param $contentType
  * @return HttpResponse
  */
 protected function createResponse($content, $contentType)
 {
     $resp = new HttpResponse();
     $resp->setStatusCode(200)->setContent($content);
     $resp->getHeaders()->addHeaders(array('Content-Length' => strlen($content), 'Content-Type' => $contentType));
     return $resp;
 }
예제 #11
0
 /**
  * Immediately send headers from a Zend\Http\Response
  * 
  * @param ZendResponse $zresponse Zend\Http\Response
  * 
  * @return void
  */
 public static function sendHeaders(ZendResponse $zresponse)
 {
     $headers = $zresponse->getHeaders()->toArray();
     foreach ($headers as $key => $value) {
         header(sprintf('%s: %s', $key, $value));
     }
 }
예제 #12
0
 public function onRoute(MvcEvent $e)
 {
     $serviceManager = $e->getApplication()->getServiceManager();
     $routeMatchName = $e->getRouteMatch()->getMatchedRouteName();
     if (strpos($routeMatchName, '.rest.') !== false || strpos($routeMatchName, '.rpc.') !== false) {
         return;
     }
     $config = $serviceManager->get('Config');
     $identityGuards = $config['zource_guard']['identity'];
     $needsIdentity = null;
     foreach ($identityGuards as $guard => $needed) {
         if (fnmatch($guard, $routeMatchName)) {
             $needsIdentity = $needed;
             break;
         }
     }
     if ($needsIdentity === null) {
         throw new RuntimeException(sprintf('The identity guard "%s" has not been configured.', $routeMatchName));
     }
     if (!$needsIdentity) {
         return;
     }
     $authenticationService = $serviceManager->get('Zend\\Authentication\\AuthenticationService');
     if ($authenticationService->hasIdentity()) {
         return;
     }
     $returnUrl = $e->getRouter()->assemble([], ['name' => $routeMatchName, 'force_canonical' => true, 'query' => $e->getRequest()->getUri()->getQuery()]);
     $url = $e->getRouter()->assemble([], ['name' => 'login', 'query' => ['redir' => $returnUrl]]);
     $response = new Response();
     $response->setStatusCode(Response::STATUS_CODE_302);
     $response->getHeaders()->addHeaderLine('Location: ' . $url);
     return $response;
 }
예제 #13
0
 /**
  * {@inheritdoc}
  */
 public function decode(Response $response)
 {
     $headers = $response->getHeaders();
     if (!$headers->has('Content-Type')) {
         $exception = new Exception\InvalidResponseException('Content-Type missing');
         $exception->setResponse($response);
         throw $exception;
     }
     /* @var $contentType \Zend\Http\Header\ContentType */
     $contentType = $headers->get('Content-Type');
     switch (true) {
         case $contentType->match('*/json'):
             $payload = Json::decode($response->getBody(), Json::TYPE_ARRAY);
             break;
             //TODO: xml
             //             case $contentType->match('*/xml'):
             //                 $xml = Security::scan($response->getBody());
             //                 $payload = Json::decode(Json::encode((array) $xml), Json::TYPE_ARRAY);
             //                 break;
         //TODO: xml
         //             case $contentType->match('*/xml'):
         //                 $xml = Security::scan($response->getBody());
         //                 $payload = Json::decode(Json::encode((array) $xml), Json::TYPE_ARRAY);
         //                 break;
         default:
             throw new Exception\InvalidFormatException(sprintf('The "%s" media type is invalid or not supported', $contentType->getMediaType()));
             break;
     }
     $this->lastPayload = $payload;
     if ($contentType->match('*/hal+*')) {
         return $this->extractResourceFromHal($payload, $this->getPromoteTopCollection());
     }
     //else
     return (array) $payload;
 }
예제 #14
0
 /**
  * Get the exception and optionally set status code, reason message and additional errors
  *
  * @internal
  * @param  MvcEvent $event
  * @return void
  */
 public function onDispatchError(MvcEvent $event)
 {
     $exception = $event->getParam('exception');
     if (isset($this->exceptionMap[get_class($exception)])) {
         $exception = $this->createHttpException($exception);
     }
     // We just deal with our Http error codes here !
     if (!$exception instanceof HttpExceptionInterface || $event->getResult() instanceof HttpResponse) {
         return;
     }
     // We clear the response for security purpose
     $response = new HttpResponse();
     $response->getHeaders()->addHeaderLine('Content-Type', 'application/json');
     $exception->prepareResponse($response);
     // NOTE: I'd like to return a JsonModel instead, and let ZF handle the request, but I couldn't make
     // it work because for unknown reasons, the Response get replaced "somewhere" in the MVC workflow,
     // so the simplest is simply to do that
     $content = ['status_code' => $response->getStatusCode(), 'message' => $response->getReasonPhrase()];
     if ($errors = $exception->getErrors()) {
         $content['errors'] = $errors;
     }
     $response->setContent(json_encode($content));
     $event->setResponse($response);
     $event->setResult($response);
     $event->stopPropagation(true);
 }
예제 #15
0
    /**
     * Challenge Client
     *
     * Sets a 401 or 407 Unauthorized response code, and creates the
     * appropriate Authenticate header(s) to prompt for credentials.
     *
     * @return Authentication\Result Always returns a non-identity Auth result
     */
    protected function _challengeClient()
    {
        if ($this->imaProxy) {
            $statusCode = 407;
            $headerName = 'Proxy-Authenticate';
        } else {
            $statusCode = 401;
            $headerName = 'WWW-Authenticate';
        }

        $this->response->setStatusCode($statusCode);

        // Send a challenge in each acceptable authentication scheme
        $headers = $this->response->getHeaders();
        if (in_array('basic', $this->acceptSchemes)) {
            $headers->addHeaderLine($headerName, $this->_basicHeader());
        }
        if (in_array('digest', $this->acceptSchemes)) {
            $headers->addHeaderLine($headerName, $this->_digestHeader());
        }
        return new Authentication\Result(
            Authentication\Result::FAILURE_CREDENTIAL_INVALID,
            array(),
            array('Invalid or absent credentials; challenging client')
        );
    }
예제 #16
0
 public function testRequestCanSetHeaders()
 {
     $response = new Response();
     $headers = new \Zend\Http\Headers();
     $ret = $response->setHeaders($headers);
     $this->assertInstanceOf('Zend\\Http\\Response', $ret);
     $this->assertSame($headers, $response->getHeaders());
 }
예제 #17
0
파일: Api.php 프로젝트: fousheezy/auth
 protected function setResponseContent(Response $response, array $data)
 {
     if ($response instanceof \Zend\Http\PhpEnvironment\Response) {
         $response->getHeaders()->addHeaderLine('Content-Type', 'application/json');
         $response->setContent(json_encode(array_merge(array('status' => $response->getStatusCode()), $data)));
     }
     return $response;
 }
예제 #18
0
 /**
  * Retrieve headers.
  *
  * Proxies to parent class, but then checks if we have an content-type
  * header; if not, sets it, with a value of "application/problem+json".
  *
  * @return \Zend\Http\Headers
  */
 public function getHeaders()
 {
     $headers = parent::getHeaders();
     if (!$headers->has('content-type')) {
         $headers->addHeaderLine('content-type', ApiProblem::CONTENT_TYPE);
     }
     return $headers;
 }
예제 #19
0
 /**
  * Set Response Header for PDF
  *
  * @param  mixed $data
  * @return string|void
  */
 public function __invoke($data, $filename = "")
 {
     $length = strlen($data);
     if (!$this->response instanceof Response || substr($data, 0, 5) != '%PDF-') {
         return $data;
     }
     // var_dump($data); exit;
     $headers = $this->response->getHeaders();
     if (empty($filename)) {
         $headers->addHeaderLine('Content-Type', 'application/pdf');
         $headers->addHeaderLine('Content-Length', $length);
     } else {
         $headers->addHeaderLine("Content-Type: application/force-download");
         $headers->addHeaderLine('Content-Disposition: attachment; filename="' . urlencode($filename) . '"');
     }
     return $data;
 }
예제 #20
0
 /**
  * Retrieve headers
  *
  * Proxies to parent class, but then checks if we have an content-type
  * header; if not, sets it, with a value of "application/api-problem+json".
  *
  * @return \Zend\Http\Headers
  */
 public function getHeaders()
 {
     $headers = parent::getHeaders();
     if (!$headers->has('content-type')) {
         $headers->addHeaderLine('content-type', 'application/api-problem+json');
     }
     return $headers;
 }
예제 #21
0
 public function testConstructorWithHttpResponse()
 {
     $httpResponse = new Response();
     $httpResponse->setStatusCode(200);
     $httpResponse->getHeaders()->addHeaderLine('Content-Type', 'text/html');
     $response = new CaptchaResponse($httpResponse);
     $this->assertSame(true, $response->getStatus());
 }
예제 #22
0
 public function testConstructorWithMissingStatus()
 {
     $params = array('error' => 'error');
     $httpResponse = new Response();
     $httpResponse->setStatusCode(200);
     $httpResponse->getHeaders()->addHeaderLine('Content-Type', 'text/html');
     $httpResponse->setContent(json_encode($params));
     $response = new CaptchaResponse($httpResponse);
     $this->assertSame(false, $response->getStatus());
 }
예제 #23
0
파일: Cookies.php 프로젝트: navassouza/zf2
 /**
  * Parse an HTTP response, adding all the cookies set in that response
  *
  * @param Response $response
  * @param Uri\Uri|string $ref_uri Requested URI
  */
 public function addCookiesFromResponse(Response $response, $ref_uri)
 {
     $cookie_hdrs = $response->getHeaders()->get('Set-Cookie');
     if (is_array($cookie_hdrs)) {
         foreach ($cookie_hdrs as $cookie) {
             $this->addCookie($cookie, $ref_uri);
         }
     } elseif (is_string($cookie_hdrs)) {
         $this->addCookie($cookie_hdrs, $ref_uri);
     }
 }
예제 #24
0
파일: Module.php 프로젝트: zfury/cmf
 /**
  * @param MvcEvent $e
  * @return Response
  */
 public function preDispatch(MvcEvent $e)
 {
     if (!$e->getRouteMatch()->getParam('module') || $e->getRouteMatch()->getParam('module') !== 'install') {
         $session = new Container('progress_tracker');
         $action = Install::getCurrentStep();
         $response = new Response();
         $response->setStatusCode(302);
         $response->getHeaders()->addHeaderLine('Location', "/install/index/{$action}");
         return $response;
     }
 }
 public function testSendHeadersMergesApplicationAndProblemHttpHeaders()
 {
     $appResponse = new HttpResponse();
     $appResponse->getHeaders()->addHeaderLine('Access-Control-Allow-Origin', '*');
     $listener = new SendApiProblemResponseListener();
     $listener->setApplicationResponse($appResponse);
     ob_start();
     $listener->sendHeaders($this->event);
     ob_get_clean();
     $headers = $this->response->getHeaders();
     $this->assertTrue($headers->has('Access-Control-Allow-Origin'));
 }
예제 #26
0
 /**
  * Wrap the Jaxon response into an HTTP response.
  *
  * @param  $code        The HTTP Response code
  *
  * @return \Zend\Http\Response
  */
 public function httpResponse($code = '200')
 {
     // Send HTTP Headers
     // $this->response->sendHeaders();
     // Create and return a ZF2 HTTP response
     $response = new HttpResponse();
     $headers = $response->getHeaders();
     $headers->addHeaderLine('Content-Type', $this->response->getContentType() . '; charset=' . $this->response->getCharacterEncoding());
     $response->setStatusCode(intval($code));
     $response->setContent($this->response->getOutput());
     return $response;
 }
예제 #27
0
 /**
  *
  */
 public function testInjectResponseSetsContentTypeHeaderToApiProblemForApiProblemModel()
 {
     $problem = new ApiProblem(500, "Error message");
     $model = new ApiProblemModel($problem);
     $this->event->setModel($model);
     $this->event->setRenderer($this->renderer);
     $this->event->setResult('{"foo":"bar"}');
     $this->strategy->injectResponse($this->event);
     $headers = $this->response->getHeaders();
     $this->assertTrue($headers->has('Content-Type'));
     $header = $headers->get('Content-Type');
     $this->assertEquals('application/problem+json', $header->getFieldValue());
 }
예제 #28
0
 public function testConstructorWithHttpResponse()
 {
     $status = 'false';
     $errorCode = 'foobar';
     $responseBody = $status . "\n" . $errorCode;
     $httpResponse = new Response();
     $httpResponse->setStatusCode(200);
     $httpResponse->getHeaders()->addHeaderLine('Content-Type', 'text/html');
     $httpResponse->setContent($responseBody);
     $response = new ReCaptcha\Response(null, null, $httpResponse);
     $this->assertSame(false, $response->getStatus());
     $this->assertSame($errorCode, $response->getErrorCode());
 }
예제 #29
0
 /**
  * Construtor.
  *
  * @param Zend\Http\Client   $client
  * @param Zend\Http\Response $response
  */
 public function __construct(ZendHttpClient $client, ZendHttpResponse $response, $depth = 0)
 {
     $this->httpClient = $client;
     $this->httpResponse = $response;
     if (!$this->httpResponse->isSuccess()) {
         $error = json_decode($this->httpResponse->getBody());
         if (empty($error)) {
             $error = new \stdClass();
             $error->status = $this->httpResponse->getStatusCode();
             $error->title = $this->httpResponse->getReasonPhrase();
             $error->detail = '';
         }
         if (!isset($error->status)) {
             $error->status = 500;
         }
         if (!isset($error->detail)) {
             $error->detail = 'An error occurred.';
         }
         throw new RuntimeException(json_encode($error, null, 100), $error->status);
     }
     if (!$this->httpResponse->getHeaders()->has('Content-Type')) {
         throw new RuntimeException("Missing 'Content-Type' header.", 500);
     }
     $contentType = $this->httpResponse->getHeaders()->get('Content-Type')->getFieldValue();
     $pos = strpos($contentType, ';');
     if ($pos !== false) {
         $contentType = substr($contentType, 0, $pos);
     }
     if (empty($this->httpResponse->getBody())) {
         $this->content = null;
     } elseif ($contentType == 'application/hal+json' || $contentType == 'application/json') {
         $this->content = new Resource(Hal::fromJson($this->httpResponse->getBody(), $depth));
     } elseif ($contentType == 'application/hal+xml' || $contentType == 'application/xml') {
         $this->content = new Resource(Hal::fromXml($this->httpResponse->getBody(), $depth));
     } else {
         throw new RuntimeException("Unable to handle content type '{$contentType}' for response: '{$this->httpResponse->getBody()}'.", 500);
     }
 }
 public function testAppendAuthorizationToVaryIfAlreadyExists()
 {
     $request = new HttpRequest();
     $request->getHeaders()->addHeaderLine('Authorization', 'abc');
     $mvcEvent = new MvcEvent();
     $mvcEvent->setRequest($request);
     $response = new HttpResponse();
     $response->getHeaders()->addHeaderLine('Vary', 'Origin');
     $mvcEvent->setResponse($response);
     $listener = new AuthorizationVaryListener();
     $listener->alterVaryHeader($mvcEvent);
     $this->assertTrue($response->getHeaders()->has('Vary'));
     $this->assertEquals('Origin, Authorization', $response->getHeaders()->get('Vary')->getFieldValue());
 }