/**
  * Sets some Meta-Data into the view.
  * 
  * @param MvcEvent $event
  */
 public function injectIntoView(MvcEvent $event)
 {
     $serviceLocator = $event->getApplication()->getServiceManager();
     $nodeOptions = $serviceLocator->get('NodeOptions');
     /* @var $nodeOptions \Node\Options\NodeOptions */
     $viewHelperManager = $serviceLocator->get('viewhelpermanager');
     $serverurl = $viewHelperManager->get('serverurl');
     if (null != $event->getParam('matchedNode')) {
         $node = $event->getParam('matchedNode');
         /* @var $node \Node\Entity\NodeInterface */
         // HeadTitle
         $headtitle = $viewHelperManager->get('headtitle');
         $headtitle->set($node->getNodeName());
         // Canonical
         $headlink = $viewHelperManager->get('headlink');
         $headlink(['rel' => 'canonical', 'href' => $serverurl() . $node->getNodeRoute()]);
         // Meta?
         if (true == $nodeOptions->getEnableMetaTags()) {
             $headmeta = $viewHelperManager->get('headmeta');
             if (null != $node->getNodeMetaRobots()) {
                 $headmeta->appendName('robots', $node->getNodeMetaRobots());
             }
             if (null != $node->getNodeMetaDescription()) {
                 $headmeta->appendName('description', $node->getNodeMetaDescription());
             }
             if (null != $node->getNodeMetaKeywords()) {
                 $headmeta->appendName('keywords', $node->getNodeMetaKeywords());
             }
         }
     }
 }
 public function testNoRolesAllowed()
 {
     $this->routeMatch->setParam('action', 'noRoles');
     $listener = new Authorized();
     $listener->onDispach($this->event);
     $this->assertNull($this->event->getParam('exception'));
 }
Beispiel #3
0
 public function onBootstrap(MvcEvent $e)
 {
     $e->getApplication()->getServiceManager()->get('translator');
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     // Add translation
     $translator = $e->getApplication()->getServiceManager()->get('translator');
     if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
         $setLang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
     } else {
         $setLang = '';
     }
     $translator->setLocale(\Locale::acceptFromHttp($setLang))->setFallbackLocale('en_US');
     // Add ACL information to the Navigation view helper
     $sm = $e->getApplication()->getServiceManager();
     $authorize = $sm->get('BjyAuthorize\\Service\\Authorize');
     $acl = $authorize->getAcl();
     $role = $authorize->getIdentity();
     \Zend\View\Helper\Navigation::setDefaultAcl($acl);
     \Zend\View\Helper\Navigation::setDefaultRole($role);
     $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\\Mvc\\Application', 'dispatch.error', function ($e) use($sm) {
         if ($e->getParam('exception')) {
             $sm->get('Zend\\Log\\Logger')->crit($e->getParam('exception'));
         }
     });
 }
 public function dispatchError(MvcEvent $e)
 {
     $sharedManager = $e->getApplication()->getEventManager()->getSharedManager();
     $sharedManager->attach('Zend\\Mvc\\Application', 'dispatch.error', function ($e) {
         if ($e->getParam('exception')) {
             ob_clean();
             //Limpar a tela de erros do php
             header('HTTP/1.1 400 Bad Request');
             $exception = $e->getParam('exception');
             $sm = $e->getApplication()->getServiceManager();
             $config = $sm->get('Config');
             $e->getApplication()->getServiceManager()->get('Controller\\Plugin\\Manager')->get('jsLog')->log($exception, 2);
             $viewModel = new \Zend\View\Model\ViewModel(['exception' => $exception]);
             if ($e->getRequest()->isXmlHttpRequest()) {
                 $viewModel->setTemplate($config['js_library']['error_ajax_exception']);
                 $e->getApplication()->getServiceManager()->get('ViewRenderer')->render($viewModel);
             } else {
                 $viewModel->setTemplate($config['js_library']['error_exception']);
                 echo $e->getApplication()->getServiceManager()->get('ViewRenderer')->render($viewModel);
             }
             /*
              * Com erros handler o codigo continua a ser executado,
              * entao o exit para e so mostra os erros
              */
             exit;
         }
     });
 }
 public function onBootstrap(MvcEvent $e)
 {
     $events = $e->getApplication()->getEventManager()->getSharedManager();
     $config = $e->getApplication()->getServiceManager()->get('config');
     // configure session
     $sessionConfig = new SessionConfig();
     $sessionConfig->setOptions($config['session']);
     $events->attach('ZfcUser\\Service\\User', 'register.post', function ($e) {
         $user = $e->getParam('user');
         // User account object
         $form = $e->getParam('form');
         // Form object
         // Perform your custom action here
         /* @var $sm ServiceLocatorInterface */
         $sm = $e->getTarget()->getServiceManager();
         /* @var $em \Doctrine\ORM\EntityManager */
         $em = $sm->get('doctrine.entitymanager.orm_default');
         $userRole = $em->find(__NAMESPACE__ . '\\Entity\\UserRole', DEFAULT_ROLE);
         if (NULL !== $userRole) {
             $user->addRole($userRole);
             $em->persist($user);
             $em->flush();
         }
     });
 }
