setResponse() public method

Set response
public setResponse ( Zend\Stdlib\ResponseInterface $response ) : MvcEvent
$response Zend\Stdlib\ResponseInterface
return MvcEvent
 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;
 }
 public function testReturnIfNotHttpResponse()
 {
     $response = $this->getMock(ResponseInterface::class);
     $response->expects($this->never())->method('setStatusCode');
     $this->event->setResponse($response);
     $this->assertNull($this->resourceResponseListener->finishResponse($this->event));
 }
 /**
  * Set up
  */
 public function setUp()
 {
     parent::setUp();
     $this->httpExceptionListener = new HttpExceptionListener();
     // Init the MvcEvent object
     $this->response = new HttpResponse();
     $this->event = new MvcEvent();
     $this->event->setResponse($this->response);
 }
Exemplo n.º 4
0
 protected function displayError($template, $status = 403)
 {
     $model = new ViewModel();
     $model->setTerminal(false);
     $model->setTemplate($template);
     /** @var $response  \Zend\Http\PhpEnvironment\Response */
     $response = $this->_event->getResponse();
     $response->setStatusCode($status);
     $this->_event->setResponse($response);
     $this->_event->setResult($model);
     return;
 }
 protected function setUp()
 {
     $this->console = $this->getMockOfConsole();
     $this->controller = new IndexController();
     $this->event = new MvcEvent();
     $this->request = new Request();
     $this->response = new Response();
     $this->routeMatch = new RouteMatch(array('controller' => 'index'));
     $this->controller->setConsole($this->console);
     $this->controller->setEvent($this->event);
     $this->event->setRequest($this->request);
     $this->event->setResponse($this->response);
     $this->event->setRouteMatch($this->routeMatch);
 }
Exemplo n.º 6
0
 public function testOnResponseWithoutAutoInstrument()
 {
     $this->moduleOptions->setBrowserTimingEnabled(true)->setBrowserTimingAutoInstrument(false);
     $this->client->expects($this->once())->method('getBrowserTimingHeader')->will($this->returnValue('<div class="browser-timing-header"></div>'));
     $this->client->expects($this->once())->method('getBrowserTimingFooter')->will($this->returnValue('<div class="browser-timing-footer"></div>'));
     $request = new HttpRequest();
     $this->event->setRequest($request);
     $response = new Response();
     $response->setContent('<html><head></head><body></body></html>');
     $this->event->setResponse($response);
     $this->listener->onResponse($this->event);
     $content = $response->getContent();
     $this->assertContains('<head><div class="browser-timing-header"></div></head>', $content);
     $this->assertContains('<body><div class="browser-timing-footer"></div></body>', $content);
 }
