getResponse() public method

Get response
public getResponse ( ) : Zend\Stdlib\ResponseInterface
return Zend\Stdlib\ResponseInterface
Esempio n. 1
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);
 }
Esempio n. 2
0
 public function onBootstrap(MvcEvent $e)
 {
     $e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_FINISH, function (MvcEvent $e) {
         $config = $e->getApplication()->getServiceManager()->get('Config');
         $routeMatch = $e->getRouteMatch();
         if (!$routeMatch instanceof RouteMatch) {
             return;
         }
         if (empty($config['page-cache'])) {
             return;
         }
         if (empty($config['page-cache']['page-to-cache'])) {
             return;
         }
         foreach ($config['page-cache']['page-to-cache'] as $match) {
             if (strtolower($match['controller']) == strtolower($routeMatch->getParam('controller')) && strtolower($match['action']) == strtolower($routeMatch->getParam('action'))) {
                 $cache = $e->getApplication()->getServiceManager()->get('PageCache\\Model\\Cache');
                 $response = $e->getResponse();
                 $response->getHeaders()->addHeaderLine('Cache-Created', date("D M j G:i:s T Y"));
                 $cache->addItem($this->getKey(), $e->getResponse()->toString());
                 break;
             }
         }
     });
 }
Esempio n. 3
0
 /**
  * @return mixed
  */
 public function notFoundByRequestedCriteria($criteriaErrors)
 {
     $zendResponse = $this->mvcEvent->getResponse();
     $zendResponse->setStatusCode(404);
     $zendResponse->getHeaders()->addHeaderLine("Content-Type", "application/json");
     $zendResponse->setContent(json_encode($criteriaErrors));
     return $zendResponse;
 }
Esempio n. 4
0
 /**
  * @return mixed
  */
 public function notFoundByRequestedCriteria($criteriaErrors)
 {
     $zendResponse = $this->mvcEvent->getResponse();
     $zendResponse->setStatusCode(404);
     $this->viewModel->setVariable('message', 'The requested resource was not found by requested criteria');
     $this->viewModel->setTemplate('error/404');
     $this->mvcEvent->setResult($this->viewModel);
     return $this->viewModel;
 }
Esempio n. 5
0
 public function onError(MvcEvent $event)
 {
     // Do nothing if no error or if response is not HTTP response
     if (!($exception = $event->getParam('exception') instanceof UnauthorizedExceptionInterface) || !($response = $event->getResponse() instanceof HttpResponse)) {
         return;
     }
     $response = $event->getResponse() ?: new HttpResponse();
     $event->setResponse($response);
     $event->setResult($response);
 }
 public function onBootstrap(MvcEvent $e)
 {
     $app = $e->getApplication();
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     $sm = $app->getServiceManager();
     $list = $this->whitelist;
     $auth = $sm->get('AuthService');
     $e->getViewModel()->setVariable('hasIdentity', $auth->hasIdentity());
     if ($auth->hasIdentity()) {
         $e->getViewModel()->setVariable('currentUserId', $auth->getStorage()->read()->id);
     } else {
         $e->getViewModel()->setVariable('currentUserId', -1);
     }
     $eventManager->attach(MvcEvent::EVENT_ROUTE, function ($e) use($list, $auth) {
         $match = $e->getRouteMatch();
         // No route match, this is a 404
         if (!$match instanceof RouteMatch) {
             return;
         } else {
             // Route is whitelisted
             $name = $match->getMatchedRouteName();
             if (in_array($name, $list)) {
                 if ($auth->hasIdentity() && $name != 'login/process') {
                     $router = $e->getRouter();
                     $url = $router->assemble(array(), array('name' => 'home'));
                     $response = $e->getResponse();
                     $response->getHeaders()->addHeaderLine('Location', $url);
                     $response->setStatusCode(302);
                     return $response;
                 } else {
                     return;
                 }
             } else {
                 // User is authenticated
                 if ($auth->hasIdentity() && $name != 'auth/logout') {
                     // $id = $this->UserAuthentication()->getIdentity()->getId();
                     // var_dump(($auth->getIdentity()));
                     // exit;
                     // var_dump($name);exit;
                     return;
                 } else {
                     // Redirect to the user login page, as an example
                     $router = $e->getRouter();
                     $url = $router->assemble(array(), array('name' => 'login'));
                     $response = $e->getResponse();
                     $response->getHeaders()->addHeaderLine('Location', $url);
                     $response->setStatusCode(302);
                     return $response;
                 }
             }
         }
     }, -100);
 }