Beispiel #6
0
 /**
  * Listener callback
  */
 public function onError()
 {
     $this->verifyIsError();
     /** @var \Exception $exception */
     $exception = $this->mvcEvent->getParam('exception');
     $logger = $this->getLogger();
     $logger->err($exception);
 }
 public function onBootstrap(MvcEvent $e)
 {
     $doctrineAdapter = $serviceManager = $e->getParam('application')->getServiceManager()->get('oauth2.doctrineadapter.default');
     $listenerAggregate = new \ZFTest\OAuth2\Doctrine\Listener\TestEvents($doctrineAdapter);
     /** @var ServiceManager $serviceManager */
     $serviceManager = $e->getParam('application')->getServiceManager();
     /** @var EventManager $eventManager */
     $eventManager = $serviceManager->get('oauth2.doctrineadapter.default')->getEventManager();
     $listenerAggregate->attach($eventManager);
 }
 protected function loadDocument(MvcEvent $event, $documentManager, $metadata, $field)
 {
     if (!($document = $event->getParam('document'))) {
         // document not set, so load it
         $document = $documentManager->createQueryBuilder()->find($metadata->name)->field($event->getTarget()->getOptions()->getProperty())->equals($event->getParam('id'))->select($field)->getQuery()->getSingleResult();
         if (!$document) {
             throw new Exception\DocumentNotFoundException();
         }
     }
     return $document;
 }
Beispiel #9
0
 /**
  *
  */
 public function handleError(MvcEvent $event)
 {
     $controller = $event->getController();
     $error = $event->getParam('error');
     $exception = $event->getParam('exception');
     $message = sprintf('Error dispatching controller "%s". Error was: "%s"', $controller, $error);
     if ($exception instanceof \Exception) {
         $message .= ', Exception(' . $exception->getMessage() . '): ' . $exception->getTraceAsString();
     }
     error_log($message);
 }
Beispiel #10
0
 /**
  * Bootstrap.
  *
  * @var MvcEvent $e
  */
 public function onBootstrap(MvcEvent $e)
 {
     $em = $e->getApplication()->getEventManager();
     // this event listener will turn the request into '403 Forbidden' when
     // there is a NotAllowedException
     $em->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) {
         if ($e->getError() == 'error-exception' && $e->getParam('exception', null) != null && $e->getParam('exception') instanceof NotAllowedException) {
             $e->getResult()->setTemplate('error/403');
             $e->getResponse()->setStatusCode(403);
         }
     }, -100);
 }