Exemplo n.º 7
0
 public function __invoke(MvcEvent $e)
 {
     $response = $e->getResponse();
     $this->rateLimitService->consume($e->getRouteMatch(), $e->getRequest());
     //var_dump($this->rateLimitService->getTopMeters('daily_limits'));exit;
     $status = $this->rateLimitService->getLimitStatus($e->getRouteMatch(), $e->getRequest(), 'daily_limits');
     if (!empty($status)) {
         //add info headers
         $headers = $response->getHeaders();
         $headers->addHeaderLine('X-RateLimit-Limit', $status['limit']);
         $headers->addHeaderLine('X-RateLimit-Remaining', $status['remaining']);
         $headers->addHeaderLine('X-RateLimit-Reset', $status['reset']);
         $response->setHeaders($headers);
     }
     if ($this->rateLimitService->isLimitExceeded()) {
         //trigger the ratelimit exceeded event
         $mvcLimitEvent = $this->mvcLimitEvent;
         $response = $this->eventManager->trigger(MvcLimitEvent::EVENT_RATELIMIT_EXCEEDED, $mvcLimitEvent, function ($r) {
             return $r instanceof Response;
         });
         $response = $response->last();
         return $response;
     } elseif ($this->rateLimitService->isLimitWarning()) {
         //trigger the ratelimit warning event
         $mvcLimitEvent = $this->mvcLimitEvent;
         $response = $this->eventManager->trigger(MvcLimitEvent::EVENT_RATELIMIT_WARN, $mvcLimitEvent, function ($r) {
             return $r instanceof Response;
         });
         $response = $response->last();
         $e->setResponse($response);
     }
 }
 /**
  * preDispatch Event Handler
  * Handle authentication process
  * Decide where user should be redirected to when logged in or not
  * 
  * 
  * @access public
  * @uses AuthenticationService
  * @uses Response
  * 
  * @param \Zend\Mvc\MvcEvent $event
  * @throws \Exception
  */
 public function preDispatch(MvcEvent $event)
 {
     // ACL dispatcher is used only in HTTP requests not console requests
     if (!$event->getRequest() instanceof HttpRequest) {
         return;
     }
     $userAuth = new AuthenticationService();
     $user = array();
     $signInController = 'DefaultModule\\Controller\\Sign';
     if ($userAuth->hasIdentity()) {
         $user = $userAuth->getIdentity();
     }
     $routeMatch = $event->getRouteMatch();
     $controller = $routeMatch->getParam('controller');
     $action = $routeMatch->getParam('action');
     if ($userAuth->hasIdentity() && isset($user['status']) && $user['status'] == 2) {
         $userAuth->clearIdentity();
         // redirect to sign/out
         $url = $event->getRouter()->assemble(array('action' => 'out'), array('name' => 'defaultSign'));
     } else {
         if ($userAuth->hasIdentity() && $controller == $signInController && $action == 'in') {
             // redirect to index
             $url = $event->getRouter()->assemble(array('action' => 'index'), array('name' => 'home'));
         }
     }
     if (isset($url)) {
         $event->setResponse(new Response());
         $this->redirect()->getController()->setEvent($event);
         $response = $this->redirect()->toUrl($url);
         return $response;
     }
 }
Exemplo n.º 9
0
 /**
  * @private
  * @param  MvcEvent $event
  * @return void
  */
 public function onError(MvcEvent $event)
 {
     // Do nothing if no error or if response is not HTTP response
     if (!$event->getParam('exception') instanceof UnauthorizedExceptionInterface || $event->getResult() instanceof HttpResponse || !$event->getResponse() instanceof HttpResponse) {
         return;
     }
     $router = $event->getRouter();
     if ($this->authenticationService->hasIdentity()) {
         if (!$this->options->getRedirectWhenConnected()) {
             return;
         }
         $redirectRoute = $this->options->getRedirectToRouteConnected();
     } else {
         $redirectRoute = $this->options->getRedirectToRouteDisconnected();
     }
     $uri = $router->assemble([], ['name' => $redirectRoute]);
     if ($this->options->getAppendPreviousUri()) {
         $redirectKey = $this->options->getPreviousUriQueryKey();
         $previousUri = $event->getRequest()->getUriString();
         $uri = $router->assemble([], ['name' => $redirectRoute, 'query' => [$redirectKey => $previousUri]]);
     }
     $response = $event->getResponse() ?: new HttpResponse();
     $response->getHeaders()->addHeaderLine('Location', $uri);
     $response->setStatusCode(302);
     $event->setResponse($response);
     $event->setResult($response);
 }
 public function testOnRenderErrorCreatesAnApiProblemResponse()
 {
     $response = new Response();
     $request = new Request();
     $request->getHeaders()->addHeaderLine('Accept', 'application/json');
     $event = new MvcEvent();
     $event->setError(Application::ERROR_EXCEPTION);
     $event->setRequest($request);
     $event->setResponse($response);
     $this->listener->onRenderError($event);
     $this->assertTrue($event->propagationIsStopped());
     $this->assertSame($response, $event->getResponse());
     $this->assertEquals(406, $response->getStatusCode());
     $headers = $response->getHeaders();
     $this->assertTrue($headers->has('Content-Type'));
     $this->assertEquals('application/problem+json', $headers->get('content-type')->getFieldValue());
     $content = json_decode($response->getContent(), true);
     $this->assertArrayHasKey('status', $content);
     $this->assertArrayHasKey('title', $content);
     $this->assertArrayHasKey('describedBy', $content);
     $this->assertArrayHasKey('detail', $content);
     $this->assertEquals(406, $content['status']);
     $this->assertEquals('Not Acceptable', $content['title']);
     $this->assertContains('www.w3.org', $content['describedBy']);
     $this->assertContains('accept', $content['detail']);
 }