Esempio n. 7
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;
 }
Esempio n. 8
0
 /**
  * @param MvcEvent $e
  * @throws \Exception
  * @throws \ServiceLocatorFactory\NullServiceLocatorException
  */
 public function preDispatch(MvcEvent $e)
 {
     $application = $e->getApplication();
     $sm = $application->getServiceManager();
     $router = $sm->get('router');
     $request = $sm->get('request');
     $matchedRoute = $router->match($request);
     $params = $matchedRoute->getParams();
     $controller = $params['controller'];
     if (!isset($controller)) {
         return false;
     }
     $currentControllerNamespace = explode('\\', $controller);
     if ($currentControllerNamespace[0] == 'Admin') {
         $sl = ServiceLocatorFactory::getInstance();
         $session = new SessionContainer();
         $userDetails = $session->offsetGet('userDetails');
         /* Check Admin Area login */
         if (!$sl->get('AuthService')->hasIdentity() or $userDetails->sitename != $this->recoverSitename($sl)) {
             $url = $e->getRouter()->assemble(array('action' => 'index'), array('name' => 'login'));
             $response = $e->getResponse();
             $response->getHeaders()->addHeaderLine('Location', $url);
             $response->setStatusCode(302);
             $response->sendHeaders();
             exit;
         }
         // Check ACL
         $roles = (include __DIR__ . '/config/module.acl.roles.php');
         foreach ($roles as $key => $value) {
             if ($key == $matchedRoute->getMatchedRouteName()) {
                 if (isset($value['resources'])) {
                     $allowed = 0;
                     foreach ($value['resources'] as $resource) {
                         if ($userDetails->acl->hasResource($resource)) {
                             $allowed = 1;
                         }
                     }
                     /* No permissions, redirect... */
                     if ($allowed == 0) {
                         $url = $e->getRouter()->assemble(array('lang' => 'it'), array('name' => 'admin/not-authorized'));
                         $response = $e->getResponse();
                         $response->getHeaders()->addHeaderLine('Location', $url);
                         $response->setStatusCode(401);
                         $response->sendHeaders();
                         exit;
                     }
                 }
             }
         }
     }
 }
Esempio n. 9
0
 public function onError(MvcEvent $event)
 {
     // Do nothing if no error or if response is not HTTP response
     if (!($exception = $event->getParam('exception') instanceof UnauthorizedExceptionInterface) || $event->getResult() instanceof HttpResponse || !($response = $event->getResponse() instanceof HttpResponse)) {
         return;
     }
     $request = $event->getRequest() ?: new HttpRequest();
     $response = $event->getResponse() ?: new HttpResponse();
     // za json requeste vedno odgovorimo z json odgovorom nikoli z redirectom
     $model = new JsonModel(['success' => false, 'errors' => [['message' => 'Unauthorized', 'code' => 'TIP-00403', 'severity' => 'error']]]);
     $response->setStatusCode(403);
     $event->setResponse($response);
     $event->setResult($model);
 }
Esempio n. 10
0
 /**
  * Redirect old assets on sites that we do not control to new AWS urls
  */
 public function routeEvent(MvcEvent $event)
 {
     $host = $event->getRequest()->getUri()->getHost();
     if (!isset($this->domainRedirects[$host])) {
         return null;
     }
     $event->getResponse()->setStatusCode(301);
     /**
      * @var $headers \Zend\Http\Headers
      */
     $headers = $event->getResponse()->getHeaders();
     $headers->addHeaderLine('location', $this->domainRedirects[$host] . $event->getRequest()->getUri()->getPath());
     return $event->getResponse();
 }
 /**
  * Method executed when the render event is triggered
  *
  * @param MvcEvent $e 
  * @return void
  */
 public static function onRender(MvcEvent $e)
 {
     if ($e->getRequest() instanceof \Zend\Console\Request || $e->getResponse()->isOk() || $e->getResponse()->getStatusCode() == Response::STATUS_CODE_401) {
         return;
     }
     $httpCode = $e->getResponse()->getStatusCode();
     $sm = $e->getApplication()->getServiceManager();
     $viewModel = $e->getResult();
     $exception = $viewModel->getVariable('exception');
     $model = new JsonModel(array('errorCode' => !empty($exception) ? $exception->getCode() : $httpCode, 'errorMsg' => !empty($exception) ? $exception->getMessage() : NULL));
     $model->setTerminal(true);
     $e->setResult($model);
     $e->setViewModel($model);
     $e->getResponse()->setStatusCode($httpCode);
 }