Beispiel #11
0
 public function latch(MvcEvent $e)
 {
     $eventManager = $e->getApplication()->getEventManager();
     $em = $eventManager->getSharedManager();
     $zfcServiceEvents = $e->getApplication()->getServiceManager()->get('zfcuser_user_service')->getEventManager();
     $zfcServiceEvents->attach('register', function ($e) {
         $form = $e->getParam('form');
         /* @var $user \FzyAuth\Entity\Base\UserInterface */
         $user = $e->getParam('user');
         $user->setRole(UserInterface::ROLE_USER);
     });
 }
Beispiel #12
0
 private function _addRegistrationFields(MvcEvent $e)
 {
     $zfcServiceEvents = $e->getApplication()->getServiceManager()->get('zfcuser_user_service')->getEventManager();
     // Store the field
     $zfcServiceEvents->attach('register', function ($e) {
         $form = $e->getParam('form');
         $user = $e->getParam('user');
         /* @var $user \FooUser\Entity\User */
         $displayName = $form->get('firstName')->getValue() . ' ' . $form->get('lastName')->getValue();
         $user->setDisplayName($displayName);
     });
 }
Beispiel #13
0
 public function onBootstrap(MvcEvent $e)
 {
     $application = $e->getApplication();
     $serviceLocator = $application->getServiceManager();
     $application->getEventManager()->attach(MvcEvent::EVENT_DISPATCH_ERROR, function (Event $e) use($serviceLocator) {
         $exception = $e->getParam('exception');
         $serviceLocator->get('Zend\\Log\\Logger')->crit($exception);
     });
     $application->getEventManager()->attach(MvcEvent::EVENT_RENDER_ERROR, function (Event $e) use($serviceLocator) {
         $exception = $e->getParam('exception');
         $serviceLocator->get('Zend\\Log\\Logger')->crit($exception);
     });
 }
 public function unserializeSingle(MvcEvent $event, $mode)
 {
     if (count($event->getParam('deeperResource')) > 0 || ($result = $event->getResult())) {
         return $event->getResult();
     }
     $data = $event->getParam('data');
     $id = $event->getParam('id');
     $options = $event->getTarget()->getOptions();
     if ($property = $options->getProperty()) {
         $data[$property] = $id;
     }
     $result = new Result($event->getTarget()->getOptions()->getManifest()->getServiceManager()->get('unserializer')->fromArray($data, $event->getTarget()->getOptions()->getClass(), $event->getParam('document'), $mode));
     $event->setResult($result);
     return $result;
 }
