public function isOpenRequest(MvcEvent $e) { if ($e->getRouteMatch()->getParam('controller') == 'SanAuthWithDbSaveHandler\\Controller\\AuthController') { return true; } return false; }
public function onBootstrap(MvcEvent $e) { $app = $e->getApplication(); $eventManager = $app->getEventManager(); $locator = $app->getServiceManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $this->initFirePHP(); $this->initAuthentication(); // 微软这个流氓,低于IE10版本一下的IE浏览器都需要使用text/html格式的Response,否则json在浏览器中会提示下载 $eventManager->attach(MvcEvent::EVENT_RENDER, function ($event) { $objResponse = $event->getResponse(); if (method_exists($objResponse, 'getHeaders')) { $objHeaders = $objResponse->getHeaders(); $contentType = $objHeaders->get('Content-Type'); if ($contentType) { $contentType = $contentType->getFieldValue(); if (strpos($contentType, 'application/json') !== false) { $objHeaders->addHeaderLine('Content-Type', 'text/html;charset=utf-8'); } } else { $objHeaders->addHeaderLine('Content-Type', 'text/html;charset=utf-8'); } } }, -10000); // 错误提示的时候,执行特殊的layout $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function (MvcEvent $event) { $viewModel = $event->getViewModel(); $viewModel->setTemplate('layout/error'); }, -200); }
public function initLocale(MvcEvent $e) { //Получаем объект translator'a $translator = $e->getApplication()->getServiceManager()->get('translator'); $translator->setLocale('ru_RU'); // ru_RU, en_US, etc... }
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(); } } }
/** * @param MvcEvent $event */ public function renderRequest(MvcEvent $event) { /** @var Response $zendResponse */ $zendResponse = $event->getResponse(); $zendResponse->send(); $event->stopPropagation(); }
/** * Handles redirects in case of dispatch errors caused by unauthorized access * * @param MvcEvent $event * @return void */ public function onError(MvcEvent $event) { if (!$event->getRequest() instanceof HttpRequest || !($routeMatch = $event->getRouteMatch())) { return; } if (null === $this->redirectUri) { if (null === $this->redirectRoute) { if ($this->authenticationService->hasIdentity()) { $this->setRedirectRoute($this->options->getAuthenticatedIdentityRedirectRoute()); } else { $this->setRedirectRoute($this->options->getUnauthenticatedIdentityRedirectRoute()); } } if (!($this->redirectRoute && $this->redirectRoute !== $routeMatch->getMatchedRouteName())) { return parent::onError($event); } $params = ['name' => $this->redirectRoute]; if ($this->options->getUseRedirectParameter()) { $redirectKey = $this->options->getRedirectKey(); $params['query'][$redirectKey] = $event->getRequest()->getUriString(); } $this->setRedirectUri($event->getRouter()->assemble([], $params)); } $response = $event->getResponse() ?: new HttpResponse(); $response->getHeaders()->addHeaderLine('Location', $this->redirectUri); $response->setStatusCode(302); $event->setResponse($response); }
public function onBootstrap(MvcEvent $e) { $app = $e->getApplication(); $events = $app->getEventManager(); $services = $app->getServiceManager(); $events->attach($services->get('ZF\\ContentValidation\\ContentValidationListener')); }
public function onDispatch(MvcEvent $e) { /** @var ConsoleRequest $request */ $request = $this->getRequest(); $queueName = $request->getParam('queueName'); $messageId = $request->getParam('messageId'); if (!isset($this->config[$queueName])) { echo "Bad queue name: " . $queueName; return; } $this->queueConfig = $this->config[$queueName]; $this->debug("Queue name: " . $queueName); $this->debug("Message Id: " . $messageId); /** @var QueueMessage $message */ $message = $this->messageRepository->findById($messageId); /** @var WorkerInterface $handler */ $handler = $this->getServiceLocator()->get($this->queueConfig['handler']); $message->setProcessed(); $this->messageRepository->add($message); try { $handler->handle($message->getMessage()); } catch (\Exception $e) { $message->setFailed($e->getMessage()); $this->messageRepository->add($message); } $message->setCompleted(); $this->messageRepository->add($message); $this->debug("done"); }
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']); }
/** * Bootstrap session * * @param MvcEvent $event */ private function bootstrapSession(MvcEvent $event) { $session = $event->getApplication()->getServiceManager()->get('Zend\\Session\\SessionManager'); $session->start(); $container = new Container('initialized'); if (!isset($container->init)) { $serviceManager = $event->getApplication()->getServiceManager(); $request = $event->getRequest(); $session->regenerateId(); $container->init = 1; $container->remoteAddr = $request->getServer()->get('REMOTE_ADDR'); $container->httpUserAgent = $request->getServer()->get('HTTP_USER_AGENT'); $config = $serviceManager->get('Config'); if (!isset($config['session'])) { return; } $sessionConfig = $config['session']; if (isset($sessionConfig['validators'])) { $chain = $session->getValidatorChain(); foreach ($sessionConfig['validators'] as $validator) { switch ($validator) { case 'Zend\\Session\\Validator\\HttpUserAgent': $validator = new $validator($container->httpUserAgent); break; case 'Zend\\Session\\Validator\\RemoteAddr': $validator = new $validator($container->remoteAddr); break; default: $validator = new $validator(); } $chain->attach('session.validate', array($validator, 'isValid')); } } } }
/** * Handle layout titles onDispatch. * * @param MvcEvent $event */ public function setTitleAndTranslation(MvcEvent $event) { $route = $event->getRouteMatch(); $title = $this->service->get('ControllerPluginManager')->get('systemsettings'); $viewHelper = $this->service->get('ViewHelperManager'); $lang = new Container('translations'); $translator = $this->service->get('translator'); /* * Load translations. */ $renderer = $this->service->get('ViewManager')->getRenderer(); $renderer->plugin('formRow')->setTranslator($translator, 'SD_Translations'); $renderer->plugin('formCollection')->setTranslator($translator, 'SD_Translations'); $renderer->plugin('formLabel')->setTranslator($translator, 'SD_Translations'); $renderer->plugin('formSelect')->setTranslator($translator, 'SD_Translations'); $renderer->plugin('formSubmit')->setTranslator($translator, 'SD_Translations'); AbstractValidator::setDefaultTranslator($translator, 'formandtitle'); $translator->setLocale($lang->offsetGet('languageName'))->setFallbackLocale('en'); $viewModel = $event->getViewModel(); $viewModel->setVariable('lang', $translator->getLocale()); /* * Custom flash messenger. */ $msg = $lang->offsetGet('flashMessages'); $viewModel->setVariable('flashMessages', $msg); /* * Load page title */ $action = $route->getParam('post') ? ' - ' . $route->getParam('post') : ucfirst($route->getParam('__CONTROLLER__')); $headTitleHelper = $viewHelper->get('headTitle'); $headTitleHelper->append($title->__invoke('general', 'site_name') . ' ' . $action); }
public function setTemplate(MvcEvent $e) { $result = $e->getResult(); $router = $e->getRouteMatch(); $params = $router->getParams(); if (isset($params['__NAMESPACE__']) && isset($params['__CONTROLLER__']) && isset($params['action'])) { $controllerClass = $params['__NAMESPACE__']; $moduleNamespace = substr($controllerClass, strpos($controllerClass, '\\')); $moduleNamespace = substr($moduleNamespace, 1); $moduleNamespace = substr($moduleNamespace, 0, strpos($moduleNamespace, '\\Controller')); $templatePath = __DIR__; $config = $e->getApplication()->getServiceManager()->get('config'); if (isset($config['view_manager']['template_map'])) { $moduleNamespace = strtolower($moduleNamespace . '/' . $params['__CONTROLLER__']); $templatePath = $templatePath . '/view/' . $moduleNamespace . '/' . $params['action'] . '.phtml'; $moduleNamespace = str_replace('\\', '/', $moduleNamespace); $template = $moduleNamespace . '/' . $params['action']; $config['view_manager']['template_map'][$template] = $templatePath; $result->setTemplate($template); } //set Title; if (isset($config['view_manager']['siteName'])) { $siteName = $config['view_manager']['siteName']; } else { $siteName = $moduleNamespace; } $viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager'); $headTitle = $viewHelperManager->get('headTitle'); $headTitle->setSeparator(' - '); $headTitle->append($params['action']); $headTitle->append($siteName); } }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $eventManager->getSharedManager()->attach('Applications', 'application.detail.actionbuttons', function ($event) { return 'pdf/application/details/button'; }); }
public function onBootstrap(MvcEvent $e) { $e->getApplication()->getServiceManager()->get('translator'); $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); }
/** * @return \Doctrine\ORM\EntityManager */ public function getEntityManager() { if (null === $this->entityManager) { $this->entityManager = $this->event->getApplication()->getServiceManager()->get('Doctrine\\ORM\\EntityManager'); } return $this->entityManager; }
/** * Listen to the "route" event and determine if the module namespace should * be prepended to the controller name. * * If the route match contains a parameter key matching the MODULE_NAMESPACE * constant, that value will be prepended, with a namespace separator, to * the matched controller parameter. * * @param MvcEvent $e * @return null */ public function onRoute($e) { $matches = $e->getRouteMatch(); if (!$matches instanceof Router\RouteMatch) { // Can't do anything without a route match return; } $module = $matches->getParam(self::MODULE_NAMESPACE, false); if (!$module) { // No module namespace found; nothing to do return; } $controller = $matches->getParam('controller', false); if (!$controller) { // no controller matched, nothing to do return; } // Ensure the module namespace has not already been applied if (0 === strpos($controller, $module)) { return; } // Keep the originally matched controller name around $matches->setParam(self::ORIGINAL_CONTROLLER, $controller); // Prepend the controllername with the module, and replace it in the // matches $controller = $module . '\\' . $controller; $matches->setParam('controller', $controller); }
public function testCollect() { $event = new MvcEvent(); $layoutModel = new ViewModel(); $layoutModel->setTemplate('layout/2cols-left'); $event->setViewModel($layoutModel); $testBlock = new ViewModel(); $testBlock->setTemplate('widget1'); $testBlock->setCaptureTo('sidebarLeft'); $testBlock2 = new ViewModel(); $testBlock2->setOption('parent', 'test.block'); $testBlock2->setTemplate('widget1'); $this->blockPool->add('test.block', $testBlock); $this->blockPool->add('test.block2', $testBlock2); $this->collector->collect($event); $this->assertEquals('layout/2cols-left', $this->collector->getLayoutTemplate()); $this->assertInternalType('array', $this->collector->getHandles()); $this->assertContainsOnlyInstancesOf(HandleInterface::class, $this->collector->getHandles()); $this->assertInternalType('array', $this->collector->getBlocks()); $blocks = $this->collector->getBlocks(); $testBlockArray = current($blocks); $testBlock2Array = array_pop($blocks); $this->assertEquals('test.block::content', $testBlock2Array['capture_to']); $this->assertContains('_files/view/widget1.phtml', $testBlockArray['template']); $this->assertEquals('sidebarLeft', $testBlockArray['capture_to']); $this->assertEquals(ViewModel::class, $testBlockArray['class']); $this->assertEquals(LayoutUpdaterInterface::AREA_DEFAULT, $this->collector->getCurrentArea()); $this->assertInternalType('array', $this->collector->getLayoutStructure()); }
/** * @param MvcEvent $event */ public function errorEventHandler(MvcEvent $event) { $exception = $event->getParam('exception'); if ($exception) { $this->logException($exception); } }
/** * Test if the content-type received is allowable. * * @param MvcEvent $e * @return null|ApiProblemResponse */ public function onRoute(MvcEvent $e) { if (empty($this->config)) { return; } $controllerName = $e->getRouteMatch()->getParam('controller'); if (!isset($this->config[$controllerName])) { return; } // Only worry about content types on HTTP methods that submit content // via the request body. $request = $e->getRequest(); if (!method_exists($request, 'getHeaders')) { // Not an HTTP request; nothing to do return; } $requestBody = (string) $request->getContent(); if (empty($requestBody)) { return; } $headers = $request->getHeaders(); if (!$headers->has('content-type')) { return new ApiProblemResponse(new ApiProblem(415, 'Invalid content-type specified')); } $contentTypeHeader = $headers->get('content-type'); $matched = $contentTypeHeader->match($this->config[$controllerName]); if (false === $matched) { return new ApiProblemResponse(new ApiProblem(415, 'Invalid content-type specified')); } }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $eventManager->getSharedManager(); }
public function checkAcl(MvcEvent $e) { if (!$e->getRequest() instanceof \Zend\Http\Request) { return; } $route = $e->getRouteMatch()->getMatchedRouteName(); /* @var $aclEnforcer \FzyAuth\Service\AclEnforcerInterface */ $aclEnforcer = $this->getServiceLocator()->get('FzyAuth\\AclEnforcerFactory'); $aclEnforcer->init($e); $aclEnforcer->attachToView($e->getViewModel()); $controller = $e->getRouteMatch()->getParam('controller'); $action = $e->getRouteMatch()->getParam('action'); $missing = true; if ($aclEnforcer->hasControllerResource($controller)) { $missing = false; if ($aclEnforcer->isAllowed(AclEnforcerInterface::RESOURCE_CONTROLLER_PREFIX . $controller, $action)) { return $aclEnforcer->handleAllowed($e); } } if ($aclEnforcer->hasRouteResource($route)) { $missing = false; if ($aclEnforcer->isAllowed(AclEnforcerInterface::RESOURCE_ROUTE_PREFIX . $route, $action)) { return $aclEnforcer->handleAllowed($e); } } return $missing ? $aclEnforcer->handleRouteMissing($e) : $aclEnforcer->handleNotAllowed($e); }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $serviceManager = $e->getApplication()->getServiceManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); if (!Console::isConsole()) { $viewHelperManager = $serviceManager->get('ViewHelperManager'); $formElementErrors = $viewHelperManager->get('formElementErrors'); $formElementErrors->setMessageOpenFormat('<div class="zui-error">'); $formElementErrors->setMessageSeparatorString('</div><div class="zui-error">'); $formElementErrors->setMessageCloseString('</div>'); $flashMessenger = $viewHelperManager->get('flashMessenger'); $flashMessenger->setMessageOpenFormat('<div class="zui-alert zui-alert-%s"><p>'); $flashMessenger->setMessageSeparatorString('</p><p>'); $flashMessenger->setMessageCloseString('</p><span class="zui-icon zui-icon-x" role="button" tabindex="0"></span></div>'); /** @var ManagerInterface $sessionManager */ $sessionManager = $serviceManager->get(ManagerInterface::class); $sessionManager->start(); } $helpers = $serviceManager->get('ViewHelperManager'); $hal = $helpers->get('Hal'); $hal->getEventManager()->attach('renderCollection.post', [$this, 'onRenderCollection']); $hal->getEventManager()->attach('renderEntity.post', [$this, 'onRenderEntity']); }
/** * {@inheritdoc} */ public function isGranted(MvcEvent $event) { $routeMatch = $event->getRouteMatch(); $controller = $routeMatch->getParam('controller'); $action = $routeMatch->getParam('action'); return $this->getAccessService()->isAllowed($controller, $action); }
/** * Take parameters from RouteMatch and inject them into the request. * * @param MvcEvent $e * @return void */ public function injectParams(MvcEvent $e) { $routeMatchParams = $e->getRouteMatch()->getParams(); $request = $e->getRequest(); /** @var $params \Zend\Stdlib\Parameters */ if ($request instanceof ConsoleRequest) { $params = $request->params(); } elseif ($request instanceof HttpRequest) { $params = $request->get(); } else { // unsupported request type return; } if ($this->overwrite) { foreach ($routeMatchParams as $key => $val) { $params->{$key} = $val; } } else { foreach ($routeMatchParams as $key => $val) { if (!$params->offsetExists($key)) { $params->{$key} = $val; } } } }
public function onBootstrap(MvcEvent $e) { $application = $e->getApplication(); $service_manager = $application->getServiceManager(); $event_manager = $application->getEventManager(); $shared_manager = $event_manager->getSharedManager(); /* allow controller short names in routing */ $module_route_listener = new ModuleRouteListener(); $module_route_listener->attach($event_manager); /* set sup our localization strategy so that we enforce localization routes */ $service_manager->get('Http\\LocalizationStrategy')->attach($event_manager); /* the scheme strategy handles processing based on (http|https) scheme */ $service_manager->get('Http\\SchemeStrategy')->attach($event_manager); /* the theme strategy handles setting up basic head scripts and style sheets to the layout */ $service_manager->get('Http\\ThemeStrategy')->attach($event_manager); /* the exception logger strategy dumps exception messages to the log before ZF2 gets it and swallows it */ $service_manager->get('Http\\ExceptionLoggerStrategy')->attach($event_manager); /* the layout strategy handles overriding the layout for specific routes */ $service_manager->get('Http\\LayoutStrategy')->attach($event_manager); /* Cornerstone Application Event Manager */ $cornerstone_event_manager = $service_manager->get('Application\\EventManager'); /* attach our CLI strategies */ $service_manager->get('Console\\InitializeApplicationStrategy')->attach($cornerstone_event_manager); $service_manager->get('Console\\BuildVirtualHostStrategy')->attach($cornerstone_event_manager); $service_manager->get('Console\\ApplicationCacheInitStrategy')->attach($cornerstone_event_manager); $service_manager->get('Console\\ApplicationCacheEmptyStrategy')->attach($cornerstone_event_manager); $service_manager->get('Console\\CasperConfigurationStrategy')->attach($cornerstone_event_manager); }
/** * {@inheritDoc} */ public function isGranted(MvcEvent $event) { $routeMatch = $event->getRouteMatch(); $controller = strtolower($routeMatch->getParam('controller')); $action = strtolower($routeMatch->getParam('action')); // If no rules apply, it is considered as granted or not based on the protection policy if (!isset($this->rules[$controller])) { return $this->protectionPolicy === self::POLICY_ALLOW; } // Algorithm is as follow: we first check if there is an exact match (controller + action), if not // we check if there are rules set globally for the whole controllers (see the index "0"), and finally // if nothing is matched, we fallback to the protection policy logic if (isset($this->rules[$controller][$action])) { $providerName = $this->rules[$controller][$action]; } elseif (isset($this->rules[$controller][0])) { $providerName = $this->rules[$controller][0]; } else { return $this->protectionPolicy === self::POLICY_ALLOW; } $provider = new $providerName($event); $provider->setServiceLocator($this->getServiceLocator()); $allowedRoles = $provider->getRoles(); if (in_array('*', $allowedRoles)) { return true; } return $this->roleService->matchIdentityRoles($allowedRoles); }
public function loadConfiguration(MvcEvent $e) { $controller = $e->getTarget(); $user_session = new Container('usuario'); $controller->layout()->nome = trim(substr($user_session->nome, 0, 16)); $controller->layout()->foto = $user_session->foto ? "/fotos/" . str_replace(" ", "_", $user_session->foto) : "/fotos/default.jpg"; }
public function onBootstrap(MvcEvent $event) { // Set the static service manager instance so we can use it everywhere in the module $serviceManager = $event->getApplication()->getServiceManager(); $themeManager = $serviceManager->get('ZeThemeManager'); $themeManager->init(); }
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; } }
/** * Whoops handle exceptions * @param MvcEvent $e */ public function prepareException(MvcEvent $e) { $error = $e->getError(); if (!empty($error) && !$e->getResult() instanceof Response) { 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: if (in_array(get_class($e->getParam('exception')), $this->noCatchExceptions)) { // No catch this exception return; } $response = $e->getResponse(); if (!$response || $response->getStatusCode() === 200) { header('HTTP/1.0 500 Internal Server Error', true, 500); } ob_clean(); $this->run->handleException($e->getParam('exception')); break; } } }