Esempio n. 12
0
 public function onBootstrap(MvcEvent $e)
 {
     $this->initSession();
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     $list = array();
     $auth = $e->getApplication()->getServiceManager()->get("Zend\\Authentication\\AuthenticationService");
     $eventManager->attach(MvcEvent::EVENT_ROUTE, function ($e) use($list, $auth) {
         $match = $e->getRouteMatch();
         // No route match, this is a 404
         if (!$match instanceof RouteMatch) {
             return;
         }
         // Route is whitelisted
         $route = $match->getMatchedRouteName();
         $params = $match->getParams();
         $module = explode('/', $route);
         /*
                     if($_SERVER['REMOTE_ADDR'] != '127.0.0.1' && $_SERVER['SERVER_PORT'] != '443') {
                         $url = 'Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                         header(str_replace( 'www.', '' , $url));
                         exit();
                     }*/
         if (@$module[0] == 'login') {
             if ($auth->hasIdentity()) {
                 $router = $e->getRouter();
                 $url = $router->assemble(array(), array('name' => 'messages'));
                 $response = $e->getResponse();
                 $response->getHeaders()->addHeaderLine('Location', $url);
                 $response->setStatusCode(302);
                 return $response;
             } else {
                 return;
             }
         }
         if ($auth->hasIdentity()) {
             return;
         } else {
             $router = $e->getRouter();
             $url = $router->assemble(array(), array('name' => 'login'));
             $response = $e->getResponse();
             $response->getHeaders()->addHeaderLine('Location', $url);
             $response->setStatusCode(302);
             return $response;
         }
     }, -100);
 }