Beispiel #15
0
 public function onBootstrap(MvcEvent $e)
 {
     $events = StaticEventManager::getInstance();
     $serviceManager = $e->getApplication()->getServiceManager();
     $appConfig = $serviceManager->get('Config');
     $logger = new Logger();
     if (!isset($appConfig['operation_logger'])) {
         throw new \RuntimeException("Logger not properly configured");
     }
     if (!isset($appConfig['operation_logger']['priority_filter'])) {
         throw new \RuntimeException("You must specify a 'priority_filter' config param");
     }
     $logFilter = new PriorityFilter($appConfig['operation_logger']['priority_filter']);
     if (!is_null($appConfig['operation_logger']['db_adapter'])) {
         if (empty($appConfig['operation_logger']['logger_table'])) {
             throw new \RuntimeException("You must specify a 'logger_table' config param");
         }
         $dbAdapter = $serviceManager->get($appConfig['operation_logger']['db_adapter']);
         if (!$dbAdapter instanceof \Zend\Db\Adapter\Adapter) {
             throw new \RuntimeException("Failed to load database adapter for logger");
         }
         $tableMapping = array('timestamp' => 'event_date', 'priorityName' => 'priority', 'message' => 'event', 'extra' => array('id_operation_log' => 'id_operation_log', 'note' => 'note', 'table' => 'table_name', 'id_user' => 'id_user', 'username' => 'username', 'id_row' => 'id_row', 'field' => 'field', 'value_old' => 'value_old', 'value_new' => 'value_new', 'source' => 'source', 'uri' => 'uri', 'ip' => 'ip', 'session_id' => 'session_id'));
         $logWriter = new DbWriter($dbAdapter, $appConfig['operation_logger']['logger_table'], $tableMapping);
         $logWriter->addFilter($logFilter);
         $logger->addWriter($logWriter);
     }
     // nel caso si volgia fare un file LOG
     if (isset($appConfig['operation_logger']['log_file']) && !is_null($appConfig['operation_logger']['log_file'])) {
         $streamWriter = new StreamWriter($appConfig['operation_logger']['log_file']);
         $streamWriter->addFilter($logFilter);
         $logger->addWriter($streamWriter);
     }
     $request = $e->getApplication()->getRequest();
     $remoteAddress = new RemoteAddress();
     Logger::registerErrorHandler($logger, true);
     Logger::registerExceptionHandler($logger);
     // Attacco evento per trigger LOG! (evento: operation-log)
     $events->attach("*", 'operation-log', function (\Zend\EventManager\Event $e) use($logger, $request, $remoteAddress, $serviceManager) {
         $targetClass = get_class($e->getTarget());
         $message = $e->getParam('message');
         $priority = $e->getParam('priority', Logger::INFO);
         $zfcAuthEvents = $serviceManager->get('zfcuser_auth_service');
         $idUser = $zfcAuthEvents->hasIdentity() ? $zfcAuthEvents->getIdentity()->getId() : (array_key_exists('id_user', $message) ? $message['id_user'] : '******');
         $displayName = $zfcAuthEvents->hasIdentity() ? $zfcAuthEvents->getIdentity()->getDisplayName() : (array_key_exists('username', $message) ? $message['username'] : '******');
         $extras = array('id_operation_log' => null, 'note' => array_key_exists('note', $message) ? $message['note'] : null, 'table_name' => array_key_exists('table', $message) ? $message['table'] : null, 'operation' => array_key_exists('operation', $message) ? $message['operation'] : null, 'id_user' => $idUser, 'username' => $displayName, 'id_row' => array_key_exists('id_row', $message) ? $message['id_row'] : null, 'field' => array_key_exists('field', $message) ? $message['field'] : null, 'value_old' => array_key_exists('value_old', $message) ? $message['value_old'] : null, 'value_new' => array_key_exists('value_new', $message) ? $message['value_new'] : null, 'source' => $targetClass, 'uri' => $request->getUriString(), 'ip' => $remoteAddress->getIpAddress(), 'session_id' => session_id());
         $logger->log($priority, $message['message'], $extras);
     });
 }
Beispiel #16
0
 /**
  * Return all event parameters or a single event parameter.
  * 
  * @param string $param Parameter name to retrieve, or null to get all.
  * @param mixed $efault Default value to use when the parameter is missing.
  * @return mixed
  * @throws RuntimeException
  */
 public function fromEvent($param = null, $default = null)
 {
     if (null === $param) {
         return $this->event->getParams();
     }
     return $this->event->getParam($param, $default);
 }
 public function onDispatch(MvcEvent $e)
 {
     $routeMatch = $e->getRouteMatch();
     $contentNegotiationParams = $e->getParam('ZFContentNegotiationParameterData');
     if ($contentNegotiationParams) {
         $routeParameters = $contentNegotiationParams->getRouteParams();
     } else {
         $routeParameters = $routeMatch->getParams();
     }
     $parameterMatcher = new ParameterMatcher($e);
     // match route params to dispatchable parameters
     if ($this->wrappedCallable instanceof \Closure) {
         $callable = $this->wrappedCallable;
     } elseif (is_array($this->wrappedCallable) && is_callable($this->wrappedCallable)) {
         $callable = $this->wrappedCallable;
     } elseif (is_object($this->wrappedCallable) || is_null($this->wrappedCallable)) {
         $action = $routeMatch->getParam('action', 'not-found');
         $method = static::getMethodFromAction($action);
         $callable = is_null($this->wrappedCallable) && get_class($this) != __CLASS__ ? $this : $this->wrappedCallable;
         if (!method_exists($callable, $method)) {
             $method = 'notFoundAction';
         }
         $callable = [$callable, $method];
     } else {
         throw new \Exception('RPC Controller Not Understood');
     }
     $dispatchParameters = $parameterMatcher->getMatchedParameters($callable, $routeParameters);
     $result = call_user_func_array($callable, $dispatchParameters);
     $e->setParam('ZFContentNegotiationFallback', ['Zend\\View\\Model\\JsonModel' => ['application/json']]);
     $e->setResult($result);
 }