Exemplo n.º 11
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);
 }
Exemplo n.º 12
0
 /**
  * @param MvcEvent $event
  *
  * @return parent::onDispatch
  */
 public function onDispatch(MvcEvent $event)
 {
     $request = $event->getRequest();
     $remoteAddr = $request->getServer('REMOTE_ADDR');
     // check IP address is allowed
     $application = $event->getApplication();
     $config = $application->getConfig();
     $autoDeployConfig = $config['auto_deploy'];
     $allowedIpAddresses = $autoDeployConfig['ipAddresses'];
     // error if ip is not allowed
     if (!in_array($remoteAddr, $allowedIpAddresses, true)) {
         $baseModel = new \Zend\View\Model\ViewModel();
         $baseModel->setTemplate('layout/output');
         $model = new \Zend\View\Model\ViewModel();
         $model->setTemplate('error/403');
         $baseModel->addChild($model);
         $baseModel->setTerminal(true);
         $event->setViewModel($baseModel);
         $response = $event->getResponse();
         $response->setStatusCode(403);
         $response->sendHeaders();
         $event->setResponse($response);
         exit;
     }
     return parent::onDispatch($event);
 }
Exemplo n.º 13
0
 /**
  * @param MvcEvent $e
  */
 protected function handleError(MvcEvent $e)
 {
     $router = $e->getRouter();
     if ($this->authenticationService->hasIdentity()) {
         if (!$this->options->getRedirectWhenConnected()) {
             return;
         }
         $redirectRoute = $this->options->getRedirectToRouteConnected();
     } else {
         $redirectRoute = $this->options->getRedirectToRouteDisconnected();
     }
     $params = array();
     $options = array('name' => $redirectRoute);
     if ($this->options->getAppendPreviousUri()) {
         $redirectKey = $this->options->getPreviousUriRouteKey();
         $previousUri = $e->getRequest()->getUriString();
         $params = array($redirectKey => $previousUri);
     }
     $uri = $router->assemble($params, $options);
     $response = $e->getResponse() ?: new HttpResponse();
     $response->getHeaders()->addHeaderLine('Location', $uri);
     $response->setStatusCode(302);
     $e->setResponse($response);
     $e->setResult($response);
 }
 public function testInjectTagsHeader()
 {
     $tag = InjectTagsHeaderListener::OPTION_CACHE_TAGS;
     $event = new MvcEvent();
     $response = new Response();
     $event->setResponse($response);
     $layout = new ViewModel();
     $child1 = new ViewModel();
     $child1->setOption($tag, ['tag1', 'tag2']);
     $layout->addChild($child1);
     $child2 = new ViewModel();
     $child21 = new ViewModel();
     $child21->setOption($tag, ['tag3', null]);
     $child2->addChild($child21);
     $layout->addChild($child2);
     $child3 = new ViewModel();
     $child3->setOption('esi', ['ttl' => 120]);
     $child3->setOption($tag, 'tag4');
     $layout->addChild($child3);
     $event->setViewModel($layout);
     $this->listener->injectTagsHeader($event);
     $this->assertSame(['tag1', 'tag2', 'tag3'], $this->listener->getCacheTags());
     $headers = $response->getHeaders();
     $this->assertEquals('tag1,tag2,tag3', $headers->get(VarnishService::VARNISH_HEADER_TAGS)->getFieldValue());
 }