Esempio n. 13
0
 public function onBootstrap(MvcEvent $e)
 {
     $eventManager = $e->getApplication()->getEventManager();
     $eventManager->attach(MvcEvent::EVENT_ROUTE, [$this, 'onViewHelper']);
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\\Mvc\\Controller\\AbstractActionController', 'dispatch', function ($e) {
         $controller = $e->getTarget();
         $routeMatch = $e->getRouteMatch();
         $apartmentId = $routeMatch->getParam('apartment_id', 0);
         // get the apartment ID
         if (method_exists($controller, 'setApartmentID')) {
             $serviceManager = $e->getApplication()->getServiceManager();
             $dbAdapter = $serviceManager->get('Zend\\Db\\Adapter\\Adapter');
             $apartmentExistValidator = new RecordExists(['adapter' => $dbAdapter, 'table' => DbTables::TBL_APARTMENTS, 'field' => 'id']);
             if (!$apartmentExistValidator->isValid($apartmentId) && $apartmentId != 0) {
                 $url = $e->getRouter()->assemble(array('controller' => 'apartment', 'action' => 'search'), ['name' => 'apartments']);
                 $response = $e->getResponse();
                 $response->getHeaders()->addHeaderLine('Location', $url);
                 $response->setStatusCode(302);
                 $response->sendHeaders();
                 return $response;
             }
             $controller->setApartmentID($apartmentId);
         }
     }, 100);
 }
 /**
  * Handle rendering errors
  *
  * Rendering errors are usually due to trying to render a template in
  * the PhpRenderer, when we have no templates.
  *
  * As such, report as an unacceptable response.
  *
  * @param  MvcEvent $e
  */
 public function onRenderError(MvcEvent $e)
 {
     $response = $e->getResponse();
     $status = 406;
     $title = 'Not Acceptable';
     $describedBy = 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html';
     $detail = 'Your request could not be resolved to an acceptable representation.';
     $details = false;
     $exception = $e->getParam('exception');
     if ($exception instanceof \Exception && !$exception instanceof ViewExceptionInterface) {
         $code = $exception->getCode();
         if ($code >= 100 && $code <= 600) {
             $status = $code;
         } else {
             $status = 500;
         }
         $title = 'Unexpected error';
         $detail = $exception->getMessage();
         $details = ['code' => $exception->getCode(), 'message' => $exception->getMessage(), 'trace' => $exception->getTraceAsString()];
     }
     $payload = ['status' => $status, 'title' => $title, 'describedBy' => $describedBy, 'detail' => $detail];
     if ($details && $this->displayExceptions) {
         $payload['details'] = $details;
     }
     $response->getHeaders()->addHeaderLine('content-type', 'application/problem+json');
     $response->setStatusCode($status);
     $response->setContent(json_encode($payload));
     $e->stopPropagation();
 }
 /**
  * Render the view
  *
  * @param  MvcEvent $e
  * @return Response
  */
 public function render(MvcEvent $e)
 {
     $result = $e->getResult();
     if ($result instanceof Response) {
         return $result;
     }
     // Martial arguments
     $request = $e->getRequest();
     $response = $e->getResponse();
     $viewModel = $e->getViewModel();
     if (!$viewModel instanceof ViewModel) {
         return;
     }
     $view = $this->view;
     $view->setRequest($request);
     $view->setResponse($response);
     try {
         $view->render($viewModel);
     } catch (\Exception $ex) {
         if ($e->getName() === MvcEvent::EVENT_RENDER_ERROR) {
             throw $ex;
         }
         $application = $e->getApplication();
         $events = $application->getEventManager();
         $e->setError(Application::ERROR_EXCEPTION)->setParam('exception', $ex);
         $events->trigger(MvcEvent::EVENT_RENDER_ERROR, $e);
     }
     return $response;
 }
Esempio n. 16
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);
     }
 }
Esempio n. 17
0
 public function onDispatch(MvcEvent $pEvent)
 {
     $request = $pEvent->getRequest();
     // Make sure that we are not running in a console
     if ($request instanceof Request) {
         /* @var \Zend\Mvc\Router\Http\RouteMatch $match */
         $match = $pEvent->getRouteMatch();
         /**
          * This code basically just makes sure that when we dispatch
          * a route the user is forced to SSL if the route is configured
          * to enable the feature
          */
         if (true === $match->getParam('force_https_scheme', false)) {
             $uri = $request->getUri();
             if ($uri->getScheme() !== "https") {
                 $uri->setScheme('https');
                 /* @var \Zend\Http\PhpEnvironment\Response $response */
                 $response = $pEvent->getResponse();
                 $response->setStatusCode(302);
                 $response->getHeaders()->addHeaderLine('Location', $uri);
                 $response->sendHeaders();
                 return $response;
             }
         }
     }
     return NULL;
 }
Esempio n. 18
0
 function boforeDispatch(MvcEvent $event)
 {
     include 'config/constant.php';
     $response = $event->getResponse();
     $controller = $event->getRouteMatch()->getParam('controller');
     $module_array = explode("\\", $controller);
     if ($module_array[0] == 'Admin') {
         $action = $event->getRouteMatch()->getParam('action');
         $requestedResourse = $controller . "\\" . $action;
         $session = new Container('User');
         if ($session->offsetExists('user')) {
             if (in_array($requestedResourse, $GLOBALS['PAGE_BEFORE_LOGIN'])) {
                 $url = $GLOBALS['SITE_ADMIN_URL'] . 'dashboard/add';
                 $response->setHeaders($response->getHeaders()->addHeaderLine('Location', $url));
                 $response->setStatusCode(302);
             }
         } else {
             if ($requestedResourse != 'Admin\\Controller\\Index\\index' && !in_array($requestedResourse, $GLOBALS['PAGE_BEFORE_LOGIN'])) {
                 $url = $GLOBALS['SITE_ADMIN_URL'] . 'index/login';
                 $response->setHeaders($response->getHeaders()->addHeaderLine('Location', $url));
                 $response->setStatusCode(302);
             }
             $response->sendHeaders();
         }
     }
 }
