public function handleRestApiError(MvcEvent $e) { if (array_key_exists('exception', $e->getParams())) { $exception = $e->getParams()['exception']; if ($exception instanceof RestApiException) { $e->stopPropagation(); $response = $e->getResponse(); $response->setStatusCode('400'); $response->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $adapter = new Json(); $errorData = $exception->getErrorData(); $original = $exception->getOriginal(); $count = 0; while ($original instanceof \Exception) { $errorData['previous-' . $count] = $original->getMessage() . '/' . $original->getFile() . '/' . $original->getLine(); $original = $original->getPrevious(); $count++; } $response->setContent($adapter->serialize($errorData)); $response->sendHeaders(); $response->sendContent(); exit; } } }
/** * 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); }
/** * @param MvcEvent $e * @return null|\Zend\Http\PhpEnvironment\Response */ public function errorProcess(MvcEvent $e) { /** @var \Zend\Di\Di $di */ $di = $e->getApplication()->getServiceManager()->get('di'); $eventParams = $e->getParams(); /** @var array $configuration */ $configuration = $e->getApplication()->getConfig(); $vars = array(); if (isset($eventParams['exception'])) { /** @var \Exception $exception */ $exception = $eventParams['exception']; if ($configuration['errors']['show_exceptions']['message']) { $vars['error-message'] = $exception->getMessage(); } if ($configuration['errors']['show_exceptions']['trace']) { $vars['error-trace'] = $exception->getTrace(); } } if (empty($vars)) { $vars['error'] = 'Something went wrong'; } /** @var PostProcessor\AbstractPostProcessor $postProcessor */ $postProcessor = $di->get($configuration['errors']['post_processor'], array('vars' => $vars, 'response' => $e->getResponse())); $postProcessor->process(); if ($eventParams['error'] === \Zend\Mvc\Application::ERROR_CONTROLLER_NOT_FOUND || $eventParams['error'] === \Zend\Mvc\Application::ERROR_ROUTER_NO_MATCH) { $e->getResponse()->setStatusCode(\Zend\Http\PhpEnvironment\Response::STATUS_CODE_501); } else { $e->getResponse()->setStatusCode(\Zend\Http\PhpEnvironment\Response::STATUS_CODE_500); } $e->stopPropagation(); return $postProcessor->getResponse(); }
public function onBootstrap(MvcEvent $e) { $serviceLocator = $e->getApplication()->getServiceManager(); Orm::setServiceLocator($serviceLocator); $identityMap = $serviceLocator->get('ZealOrm\\Identity\\Map'); $eventManager = $e->getApplication()->getEventManager(); $eventManager->attach(new IdentityMapListener($identityMap)); $events = $eventManager->getSharedManager(); // if an auto incrementing primary key is being used, ensure it is // populated after creation when using the DB adapter $events->attach('mapper', 'create.post', function ($e) { $mapper = $e->getTarget(); $params = $e->getParams(); $object = $params['object']; $adapter = $mapper->getAdapter(); if ($adapter instanceof Db) { $primaryKey = $mapper->getAdapterOption('primaryKey'); if ($primaryKey && $mapper->getAdapterOption('autoIncrement', true)) { $id = $mapper->getAdapter()->getTableGateway()->getAdapter()->getDriver()->getLastGeneratedValue(); if (is_scalar($id)) { $object->{$primaryKey} = $id; } } } }, 999); // save associated data $events->attach('mapper', array('create.post', 'update.post'), function ($e) { $mapper = $e->getTarget(); $params = $e->getParams(); $object = $params['object']; $associationsToSave = $object->getAssociationsWithUnsavedData(); if ($associationsToSave) { foreach ($associationsToSave as $shortname => $association) { $associationMapper = $association->getTargetMapper(); $adapter = $associationMapper->getAdapter(); $association->saveData($object, $adapter); } } }, 900); }
public function onBootstrap(MvcEvent $e) { $serviceLocator = $e->getApplication()->getServiceManager(); $e->getApplication()->getEventManager()->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH, function (MvcEvent $e) use($serviceLocator) { if (!$e->getRequest() instanceof Request) { return; } $request = $e->getRequest(); $config = $serviceLocator->get('Config'); $serviceName = isset($config['hermes']['service_name']) ? $config['hermes']['service_name'] : ''; $data = ['direction' => 'in', 'status' => 'success', 'destination' => ['service' => $serviceName, 'server' => $request->getUri()->getHost(), 'uri' => $request->getUriString()], 'source' => ['server' => $_SERVER['REMOTE_ADDR'], 'service' => $request->getHeader('X-Request-Name') ? $request->getHeader('X-Request-Name')->getFieldValue() : '', 'uri' => '']]; if (!$e->getRequest()->isGet()) { $post = json_decode($e->getRequest()->getContent(), true, 100); unset($post['password']); $data['data'] = $post; } \LosLog\Log\RequestLogger::save($e->getRequest(), $data); }, 100); $hermes = $serviceLocator->get('hermes'); $em = $hermes->getEventManager(); $em->attach('request.post', function (Event $e) use($serviceLocator) { /* @var \Hermes\Api\Client $hermes */ $hermes = $e->getTarget(); $request = $hermes->getZendClient()->getRequest(); $config = $serviceLocator->get('Config'); $serviceName = isset($config['hermes']['service_name']) ? $config['hermes']['service_name'] : ''; $data = ['direction' => 'out', 'status' => 'success', 'source' => ['service' => $serviceName, 'server' => $_SERVER['SERVER_ADDR'], 'uri' => $_SERVER['REQUEST_URI']], 'destination' => ['service' => $hermes->getServiceName(), 'server' => $request->getUri()->getHost(), 'uri' => $request->getUriString()], 'http_code' => $hermes->getZendClient()->getResponse()->getStatusCode()]; if (!$request->isGet()) { $post = json_decode($request->getContent(), true, 100); unset($post['password']); $data['data'] = $post; } \LosLog\Log\RequestLogger::save($request, $data); }, 100); $em->attach('request.fail', function (Event $e) use($serviceLocator) { /* @var \Hermes\Api\Client $hermes */ $hermes = $e->getTarget(); $request = $hermes->getZendClient()->getRequest(); $config = $serviceLocator->get('Config'); $serviceName = isset($config['hermes']['service_name']) ? $config['hermes']['service_name'] : ''; $data = ['direction' => 'out', 'status' => 'failed', 'source' => ['service' => $serviceName, 'server' => $_SERVER['SERVER_ADDR'], 'uri' => $_SERVER['REQUEST_URI']], 'destination' => ['service' => $hermes->getServiceName(), 'server' => $request->getUri()->getHost(), 'uri' => $request->getUriString()]]; if (!$request->isGet()) { $post = json_decode($request->getContent(), true, 100); unset($post['password']); $data['data'] = $post; } $exception = $e->getParams(); $data['http_code'] = $exception->getCode(); $data['error'] = $exception->getMessage(); \LosLog\Log\RequestLogger::save($request, $data); }, 100); }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $serviceManager = $e->getApplication()->getServiceManager(); $sem = $eventManager->getSharedManager(); /* * Add a series of events covering the feed lifecycle (create, modify, delete) */ $sem->attach('BabyMonitor\\Controller\\FeedsController', 'Feed.Create', function ($e) use($serviceManager) { $notifier = $serviceManager->get('BabyMonitor\\Notify\\Feed\\EmailNotifier'); $notifier->notify($e->getParams()['feedData'], EmailNotifier::NOTIFY_CREATE); }); $sem->attach('BabyMonitor\\Controller\\FeedsController', 'Feed.Modify', function ($e) use($serviceManager) { $notifier = $serviceManager->get('BabyMonitor\\Notify\\Feed\\EmailNotifier'); $notifier->notify($e->getParams()['feedData'], EmailNotifier::NOTIFY_UPDATE); }); $sem->attach('BabyMonitor\\Controller\\FeedsController', 'Feed.Delete', function ($e) use($serviceManager) { $notifier = $serviceManager->get('BabyMonitor\\Notify\\Feed\\EmailNotifier'); $notifier->notify($e->getParams()['feedData'], EmailNotifier::NOTIFY_DELETE); }); }
/** * {@inheritDoc} */ public function onError(MvcEvent $event) { $model = new ViewModel($event->getParams()); if (!$event->getParam('identity')) { /* @var $services \Zend\ServiceManager\ServiceLocatorInterface */ $services = $event->getApplication()->getServiceManager(); /* @var $provider IdentityProviderInterface */ $provider = $services->get(IdentityProviderInterface::class); $model->setVariable('identity', $provider->getIdentity()); } $model->setTemplate($this->getTemplate() ?: $this->options->getTemplate()); $response = $event->getResponse() ?: new HttpResponse(); $response->setStatusCode(403); $event->setResponse($response); $event->getViewModel()->addChild($model); }
public function onBootstrap(MvcEvent $e) { $oApplication = $e->getApplication(); $oServiceLocator = $oApplication->getServiceManager(); $oSharedManager = $oApplication->getEventManager()->getSharedManager(); $oEventManager = $oApplication->getEventManager(); $oModuleRouteListener = new ModuleRouteListener(); $oModuleRouteListener->attach($oEventManager); $oRouter = $oServiceLocator->get('router'); $oRequest = $oServiceLocator->get('request'); $oMatchedRoute = $oRouter->match($oRequest); if (null !== $oMatchedRoute) { $oSharedManager->attach('Zend\\Mvc\\Controller\\AbstractActionController', 'dispatch', function ($e) use($oServiceLocator) { if ($oServiceLocator->get('ControllerPluginManager')->has('LogsPlugin')) { //$oServiceLocator->get('ControllerPluginManager')->get('LogsPlugin')->init($e); } }, 2); } $oSharedManager->attach('Zend\\Mvc\\Controller\\AbstractActionController', 'dispatch', function ($e) use($oServiceLocator) { $oController = $e->getTarget(); $sControllerClassName = get_class($oController); $sModuleName = substr($sControllerClassName, 0, strpos($sControllerClassName, '\\')); $aConfig = $oServiceLocator->get('config'); if (isset($aConfig['module_layouts'][$sModuleName])) { //$oController->layout($aConfig['module_layouts'][$sModuleName]); } }, 100); $oSharedManager->attach('User\\Controller\\Plugin\\AuthPlugin', 'auth', function ($e) use($oServiceLocator) { $oParam = $e->getParams(); $oMail = new \Application\Mail($oServiceLocator); $oMail->fillMessage('sendLoginMessage', $oParam); }, -10); $oTranslator = $oServiceLocator->get('translator'); \Zend\Validator\AbstractValidator::setDefaultTranslator($oTranslator); //$oEventManager->attach('dispatch.error', new \Application\Listener\DispatchErrorHandlerListener(), 100); //$oEventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function (MvcEvent $oEvent) { //$oViewModel = $oEvent->getViewModel(); //$oViewModel->setTemplate('layout/layout_404'); //}, -200); }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); // dzieki temu mozemy ustawic trigger na okreslony obiekt klasy $sharedEventManager = $eventManager->getSharedManager(); $sharedEventManager->attach('Import\\Model\\AbstractTable', 'saveHistoryChange', function ($e) { $params = json_encode($e->getParams()); $aNoweDane = is_array($params['new']) ? $params['new'] : array(); $aStareDane = is_array($params['old']) ? $params['old'] : array(); $iId = $params['id']; $auth = Zend_Auth::getInstance()->getStorage()->read(); $iIdUzytkownika = isset($auth['user_id']) ? $auth['user_id'] : 0; $aPomijaneKolumny = array(); foreach ($aNoweDane as $sNazwaKolumny => $sNowaWartosc) { if (!is_integer($sNazwaKolumny)) { if (!in_array($sNazwaKolumny, $aPomijaneKolumny)) { $sStaraWartosc = isset($aStareDane[$sNazwaKolumny]) ? $aStareDane[$sNazwaKolumny] : ''; if ($sNowaWartosc != $sStaraWartosc) { $aData = array(); if (empty($aStareDane)) { $aData['operacja'] = 'I'; } else { $aData['operacja'] = 'U'; } $aData['tabela'] = $this->_name; $aData['kolumna'] = $sNazwaKolumny; $aData['nowedane'] = $sNowaWartosc; $aData['staredane'] = $aStareDane[$sNazwaKolumny]; $aData['id_uzytkownika'] = $iIdUzytkownika; $aData['row_id'] = $iId; $aData['data_dodania'] = $oData->format('Y-m-d H:i:s'); My_Tools_Lista::Insert($this->_name_history_table, $aData); } } } } return true; }); }
public function it_dispatches_ajax_errors_properly(MvcEvent $event) { $_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest'; $event->getParams()->willReturn(['a' => 1]); $event->getResponse()->willReturn(null); $event->getError()->willReturn(AccessService::ACCESS_DENIED); $event->setResponse(Argument::type(Response::class))->shouldBeCalled(); $event->setViewModel(Argument::type(JsonModel::class))->shouldBeCalled(); $this->onDispatchError($event); }
/** * @param MvcEvent $e * @return null|\Zend\Stdlib\ResponseInterface * @throws \Exception */ public function checkAuthentication(MvcEvent $e) { $matches = $e->getRouteMatch(); if (!$matches instanceof RouteMatch) { return null; } //framework error $eventParams = $e->getParams(); if (isset($eventParams['error'])) { /** @var \Zend\Http\PhpEnvironment\Response $response */ $response = $e->getResponse(); switch ($eventParams['error']) { case Application::ERROR_CONTROLLER_NOT_FOUND: $response->setStatusCode(Response::STATUS_CODE_501); break; case Application::ERROR_ROUTER_NO_MATCH: $response->setStatusCode(Response::STATUS_CODE_501); break; default: $response->setStatusCode(Response::STATUS_CODE_500); break; } $e->stopPropagation(); return $response; } $controller = $matches->getParam('controller'); $action = $matches->getParam('action'); $config = $this->getServiceManager()->get('config'); $auth = $this->getServiceManager()->get(AuthenticationService::class); $acl = $this->getServiceManager()->get(Permissions\Acl\Acl::class); if (!$acl->hasResource($controller)) { throw new \Exception('Resource ' . $controller . ' not defined', Response::STATUS_CODE_501); } if (!$auth->hasIdentity()) { // Authentication if (!$acl->isAllowed($acl->getDefaultRole(), $controller, $action)) { /** @var FlashMessenger $flashMessenger */ $flashMessenger = $this->getPluginManager()->get(FlashMessenger::class); $flashMessenger->addErrorMessage(_('Please, sign in.')); $router = $e->getRouter(); $url = $router->assemble($matches->getParams(), array('name' => $config['tss']['authentication']['routes']['signin']['name'])); /** @var \Zend\Http\PhpEnvironment\Response $response */ $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $e->stopPropagation(); return $response; } } else { // Authorization $userRole = $auth->getIdentity()->getRoleName(); if (!$acl->isAllowed($userRole, $controller, $action)) { throw new \Exception('Resource ' . $controller . ' not allow', Response::STATUS_CODE_403); } else { $navigation = $this->getHelperManager()->get('navigation'); $navigation->setAcl($acl)->setRole($userRole); } } return null; }
public function onDispatchError(MvcEvent $event) { switch ($event->getError()) { case AccessService::ACCESS_DENIED: $statusCode = 403; break; case AccessService::ACCESS_UNAUTHORIZED: $statusCode = 401; break; default: // do nothing if this is a different kind of error we should not trap return; } if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $viewModel = new JsonModel(); } else { $viewModel = new ViewModel(); $viewModel->setTemplate('user/' . $statusCode); } $viewModel->setVariables($event->getParams()); $response = $event->getResponse() ?: new Response(); $response->setStatusCode($statusCode); $event->setViewModel($viewModel); $event->setResponse($response); }