Exemplo n.º 15
0
    public function setUp()
    {
        StaticEventManager::resetInstance();

        $mockSharedEventManager = $this->getMock('Zend\EventManager\SharedEventManagerInterface');
        $mockSharedEventManager->expects($this->any())->method('getListeners')->will($this->returnValue(array()));
        $mockEventManager = $this->getMock('Zend\EventManager\EventManagerInterface');
        $mockEventManager->expects($this->any())->method('getSharedManager')->will($this->returnValue($mockSharedEventManager));
        $mockApplication = $this->getMock('Zend\Mvc\ApplicationInterface');
        $mockApplication->expects($this->any())->method('getEventManager')->will($this->returnValue($mockEventManager));

        $event   = new MvcEvent();
        $event->setApplication($mockApplication);
        $event->setRequest(new Request());
        $event->setResponse(new Response());

        $routeMatch = new RouteMatch(array('action' => 'test'));
        $routeMatch->setMatchedRouteName('some-route');
        $event->setRouteMatch($routeMatch);

        $locator = new Locator;
        $locator->add('forward', function () {
            return new ForwardController();
        });

        $this->controller = new SampleController();
        $this->controller->setEvent($event);
        $this->controller->setServiceLocator($locator);

        $this->plugin = $this->controller->plugin('forward');
    }
Exemplo n.º 16
0
 public function setUp()
 {
     $response = new Response();
     $response->setHeaders(new Headers());
     $mvcEvent = new MvcEvent();
     $mvcEvent->setResponse($response);
     $this->error = new ApiError($mvcEvent);
 }
 public function setUp()
 {
     $response = new HttpResponse();
     $mvcEvent = new MvcEvent();
     $mvcEvent->setResponse($response);
     $this->mvcAuthEvent = $this->createMvcAuthEvent($mvcEvent);
     $this->listener = new DefaultAuthenticationPostListener();
 }
Exemplo n.º 18
0
 public function testFillEventWithoutException()
 {
     $event = new MvcEvent();
     $response = new HttpResponse();
     $event->setResponse($response);
     $listener = new ErrorListener();
     $listener->onError($event);
     $this->assertEquals(HttpResponse::STATUS_CODE_200, $response->getStatusCode());
 }
Exemplo n.º 19
0
 public function onException(MvcEvent $event)
 {
     $response = $event->getParam('response');
     if (!$response instanceof ApiProblemResponse) {
         return;
     }
     $response = new ApiProblemResponse(new ApiProblem(500, 'An unexpected exception occurred.'));
     $event->setResponse($response);
 }
 public function testOnError_WithApiException()
 {
     $event = new MvcEvent();
     $event->setError("The resource doesn't support the specified HTTP verb.");
     $event->setParam('exception', new MethodNotAllowedException());
     $event->setResponse(new Response());
     $result = $this->testedObject->onError($event);
     $this->assertInstanceOf(JsonModel::class, $result);
 }
Exemplo n.º 21
-1
 public function onDispatchError(MvcEvent $e)
 {
     $result = $e->getResult();
     $response = $e->getResponse();
     if ($result instanceof Response || $response && !$response instanceof HttpResponse) {
         return;
     }
     $viewVariables = array('error' => $e->getParam('error'), 'identity' => $e->getParam('identity'));
     switch ($e->getError()) {
         case Controller::ERROR:
             $viewVariables['controller'] = $e->getParam('controller');
             $viewVariables['action'] = $e->getParam('action');
             $router = $e->getRouter();
             if ($e->getParam('exception') instanceof UnAuthorizedException && !$e->getApplication()->getServiceManager()->get('Zend\\Authentication\\AuthenticationService')->hasIdentity()) {
                 $session = new Container('location');
                 $session->location = $e->getRequest()->getUri();
                 // get url to the login route
                 $options['name'] = 'login';
                 $url = $router->assemble(array(), $options);
                 if (!$response) {
                     $response = new HttpResponse();
                     $e->setResponse($response);
                 }
                 if ($e->getRequest()->isXmlHttpRequest()) {
                     $response->setStatusCode(204);
                     $response->getHeaders()->addHeaderLine('Fury-Redirect', $url);
                 } else {
                     $response->setStatusCode(302);
                     $response->getHeaders()->addHeaderLine('Location', $url);
                 }
                 return;
             }
             break;
         case Route::ERROR:
             $viewVariables['route'] = $e->getParam('route');
             break;
         case Application::ERROR_EXCEPTION:
             if (!$e->getParam('exception') instanceof UnAuthorizedException) {
                 return;
             }
             $viewVariables['reason'] = $e->getParam('exception')->getMessage();
             $viewVariables['error'] = 'error-unauthorized';
             break;
         default:
             /*
              * do nothing if there is no error in the event or the error
              * does not match one of our predefined errors (we don't want
              * our 403 template to handle other types of errors)
              */
             return;
     }
     $model = new ViewModel($viewVariables);
     $response = $response ?: new HttpResponse();
     $model->setTemplate($this->getTemplate());
     $e->getViewModel()->addChild($model);
     $response->setStatusCode(403);
     $e->setResponse($response);
 }