Esempio n. 19
0
 /**
  * @param MvcEvent $event
  */
 public function renderRequest(MvcEvent $event)
 {
     /** @var Response $zendResponse */
     $zendResponse = $event->getResponse();
     $zendResponse->send();
     $event->stopPropagation();
 }
 /**
  * @covers ::onDispatchError
  */
 public function testOnDispatchErrorStoreAndStreamImage()
 {
     $id = 'someId';
     $resource = 'someResource';
     $this->event->setError(Application::ERROR_ROUTER_NO_MATCH);
     $image = $this->getMockBuilder(ImageEntity::class)->setMethods(['getLength', 'getResource'])->getMock();
     $image->setId($id);
     $image->setType('image/jpeg');
     $image->setName('image.jpg');
     $image->method('getLength')->willReturn(1024);
     $image->method('getResource')->willReturn($resource);
     $this->manager->expects($this->once())->method('matchUri')->willReturn($id);
     $this->repository->expects($this->once())->method('find')->with($this->equalTo($id))->willReturn($image);
     $this->manager->expects($this->once())->method('store')->with($this->identicalTo($image));
     $this->listener->onDispatchError($this->event);
     $response = $this->event->getResponse();
     $this->assertInstanceOf(Stream::class, $response);
     $this->assertEquals(Response::STATUS_CODE_200, $response->getStatusCode());
     $this->assertEquals($image->getName(), $response->getStreamName());
     $this->assertEquals($image->getResource(), $response->getStream());
     $headers = $response->getHeaders();
     $this->assertInstanceOf(Headers::class, $headers);
     $this->assertTrue($headers->has('Content-Type'));
     $this->assertEquals($image->getType(), $headers->get('Content-Type')->getFieldValue());
     $this->assertTrue($headers->has('Content-Length'));
     $this->assertEquals($image->getLength(), $headers->get('Content-Length')->getFieldValue());
 }
Esempio n. 21
0
 public function afterDispatch(MvcEvent $e)
 {
     $controllerName = $e->getRouteMatch()->getMatchedRouteName();
     if ($controllerName != 'login' && ($controllerName != 'application' && $controllerName != 'home')) {
         $containerSession = new \Zend\Session\Container('cbol');
         $e->getTarget()->layout()->repo = $containerSession->reportesVias;
         $e->getTarget()->layout()->acceso = $containerSession->permisosUser;
         $e->getTarget()->layout()->suge = $containerSession->sugerencias;
         $auth = new \Zend\Authentication\AuthenticationService();
         $response = $e->getResponse();
         if (!$auth->hasIdentity()) {
             $url = $e->getRequest()->getBaseUrl() . '/login';
             $response->getHeaders()->addHeaderLine('Location', $url);
             $response->setStatusCode(302);
             $response->sendHeaders();
             return $response;
         } else {
             $localAcl = new \Login\Model\permisos();
             if (!$localAcl->isAllowed($auth->getIdentity()->perfil_id, $controllerName)) {
                 $this->onDispatchError($e, $controllerName);
             } elseif (is_null($containerSession->idSession)) {
                 $url = $e->getRequest()->getBaseUrl() . '/login/logout';
                 $response->getHeaders()->addHeaderLine('Location', $url);
                 $response->setStatusCode(302);
                 $response->sendHeaders();
                 return $response;
             } elseif ($e->getResponse()->getStatusCode() == 403) {
                 $this->onDispatchError($e, $controllerName);
             }
         }
     }
 }
