/** * Check for document from route * * @param EventInterface $event Mvc Event * * @return void */ public function onRoute(EventInterface $event) { $matchedRouteName = $event->getRouteMatch()->getMatchedRouteName(); if ($matchedRouteName !== 'cms') { return; } $serviceManager = $event->getApplication()->getServiceManager(); $isAdmin = $serviceManager->get('Auth')->hasIdentity(); $isPreview = ($isAdmin and $event->getRequest()->getQuery()->get('preview') === 'true'); $path = ltrim($event->getRouteMatch()->getParam('path'), '/'); if (empty($path)) { $document = Document\Model::fromUrlKey(''); } else { $document = $this->findDocument($path, $isPreview); } $this->logVisitor($isPreview, $isAdmin); if (empty($document) or !$document->isPublished() and !$isPreview) { $serviceManager->setService('CurrentDocument', false); } else { $translator = $serviceManager->get('MvcTranslator'); $translator->setLocale($this->getLocale($document)); AbstractValidator::setDefaultTranslator($translator); $serviceManager->setService('CurrentDocument', $document); } }
private function attachListeners(EventInterface $event) { $request = $event->getRequest(); $application = $event->getApplication(); $services = $application->getServiceManager(); $events = $application->getEventManager(); $config = $services->get('Config'); //Display exceptions based on configuration and console mode if ($request instanceof ConsoleRequest || empty($config['view_manager']['display_exceptions'])) { return; } $jsonHandler = new JsonResponseHandler(); if (!empty($config['view_manager']['json_exceptions']['show_trace'])) { //Add trace to the JSON output $jsonHandler->addTraceToOutput(true); } if (!empty($config['view_manager']['json_exceptions']['ajax_only'])) { //Only return JSON response for AJAX requests $jsonHandler->onlyForAjaxRequests(true); } if (!empty($config['view_manager']['json_exceptions']['display'])) { //Turn on JSON handler $this->run->pushHandler($jsonHandler); } //Attach the Whoops ExceptionStrategy $exceptionStrategy = new ExceptionStrategy($this->run); $exceptionStrategy->attach($events); //Attach the Whoops RouteNotFoundStrategy $routeNotFoundStrategy = new RouteNotFoundStrategy($this->run); $routeNotFoundStrategy->attach($events); //Detach default ExceptionStrategy $services->get('Zend\\Mvc\\View\\Http\\ExceptionStrategy')->detach($events); //Detach default RouteNotFoundStrategy $services->get('Zend\\Mvc\\View\\Http\\RouteNotFoundStrategy')->detach($events); }
public function onBootstrap(EventInterface $event) { /*$eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager);*/ $application = $event->getTarget(); $serviceManager = $application->getServiceManager(); $translator = $serviceManager->get('translator'); $translator->setLocale(\Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']))->setFallbackLocale('en_US'); $application->getEventManager()->attach(MvcEvent::EVENT_DISPATCH, function (MvcEvent $event) use($serviceManager) { $request = $event->getRequest(); $response = $event->getResponse(); if (!($request instanceof HttpRequest && $response instanceof HttpResponse)) { return; // CLI application maybe? } $authAdapter = $serviceManager->get('AuthenticationAdapter'); $authAdapter->setRequest($request); $authAdapter->setResponse($response); $result = $authAdapter->authenticate(); if ($result->isValid()) { return; // OK } $response->setContent('Access denied'); $response->setStatusCode(HttpResponse::STATUS_CODE_401); $event->setResult($response); // to end return false; // event propagation stop }); }
/** * Authenticate user via cookies * * @param EventInterface $e */ public function authenticateViaCookie(EventInterface $e) { $serviceManager = $e->getApplication()->getServiceManager(); $userIsLoggedIn = $serviceManager->get('zfcuser_auth_service')->hasIdentity(); $cookie = $e->getRequest()->getCookie(); if (!$userIsLoggedIn && isset($cookie['remember_me'])) { $adapter = $e->getApplication()->getServiceManager()->get('ZfcUser\\Authentication\\Adapter\\AdapterChain'); $adapter->prepareForAuthentication($e->getRequest()); $authService = $e->getApplication()->getServiceManager()->get('zfcuser_auth_service'); $authService->authenticate($adapter); } $e->getApplication()->getEventManager()->getSharedManager()->attach('*', ['changePassword.post', 'logout'], function (EventInterface $e) use($serviceManager, $cookie) { if (isset($cookie['remember_me'])) { $cookie = explode("\n", $cookie['remember_me']); $user = $serviceManager->get('zfcuser_auth_service')->getIdentity(); $serviceManager->get('User\\Cookie\\Service\\Cookie')->removeSerie($user, $cookie[1]); $serviceManager->get('User\\Cookie\\Service\\Cookie')->removeCookie(); } }); }
/** * {@inheritDoc} */ public function onBootstrap(EventInterface $event) { if (!$event->getRequest() instanceof HttpRequest) { return; } /* @var $app \Zend\Mvc\ApplicationInterface */ $app = $event->getTarget(); /* @var $services \Zend\ServiceManager\ServiceLocatorInterface */ $services = $app->getServiceManager(); $guards = $services->get('CmsAcl\\Guards'); foreach ($guards as $guard) { $app->getEventManager()->attach($guard); } }
/** * {@inheritDoc} */ public function onBootstrap(EventInterface $e) { $config = $e->getTarget()->getServiceManager()->get('Config'); $config = isset($config['view_manager']) ? $config['view_manager'] : array(); if ($e->getRequest() instanceof ConsoleRequest || empty($config['display_exceptions'])) { return; } $this->run = new Run(); $this->run->register(); // set up whoops config $prettyPageHandler = new PrettyPageHandler(); if (isset($config['editor'])) { if ($config['editor'] == 'phpStorm') { $localPath = null; if (isset($config['local_path'])) { $localPath = $config['local_path']; } $prettyPageHandler->setEditor(function ($file, $line) use($localPath) { if ($localPath) { // if your development server is not local it's good to map remote files to local $translations = array('^' . __DIR__ => $config['editor_path']); // change to your path foreach ($translations as $from => $to) { $file = preg_replace('#' . $from . '#', $to, $file, 1); } } return "pstorm://{$file}:{$line}"; }); } else { $prettyPageHandler->setEditor($config['editor']); } } if (!empty($config['json_exceptions']['display'])) { $jsonHandler = new JsonResponseHandler(); if (!empty($config['json_exceptions']['show_trace'])) { $jsonHandler->addTraceToOutput(true); } if (!empty($config['json_exceptions']['ajax_only'])) { $jsonHandler->onlyForAjaxRequests(true); } $this->run->pushHandler($jsonHandler); } if (!empty($config['whoops_no_catch'])) { $this->noCatchExceptions = $config['whoops_no_catch']; } $this->run->pushHandler($prettyPageHandler); $eventManager = $e->getTarget()->getEventManager(); $eventManager->attach(MvcEvent::EVENT_RENDER_ERROR, array($this, 'prepareException')); $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'prepareException')); }
/** * {@inheritDoc} */ public function onBootstrap(EventInterface $event) { if (!$event->getRequest() instanceof HttpRequest) { return; } /* @var $app \Zend\Mvc\ApplicationInterface */ $app = $event->getTarget(); /* @var $services \Zend\ServiceManager\ServiceLocatorInterface */ $services = $app->getServiceManager(); /* @var $options ModuleOptionsInterface */ $options = $services->get(ModuleOptions::class); /* @var $strategy \CmsAuthorization\View\Strategy\AbstractStrategy */ $strategy = $services->get($options->getUnauthorizedStrategy()); $app->getEventManager()->attach($strategy); }
public function onBootstrap(EventInterface $e) { /** @var EventManager $eventManager */ $eventManager = $e->getApplication()->getEventManager(); $eventManager->attach(MvcEvent::EVENT_ROUTE, function (EventInterface $e) { /** @var Request $request */ $request = $e->getRequest(); if (!$request instanceof Request) { return; } $serviceManager = $e->getApplication()->getServiceManager(); $routeGenerator = $serviceManager->get(RouteGenerator::class); $routeGenerator->generate(); }, 1000); }
public function onBootstrap(EventInterface $e) { /* @var $e MvcEvent */ $eventManager = $e->getApplication()->getEventManager(); $sharedManager = $eventManager->getSharedManager(); $createJobListener = new \Organizations\Acl\Listener\CheckJobCreatePermissionListener(); $createJobListener->attachShared($sharedManager); if ($e->getRequest() instanceof \Zend\Http\Request) { $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function (MvcEvent $event) { $serviceManager = $event->getApplication()->getServiceManager(); $options = $serviceManager->get('Organizations/ImageFileCacheOptions'); if ($options->getEnabled()) { $serviceManager->get('Organizations\\ImageFileCache\\ApplicationListener')->onDispatchError($event); } }); } }
/** * Bootstrap Listener * * @param EventInterface $event * @return void */ public function onBootstrap(EventInterface $event) { $request = $event->getRequest(); if (!$request instanceof PhpRequest) { return; } $app = $event->getTarget(); $locator = $app->getServiceManager(); $config = $locator->get('Config'); if (true === $config['netglue_ip']['rewrite_remote_addr']) { $service = $locator->get('NetglueIp\\Service\\IpService'); if ($ip = $service->getIp()) { $serverParams = $request->getServer(); $serverParams->ORIGINAL_REMOTE_ADDR = $serverParams->REMOTE_ADDR; $serverParams->REMOTE_ADDR = $ip; } } }
/** * Load menu if module has view with name "menu.phtml" * * @param EventInterface $event Event * * @return void */ public function loadMenu(EventInterface $event) { if ($route = $event->getRouter()->getRoute('module')->match($event->getRequest())) { if ($route->getParam('module') === 'module') { return; } $filter = new Filter\Word\CamelCaseToSeparator(); $filter->setSeparator('-'); $filterChain = new Filter\FilterChain(); $filterChain->attach($filter)->attach(new Filter\StringToLower()); $template = $filterChain->filter($route->getParam('module')) . '/menu'; $target = $event->getTarget(); $resolver = $event->getApplication()->getServiceManager()->get('Zend\\View\\Resolver\\TemplatePathStack'); $navigation = $target->getServiceLocator()->get('navigation'); $navigation->findByRoute('module')->addPage(array('label' => $route->getParam('module'), 'route' => $event->getRouteMatch()->getMatchedRouteName(), 'active' => true)); if (false !== $resolver->resolve($template)) { $target->layout()->setVariable('moduleMenu', $template); } } }
/** * Check if ssl is forced or not * * @param EventInterface $event Mvc event * * @return null|Zend\Http\PhpEnvironment\Response */ public function check(EventInterface $event) { $coreConfig = $event->getApplication()->getServiceManager()->get('CoreConfig'); $matchedRouteName = $event->getRouteMatch()->getMatchedRouteName(); $request = $event->getRequest(); $uri = $request->getUri(); if ($matchedRouteName === 'cms') { if ($uri->getScheme() === 'https' or $coreConfig->getValue('force_frontend_ssl')) { $newUri = new Uri($coreConfig->getValue('secure_frontend_base_path')); $newUri->setScheme('https'); } else { $newUri = new Uri($coreConfig->getValue('unsecure_frontend_base_path')); } } else { if ($uri->getScheme() === 'https' or $coreConfig->getValue('force_backend_ssl')) { $newUri = new Uri($coreConfig->getValue('secure_backend_base_path')); $newUri->setScheme('https'); } else { $newUri = new Uri($coreConfig->getValue('unsecure_backend_base_path')); } } if (!empty($newUri) and $newUri->isValid() and ($newUri->getHost() != '' and $uri->getHost() != $newUri->getHost()) or $newUri->getScheme() != '' and $uri->getScheme() != $newUri->getScheme()) { $uri->setPort($newUri->getPort()); if ($newUri->getHost() != '') { $uri->setHost($newUri->getHost()); } if ($newUri->getScheme() != '') { $uri->setScheme($newUri->getScheme()); } $response = $event->getResponse(); $response->setStatusCode(302); $response->getHeaders()->addHeaderLine('Location', $request->getUri()); $event->stopPropagation(); return $response; } }
/** * @param EventInterface $event */ public function logRequest(EventInterface $event) { if ($event->getRequest() instanceof \Zend\Http\PhpEnvironment\Request) { $this->getLog()->debug(print_r(array($event->getRequest()->getUri()->getHost() => array('Request' => $event->getRequest()->getUri())), true)); } }
public function onBootstrap(EventInterface $e) { $serviceManager = $e->getApplication()->getServiceManager(); $config = $e->getApplication()->getServiceManager()->get('config'); $translator = $serviceManager->get('translator'); // Gestion de la locale if (PHP_SAPI !== 'cli') { //translator // Gestion locale pour le back if ($serviceManager->get('router')->match($serviceManager->get('request')) && strpos($serviceManager->get('router')->match($serviceManager->get('request'))->getMatchedRouteName(), 'admin') !== false) { if ($e->getRequest()->getCookie() && $e->getRequest()->getCookie()->offsetExists('pg_locale_back')) { $locale = $e->getRequest()->getCookie()->offsetGet('pg_locale_back'); } } if (empty($locale)) { if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $locale = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); } else { $locale = 'fr_FR'; } } $translator->setLocale($locale); // plugins $translate = $serviceManager->get('viewhelpermanager')->get('translate'); $translate->getTranslator()->setLocale($locale); $options = $serviceManager->get('playgroundcore_module_options'); $options->setLocale($locale); } // positionnement de la langue pour les traductions de date avec strftime setlocale(LC_TIME, "fr_FR", 'fr_FR.utf8', 'fra'); AbstractValidator::setDefaultTranslator($translator, 'playgroundcore'); /* * Entity translation based on Doctrine Gedmo library */ $doctrine = $serviceManager->get('doctrine.entitymanager.orm_default'); $evm = $doctrine->getEventManager(); $translatableListener = new \Gedmo\Translatable\TranslatableListener(); // TODO : Set the Default locale to be taken from config $translatableListener->setDefaultLocale('fr_FR'); // If no translation is found, fallback to entity data $translatableListener->setTranslationFallback(true); // set Locale if (!empty($locale)) { $translatableListener->setTranslatableLocale($locale); } $evm->addEventSubscriber($translatableListener); /** * Adding a Filter to slugify a string (make it URL compliiant) */ $filterChain = new \Zend\Filter\FilterChain(); $filterChain->getPluginManager()->setInvokableClass('slugify', 'PlaygroundCore\\Filter\\Slugify'); $filterChain->attach(new Filter\Slugify()); // Start the session container $sessionConfig = new SessionConfig(); $sessionConfig->setOptions($config['session']); $sessionManager = new SessionManager($sessionConfig); $sessionManager->start(); /** * Optional: If you later want to use namespaces, you can already store the * Manager in the shared (static) Container (=namespace) field */ \Zend\Session\Container::setDefaultManager($sessionManager); // Google Analytics : When the render event is triggered, we invoke the view helper to // render the javascript code. $e->getApplication()->getEventManager()->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER, function (\Zend\Mvc\MvcEvent $e) use($serviceManager) { $view = $serviceManager->get('ViewHelperManager'); $plugin = $view->get('googleAnalytics'); $plugin(); $pluginOG = $view->get('facebookOpengraph'); $pluginOG(); }); if (PHP_SAPI !== 'cli') { $session = new Container('facebook'); $fb = $e->getRequest()->getPost()->get('signed_request'); if ($fb) { list($encoded_sig, $payload) = explode('.', $fb, 2); $sig = base64_decode(strtr($encoded_sig, '-_', '+/')); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); $session->offsetSet('signed_request', $data); // This fix exists only for safari on Windows : we need to redirect the user to the page outside of iframe // for the cookie to be accepted. Core just adds a 'redir_fb_page_id' var to alert controllers // that they need to send the user back to FB... if (!count($_COOKIE) > 0 && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari')) { echo '<script type="text/javascript">' . 'window.top.location.href = window.location.href+"?redir_fb_page_id=' . $data["page"]["id"] . '";' . '</script>'; } // This fix exists only for IE6+, when this app is embedded into an iFrame : The P3P policy has to be set. $response = $e->getResponse(); if ($response instanceof \Zend\Http\Response && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') || strpos($_SERVER['HTTP_USER_AGENT'], 'rv:11.'))) { $response->getHeaders()->addHeaderLine('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); } } } }
public function onRoute(\Zend\EventManager\EventInterface $e) { $application = $e->getApplication(); $routeMatch = $e->getRouteMatch(); $serviceManager = $application->getServiceManager(); $authenticationService = $serviceManager->get('Zend\\Authentication\\AuthenticationService'); $acl = $serviceManager->get('VisoftBaseModule\\Service\\Authorization\\Acl\\Acl'); // everyone is guest until logging in $role = \VisoftBaseModule\Service\Authorization\Acl\Acl::DEFAULT_ROLE; // The default role is guest $acl // get role if user logged in if ($authenticationService->hasIdentity()) { $user = $authenticationService->getIdentity(); $role = $user->getRole()->getName(); } // requested route $controller = $routeMatch->getParam('controller'); $action = $routeMatch->getParam('action'); $params = $routeMatch->getParams(); if (!$acl->hasResource($controller)) { throw new \Exception('Resource ' . $controller . ' not defined in ACL'); } if (!$acl->isAllowed($role, $controller, $action)) { $response = $e->getResponse(); $requestedUri = $e->getRequest()->getRequestUri(); $config = $serviceManager->get('config'); $redirect_route = $config['acl']['redirect_route']; if (!empty($redirect_route)) { // TODO: FIXIT $url = $e->getRouter()->assemble($redirect_route['params'], $redirect_route['options']); $response->getHeaders()->addHeaderLine('Location', $url); // The HTTP response status code 302 Found is a common way of performing a redirection. // http://en.wikipedia.org/wiki/HTTP_302 $response->setStatusCode(302); $headers = $response->getHeaders(); $cookie = new \Zend\Http\Header\SetCookie('requestedUri', $requestedUri, time() + 60, '/'); $headers->addHeader($cookie); $response->sendHeaders(); exit; } else { // Status code 403 responses are the result of the web server being configured to deny access, // for some reason, to the requested resource by the client. // http://en.wikipedia.org/wiki/HTTP_403 $response->setStatusCode(403); $response->setContent(' <html> <head> <title>403 Forbidden</title> </head> <body> <h1>403 Forbidden</h1> </body> </html>'); return $response; } } }
/** * {@inheritDoc} */ public function onBootstrap(EventInterface $e) { if ($e->getRequest() instanceof HttpRequest) { $this->setExtensionParams($e); } }
/** * @param EventInterface $event */ public function logResponse(EventInterface $event) { if ($event->getRequest() instanceof \Zend\Http\PhpEnvironment\Request) { $contentType = $event->getResponse()->getHeaders()->get('Content-Type'); $content = $event->getResponse()->getContent(); if ($contentType instanceof \Zend\Http\Header\ContentType) { if (in_array($event->getResponse()->getHeaders()->get('Content-Type')->getMediaType(), $this->getIgnoreMediaTypes())) { $content = 'BINARY'; } } $this->getLog()->debug(print_r(array($event->getRequest()->getUri()->getHost() => array('Response' => array('statusCode' => $event->getResponse()->getStatusCode(), 'contentType' => !$event->getResponse()->getHeaders()->get('Content-Type') ? 'unknown' : $event->getResponse()->getHeaders()->get('Content-Type')->getMediaType(), 'content' => $content))), true)); } }
/** * Listen to the bootstrap event * * @param \Zend\EventManager\EventInterface $event * @return array */ public function onBootstrap(EventInterface $event) { /* @var $event \Zend\Mvc\MvcEvent */ /* @var $application \Zend\Mvc\Application */ /* @var $serviceManager \Zend\ServiceManager\ServiceManager */ $application = $event->getApplication(); $serviceManager = $application->getServiceManager(); $application->getEventManager()->getSharedManager()->attach('Zend\\Mvc\\Application', MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'onDispatchError')); $response = $event->getResponse(); if ($response instanceof HttpResponse && $serviceManager->has('RedirectToDomain')) { $redirect = $serviceManager->get('RedirectToDomain'); $path = ''; $request = $event->getRequest(); if ($request instanceof HttpRequest && $redirect->getUsePath()) { $path = $request->getRequestUri(); } $url = $redirect->getUrl($path); $response->setStatusCode(302)->getHeaders()->addHeaders(array('Location' => $url, 'X-Redirect-Reason' => $redirect->getReason())); $this->response = $response->setContent(sprintf('<meta http-equiv="refresh" content="0;url=%1$s">' . '<a href="%1$s">%1$s</a>', htmlspecialchars($url))); } }