Exemplo n.º 22
-1
 /**
  * Listen for specific thrown exceptions and display the proper error page
  * and code for each.
  *
  * @param MvcEvent $e
  */
 public function handleException(MvcEvent $e)
 {
     $result = $e->getResult();
     // Don't interfere with a complete response.
     if ($result instanceof ResponseInterface) {
         return;
     }
     // Only handle exceptions.
     if ($e->getError() !== ZendApplication::ERROR_EXCEPTION) {
         return;
     }
     $exception = $e->getParam('exception');
     $this->getServiceLocator()->get('Omeka\\Logger')->err((string) $exception);
     if ($exception instanceof AclException\PermissionDeniedException) {
         $template = 'error/403';
         $status = 403;
     } else {
         if ($exception instanceof ApiException\NotFoundException || $exception instanceof MvcException\NotFoundException) {
             $template = 'error/404';
             $status = 404;
         } else {
             return;
         }
     }
     $model = new ViewModel(['exception' => $exception]);
     $model->setTemplate($template);
     $response = $e->getResponse();
     if (!$response) {
         $response = new Response();
     }
     $response->setStatusCode($status);
     $e->setResponse($response);
     $e->getViewModel()->addChild($model);
 }
Exemplo n.º 23
-1
 public function prepareViewModel(MvcEvent $e)
 {
     // Do nothing if the result is a response object
     $result = $e->getResult();
     if ($result instanceof Response) {
         return;
     }
     // Common view variables
     $viewVariables = array('error' => $e->getParam('error'), 'identity' => $e->getParam('identity'));
     $error = $e->getError();
     switch ($error) {
         case 'error-unauthorized-controller':
             $viewVariables['controller'] = $e->getParam('controller');
             $viewVariables['action'] = $e->getParam('action');
             break;
         case 'error-unauthorized-route':
             $viewVariables['route'] = $e->getParam('route');
             break;
         default:
             // Do nothing if no error in the event
             return;
     }
     $model = new ViewModel($viewVariables);
     $model->setTemplate($this->getTemplate());
     $e->getViewModel()->addChild($model);
     $response = $e->getResponse();
     if (!$response) {
         $response = new HttpResponse();
         $e->setResponse($response);
     }
     $response->setStatusCode(403);
 }
Exemplo n.º 24
-1
 /**
  * Handles redirects in case of dispatch errors caused by unauthorized access
  *
  * @param \Zend\Mvc\MvcEvent $event
  */
 public function onDispatchError(MvcEvent $event)
 {
     // Do nothing if the result is a response object
     $result = $event->getResult();
     $routeMatch = $event->getRouteMatch();
     $response = $event->getResponse();
     $router = $event->getRouter();
     $error = $event->getError();
     $url = $this->redirectUri;
     if ($result instanceof Response || !$routeMatch || $response && !$response instanceof Response || !(Route::ERROR === $error || Controller::ERROR === $error || Application::ERROR_EXCEPTION === $error && $event->getParam('exception') instanceof UnAuthorizedException)) {
         return;
     }
     // if application needs install
     if (AppGuard::ERROR === $error && $event->getParam('exception') instanceof NeedsInstallException) {
         die('died here');
         $this->redirectRoute = 'zfmuscle/install';
     }
     if (null === $url) {
         $url = $router->assemble(array(), array('name' => $this->redirectRoute));
     }
     $response = $response ?: new Response();
     $response->getHeaders()->addHeaderLine('Location', $url);
     $response->setStatusCode(302);
     $event->setResponse($response);
 }