Beispiel #18
0
 /**
  * @param MvcEvent $event
  */
 public function errorEventHandler(MvcEvent $event)
 {
     $exception = $event->getParam('exception');
     if ($exception) {
         $this->logException($exception);
     }
 }
 /**
  * @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);
 }
 /**
  * @param MvcEvent $e
  */
 public function validateIdentity(MvcEvent $e)
 {
     $inputFilter = $e->getParam('ZF\\ContentValidation\\InputFilter');
     if (!$inputFilter instanceof InputFilter) {
         return new ApiProblemModel(new ApiProblem(500, 'Missing InputFilter; cannot validate request'));
     }
     $data = $inputFilter->getValues();
     $criteria = (new UserMongoCollectionCriteria())->setIdentityExistToken($data['token']);
     /** @var $userService  UserModelInterface */
     $userService = $this->model()->get(UserModelService::class);
     $result = $userService->find($criteria);
     if ($result->count() == 1) {
         $user = $result->current();
         if ($user instanceof UserStateAwareInterface && $user instanceof ActiveRecordInterface) {
             $user->validated();
             $user->save();
             if ($this->getResponse() instanceof Response) {
                 $this->getResponse()->setStatusCode(204);
             }
             return new JsonModel();
         }
         return new ApiProblemModel(new ApiProblem(500, 'Invalid object register in user service'));
     }
     return new ApiProblemModel(new ApiProblem(404, 'Token not found'));
 }
 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);
 }
 /**
  * Callback used when a dispatch error occurs. Modifies the
  * response object with an according error if the application
  * event contains an exception related with authorization.
  *
  * @param MvcEvent $event
  *
  * @return void
  */
 public function onDispatchError(MvcEvent $event)
 {
     // Do nothing if the result is a response object
     $result = $event->getResult();
     $response = $event->getResponse();
     if ($result instanceof Response || $response && !$response instanceof HttpResponse) {
         return;
     }
     // Common view variables
     $viewVariables = array('error' => $event->getParam('error'), 'identity' => $event->getParam('identity'));
     switch ($event->getError()) {
         case Application::ERROR_EXCEPTION:
             if (!$event->getParam('exception') instanceof UnAuthorizedException) {
                 return;
             }
             $viewVariables['reason'] = $event->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());
     $event->getViewModel()->addChild($model);
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
 /**
  * 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);
 }
Beispiel #25
-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);
 }
Beispiel #26
-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);
 }
Beispiel #27
-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;
    }
 public function handleError(MvcEvent $event)
 {
     // Do nothing if no error in the event
     $error = $event->getError();
     if (empty($error)) {
         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');
             $logMessages = array();
             do {
                 $priority = Logger::ERR;
                 $extra = array('file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => $exception->getTrace());
                 if (isset($exception->xdebug_message)) {
                     $extra['xdebug'] = $exception->xdebug_message;
                 }
                 $logMessages[] = array('priority' => $priority, 'message' => $exception->getMessage(), 'extra' => $extra);
                 $exception = $exception->getPrevious();
             } while ($exception);
             foreach (array_reverse($logMessages) as $logMessage) {
                 $this->log->log($logMessage['priority'], $logMessage['message'], $logMessage['extra']);
             }
             break;
     }
 }
 /**
  * @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);
 }
Beispiel #30
-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);
 }