Esempio n. 22
0
 /**
  * @param MvcEvent $e
  * @return void
  */
 public function onError(MvcEvent $e)
 {
     if (!$e->getParam('exception') instanceof UnauthorizedException || $e->getResult() instanceof HttpResponse || !$e->getResponse() instanceof HttpResponse) {
         return;
     }
     $this->handleError($e);
 }
 public function checkAuthentication(MvcEvent $event)
 {
     if ($event->getRequest() instanceof ConsoleResquest) {
         return;
     }
     $routename = $event->getRouteMatch()->getMatchedRouteName();
     // TODO mettre en conf
     if ($routename == 'zfcuser/login' || $routename == 'zfcuser/logout' || $routename == 'execution') {
         return;
     }
     $zfcUser = $this->getServiceLocator()->get('zfcuser_auth_service');
     $config = $this->getServiceLocator()->get('Config');
     $authorized = false;
     if ($zfcUser->hasIdentity()) {
         $authorized = $this->getFileAuthService()->checkAutorisation($zfcUser->getIdentity()->getUserName(), $routename);
     }
     if (!$zfcUser->hasIdentity() || true !== $authorized) {
         $url = $event->getRouter()->assemble(array(), array('name' => 'zfcuser/login'));
         $response = $event->getResponse();
         $response->getHeaders()->addHeaderLine('Location', $url);
         $response->setStatusCode(302);
         $response->sendHeaders();
         $stopCallBack = function ($event) use($response) {
             $event->stopPropagation();
             return $response;
         };
         $event->getApplication()->getEventManager()->attach(MvcEvent::EVENT_ROUTE, $stopCallBack, -10000);
         return $response;
     }
 }
Esempio n. 24
0
 public function onBootstrap(MvcEvent $e)
 {
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\\Mvc\\Controller\\AbstractActionController', 'dispatch', function ($e) {
         $controller = $e->getTarget();
         $routeMatch = $e->getRouteMatch();
         $parkingLotId = $routeMatch->getParam('parking_lot_id', 0);
         // get the parking lot id
         if (method_exists($controller, 'setParkingLotId')) {
             $serviceManager = $e->getApplication()->getServiceManager();
             $dbAdapter = $serviceManager->get('Zend\\Db\\Adapter\\Adapter');
             $parkingLotExistsValidator = new RecordExists(['adapter' => $dbAdapter, 'table' => DbTables::TBL_PARKING_LOTS, 'field' => 'id']);
             if (!$parkingLotExistsValidator->isValid($parkingLotId) && $parkingLotId != 0) {
                 $url = $e->getRouter()->assemble(['controller' => 'parking', 'action' => 'index'], ['name' => 'parking']);
                 $response = $e->getResponse();
                 $response->getHeaders()->addHeaderLine('Location', $url);
                 $response->setStatusCode(302);
                 $response->sendHeaders();
                 return $response;
             }
             $controller->setParkingLotId($parkingLotId);
         }
     }, 100);
 }
 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;
     }
     switch ($error) {
         case Application::ERROR_CONTROLLER_NOT_FOUND:
         case Application::ERROR_CONTROLLER_INVALID:
         case Application::ERROR_ROUTER_NO_MATCH:
             // Specifically not handling these
             return;
         case Application::ERROR_EXCEPTION:
         default:
             $exception = $event->getParam('exception');
             if ($exception) {
                 $response = $event->getResponse();
                 if (!$response || $response->getStatusCode() === 200) {
                     header('HTTP/1.0 500 Internal Server Error', true, 500);
                 }
                 ob_clean();
                 $this->run->handleException($event->getParam('exception'));
             }
             break;
     }
 }
 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);
 }
 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);
 }
Esempio n. 28
-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);
 }
 /**
  * @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);
 }
Esempio n. 30
-1
    /**
     * @param MvcEvent $e
     * @return void|ViewModel
     */
    public function handleDispatchErrors(MvcEvent $e)
    {
        $exception = $e->getParam('exception');
        $routeMatch = $e->getRouteMatch();
        if (!$routeMatch || $exception instanceof UnauthorizedException) {
            // We don't handle permissions errors or unmatched routes
            return;
        }

        // We will do the final handling here
        $e->stopPropagation();

        if (Console::isConsole()) {
            return;
        }
        $error = $e->getError();
        $model = new ViewModel(
            [
                'message' => 'An error occurred. Good luck!<br/><br/><pre>' . $exception->getMessage() . '</pre>',
                'reason' => $error,
                'exception' => $exception,
            ]
        );
        $model->setTemplate('error/404');
        $e->getViewModel()->addChild($model);

        $response = $e->getResponse();
        $response->setStatusCode(404);

        return $model;
    }