Exemplo n.º 25
-1
 /**
  * @param MvcEvent $event
  */
 public function onDispatchError(MvcEvent $event)
 {
     if (Application::ERROR_ROUTER_NO_MATCH != $event->getError()) {
         // ignore other than 'no route' errors
         return;
     }
     // get URI stripped of a base URL
     $request = $event->getRequest();
     $uri = str_replace($request->getBaseUrl(), '', $request->getRequestUri());
     // try get image ID from URI
     $id = $this->manager->matchUri($uri);
     if (!$id) {
         // abort if URI does not match
         return;
     }
     // try get image from repository
     $image = $this->repository->find($id);
     if (!$image) {
         // abort if image does not exist
         return;
     }
     // store image
     $this->manager->store($image);
     // return image in response as a stream
     $headers = new Headers();
     $headers->addHeaders(['Content-Type' => $image->getType(), 'Content-Length' => $image->getLength()]);
     $response = new Stream();
     $response->setStatusCode(Response::STATUS_CODE_200);
     $response->setStream($image->getResource());
     $response->setStreamName($image->getName());
     $response->setHeaders($headers);
     $event->setResponse($response);
 }
Exemplo n.º 26
-1
 /**
  * @see \Zend\Mvc\View\Http\ExceptionStrategy::prepareExceptionViewModel()
  */
 public function prepareExceptionViewModel(MvcEvent $event)
 {
     // do nothing if no error in the event
     $error = $event->getError();
     if (empty($error)) {
         return;
     }
     // do nothing if the result is a response object
     $result = $event->getResult();
     if ($result instanceof Response) {
         return;
     }
     // do nothing if there is no exception or the exception is not an UserDeactivatedException
     $exception = $event->getParam('exception');
     if (!$exception instanceof UserDeactivatedException) {
         return;
     }
     $auth = $event->getApplication()->getServiceManager()->get('AuthenticationService');
     // do nothing if no user is logged in or is active one
     if (!$auth->hasIdentity() || $auth->getUser()->isActive()) {
         return;
     }
     $response = $event->getResponse();
     if (!$response) {
         $response = new Response();
         $event->setResponse($response);
     }
     $response->setStatusCode(Response::STATUS_CODE_403);
     $model = new ViewModel(['message' => 'This user account has been disabled. Please contact the system adminstrator.', 'exception' => $exception, 'display_exceptions' => $this->displayExceptions()]);
     $model->setTemplate($this->getExceptionTemplate());
     $event->setResult($model);
 }
Exemplo n.º 27
-1
 public function onDispatchError(MvcEvent $event)
 {
     $result = $event->getResult();
     $response = $event->getResponse();
     if ($result instanceof Response || $response && !$response instanceof HttpResponse) {
         return;
     }
     $viewVariables = array('error' => $event->getParam('error'), 'identity' => $event->getParam('identity'));
     switch ($event->getError()) {
         case Application::ERROR_EXCEPTION:
             if (!$event->getParam('exception') instanceof NotFoundException) {
                 return;
             }
             $viewVariables['reason'] = $event->getParam('exception')->getMessage();
             $viewVariables['error'] = 'error-unauthorized';
             break;
         default:
             return;
     }
     $model = new ViewModel($viewVariables);
     $response = $response ?: new HttpResponse();
     $model->setTemplate($this->getTemplate());
     $event->getViewModel()->addChild($model);
     $response->setStatusCode(404);
     $event->setResponse($response);
 }
Exemplo n.º 28
-1
 public function renderAssets(MvcEvent $e)
 {
     $sm = $e->getApplication()->getServiceManager();
     /** @var Configuration $config */
     $config = $sm->get('AsseticConfiguration');
     if ($e->getName() === MvcEvent::EVENT_DISPATCH_ERROR) {
         $error = $e->getError();
         if ($error && !in_array($error, $config->getAcceptableErrors())) {
             // break if not an acceptable error
             return;
         }
     }
     $response = $e->getResponse();
     if (!$response) {
         $response = new Response();
         $e->setResponse($response);
     }
     /** @var $asseticService \AsseticBundle\Service */
     $asseticService = $sm->get('AsseticService');
     // setup service if a matched route exist
     $router = $e->getRouteMatch();
     if ($router) {
         $asseticService->setRouteName($router->getMatchedRouteName());
         $asseticService->setControllerName($router->getParam('controller'));
         $asseticService->setActionName($router->getParam('action'));
     }
     // Create all objects
     $asseticService->build();
     // Init assets for modules
     $asseticService->setupRenderer($sm->get('ViewRenderer'));
 }
Exemplo n.º 29
-1
 public function onDispatchError(MvcEvent $e)
 {
     // Do nothing if the result is a response object
     $result = $e->getResult();
     $type = $e->getError();
     if ($result instanceof Response || strpos($type, 'unauthorized') === false) {
         return;
     }
     $router = $e->getRouter();
     $match = $e->getRouteMatch();
     // get url to the zfcuser/login route
     $options['name'] = 'zfcuser/login';
     $url = $router->assemble(array(), $options);
     // Work out where were we trying to get to
     $options['name'] = $match->getMatchedRouteName();
     $redirect = $router->assemble($match->getParams(), $options);
     // set up response to redirect to login page
     $response = $e->getResponse();
     if (!$response) {
         $response = new HttpResponse();
         $e->setResponse($response);
     }
     $response->getHeaders()->addHeaderLine('Location', $url . '?redirect=' . $redirect);
     $response->setStatusCode(302);
 }
Exemplo n.º 30
-1
 /**
  * Create an exception view model, and set the HTTP status code
  *
  * @todo   dispatch.error does not halt dispatch unless a response is
  *         returned. As such, we likely need to trigger rendering as a low
  *         priority dispatch.error event (or goto a render event) to ensure
  *         rendering occurs, and that munging of view models occurs when
  *         expected.
  * @param  MvcEvent $e
  * @return void
  */
 public function prepareExceptionViewModel(MvcEvent $e)
 {
     // Do nothing if no error in the event
     $error = $e->getError();
     if (empty($error)) {
         return;
     }
     // Do nothing if the result is a response object
     $result = $e->getResult();
     if ($result instanceof Response) {
         return;
     }
     // Do nothing if there is no exception or the exception is not
     // an UnauthorizedAccessException
     $exception = $e->getParam('exception');
     if (!$exception instanceof UnauthorizedAccessException) {
         return;
     }
     $response = $e->getResponse();
     if (!$response) {
         $response = new Response();
         $e->setResponse($response);
     }
     /*
      * Return an image, if an image was requested.
      */
     if ($exception instanceof UnauthorizedImageAccessException) {
         $image = __DIR__ . '/../../../../../public/images/unauthorized-access.png';
         $response->setStatusCode(403)->setContent(file_get_contents($image))->getHeaders()->addHeaderLine('Content-Type', 'image/png');
         $e->stopPropagation();
         $response->sendHeaders();
         //echo file_get_contents($image);
         //$response->stopped = true;
         return $response;
     }
     $auth = $e->getApplication()->getServiceManager()->get('AuthenticationService');
     if (!$auth->hasIdentity()) {
         $response->setStatusCode(Response::STATUS_CODE_403);
         $routeMatch = $e->getRouteMatch();
         $routeMatch->setParam('controller', 'Auth\\Controller\\Index');
         $routeMatch->setParam('action', 'index');
         $query = $e->getRequest()->getQuery();
         $ref = $e->getRequest()->getRequestUri();
         $ref = preg_replace('~^' . preg_quote($e->getRouter()->getBaseUrl()) . '~', '', $ref);
         $query->set('ref', $ref);
         $query->set('req', 1);
         $result = $e->getApplication()->getEventManager()->trigger('dispatch', $e);
         $e->stopPropagation();
         return $result;
     }
     $message = $exception->getMessage();
     $model = new ViewModel(array('message' => empty($message) ? 'You are not permitted to access this resource.' : $message, 'exception' => $e->getParam('exception'), 'display_exceptions' => $this->displayExceptions()));
     $model->setTemplate($this->getExceptionTemplate());
     $e->setResult($model);
     // $statusCode = $response->getStatusCode();
     // if ($statusCode === 200) {
     $response->setStatusCode(403);
     // }
 }