Handle a CORS request (non-preflight, normal CORS request)

@param MvcEvent $event
548887
public function onCorsRequest(MvcEvent $event)
    {
        // Do nothing if we previously created a preflight response
        if ($this->isPreflight) {
            return;
        }

        /** @var $request HttpRequest */
        $request  = $event->getRequest();
        /** @var $response HttpResponse */
        $response = $event->getResponse();


        if (! $request instanceof HttpRequest) {
            return;
        }

        try {
            $isCorsRequest = $this->corsService->isCorsRequest($request);
        } catch (InvalidOriginException $exception) {
            // InvalidOriginException should already be handled by `CorsRequestListener::onCorsPreflight`
            return;
        }

        // Also ensure that the vary header is set when no origin is set
        // to prevent reverse proxy caching a wrong request; causing all of the following
        // requests to fail due to missing CORS headers.
        if (! $isCorsRequest) {
            if (! $request->getHeader('Origin')) {
                $this->corsService->ensureVaryHeader($response);
            }
            return;
        }

        // This is the second step of the CORS request, and we let ZF continue
        // processing the response
        try {
            $response = $this->corsService->populateCorsResponse($request, $response);
        } catch (DisallowedOriginException $exception) {
            $response = new HttpResponse(); // Clear response for security
            $response->setStatusCode(403)
                     ->setReasonPhrase($exception->getMessage());
        }

        $event->setResponse($response);
    }
57444
protected function config(MvcEvent $event)
    {
        $appConfig = $event->getApplication()->getServiceManager()->get('config');
        $config = array_key_exists(self::CONFIG_KEY, $appConfig) ? $appConfig[self::CONFIG_KEY] : array();
        
        if (array_key_exists('template', $config)) {
            $this->setTemplate($config['template']);
        }
        
        if (array_key_exists('renderLayout', $config)) {
            $this->setRenderLayout($config['renderLayout']);
        }
    }
808173
public function onRoute(MvcEvent $e)
    {
        /* @var $request \Zend\Http\PhpEnvironment\Request */
        $request = $e->getRequest();

        /* Detect language */
        $lang = $request->getQuery('lang');

        if (!$lang) {
            $headers = $request->getHeaders();
            if ($headers->has('Accept-Language')) {
                /* @var $acceptLangs \Zend\Http\Header\AcceptLanguage */
                $acceptLangs = $headers->get('Accept-Language');
                $locales = $acceptLangs->getPrioritized();
                $locale  = $locales[0];
                $lang    = $locale->type;
            } else {
                $lang = 'en';
            }
        }

        /* Set locale */
        $translator = $e->getApplication()->getServiceManager()->get('mvctranslator');
        $locale     = $lang . '_' . strtoupper($lang);

        setlocale(
            LC_ALL,
            array(
                            $locale . ".utf8",
                            $locale . ".iso88591",
                            $locale,
                            substr($locale, 0, 2),
                            'de_DE.utf8',
                            'de_DE',
                            'de'
                        )
        );
        \Locale::setDefault($locale);
        $translator->setLocale($locale);
        $routeMatch = $e->getRouteMatch();
        if ($routeMatch && $routeMatch->getParam('lang') === null) {
            $routeMatch->setParam('lang', $lang);
        }

        /* @var $router \Zend\Mvc\Router\SimpleRouteStack */
        $router = $e->getRouter();
        $router->setDefaultParam('lang', $lang);
    }
387089
protected function injectContentTemplate(MvcEvent $event)
    {
        $model = $event->getResult();

        if (! $model instanceof ViewModel) {
            return $this;
        }
        if ($model->getTemplate()) {
            return $this;
        }

        $routeMatch   = $event->getRouteMatch();
        $themeName    = $this->getThemeName();
        $themeOptions = $this->getThemeOptions();

        $options = [];
        if (isset($themeOptions[static::$side])) {
            $options = $themeOptions[static::$side];
        }

        if (isset($options['templates'])) {
            $templatesPath = rtrim($options['templates'], '/') . '/';
        } else {
            $templatesPath = str_replace(
                ['{theme}', '{side}'],
                [$themeName, static::$side],
                self::DefaultTemplatesPath
            );
        }

        $controller = $event->getTarget();
        if ($controller) {
            $controller = get_class($controller);
        } else {
            $controller = $routeMatch->getParam('controller', '');
        }
        $controller = $this->deriveControllerClass($controller);
        $template = $templatesPath . $this->inflectName($controller);

        $action  = $routeMatch->getParam('action');
        if (null !== $action) {
            $template .= '/' . $this->inflectName($action);
        }

        $model->setTemplate($template);

        return $this;
    }
821197
public function onPostRoute(MvcEvent $e)
    {
        $matches = $e->getRouteMatch();
        if (!$matches instanceof Router\RouteMatch) {
            // Can't do anything without a route match
            return;
        }
        
    	// Check for 'asset_manager' route
    	$routeName = $matches->getMatchedRouteName();
    	$routeName = explode('/', $routeName, 2);
    	$routeName = $routeName[0];
    	
    	if ($routeName !== 'asset_manager') {
    		// Not an asset request
    		return;
    	}
    	
    	// TODO: Take care of grouped assets (Merged assets)
    	//       Right now only direct access
    	
    	$serviceManager = $e->getApplication()->getServiceManager();
    	$router         = $e->getRouter();
    	$assetManager   = $serviceManager->get('AssetManager');
    	
    	$requestPath     = $e->getRequest()->getUri()->getPath();
    	$requestBasePath = $router->assemble(array(), array('name' => 'asset_manager'));
    	$requestBasePath = $requestBasePath . '/';
   
    	if (strlen($requestPath) <= strlen($requestBasePath)) {
    		// Not enough data!
    		return;
    	}
    	
    	$requestPath = substr($requestPath, strlen($requestBasePath) - 1);
    	
    	$assetPathStack = $serviceManager->get('AssetPathStack');
    	$content = $assetPathStack->resolve($requestPath);  	
    	if (!empty($content)) {
    		$response = $e->getResponse();
    		$headers  = $response->getHeaders();
    		$headers->addHeaderLine('Content-Type', MimeResolver::getMimeType($requestPath));
    		$response->setContent($content);
    		return $response;
    	}
    	
    }
913331
public function dispatchEvent(MvcEvent $event)
    {
        /**
         * Don't do anything for assets
         */
        $matchRoute = $event->getRouteMatch();
        if (empty($matchRoute)) {
            return null;
        }

        /** @var \Rcm\EventListener\DispatchListener $dispatchListener */
        $dispatchListener
            = $this->serviceLocator->get(\Rcm\EventListener\DispatchListener::class);

        $return = $dispatchListener->setSiteLayout($event);

        if (!empty($return)) {
            return $return;
        }

        return null;
    }
446593
public function onDispatch(MvcEvent $event)
    {
        /* @var $service \BjyAuthorize\Service\Authorize */
        $service    = $this->serviceLocator->get('BjyAuthorize\Service\Authorize');
        $match      = $event->getRouteMatch();
        $controller = $match->getParam('controller');
        $action     = $match->getParam('action');
        $request    = $event->getRequest();
        $method     = $request instanceof HttpRequest ? strtolower($request->getMethod()) : null;

        $authorized = $service->isAllowed($this->getResourceName($controller))
            || $service->isAllowed($this->getResourceName($controller, $action))
            || ($method && $service->isAllowed($this->getResourceName($controller, $method)));

        if ($authorized) {
            return;
        }

        $event->setError(static::ERROR);
        $event->setParam('identity', $service->getIdentity());
        $event->setParam('controller', $controller);
        $event->setParam('action', $action);

        $errorMessage = sprintf("You are not authorized to access %s:%s", $controller, $action);
        $event->setParam('exception', new UnAuthorizedException($errorMessage));

        /* @var $app \Zend\Mvc\ApplicationInterface */
        $app = $event->getTarget();
        $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
    }
1213928
public function onDispatch(MvcEvent $e)
    {
        $this->routeMatch = $e->getRouteMatch();

        $preResponse = $this->preDispatch($e);

        /** @var MvcEvent $e */

        if ($preResponse !== null) {
            $e->setResult($preResponse);

            return $preResponse;
        }

        $actionResponse = parent::onDispatch($e);

        $e->setResult($actionResponse);

        $postResponse = $this->postDispatch($e);

        if ($postResponse !== null) {
            /** @var MvcEvent $e */
            $e->setResult($postResponse);
        }

        return $e->getResult();
    }
394213
public function init(MvcEvent $e)
    {
        $request = $e->getRequest();
        if (!$request instanceof Request) {
            return;
        }

        $sem = $e->getApplication()->getEventManager()->getSharedManager();
        $sem->attach('UploadableManager', 'createFile', [$this, 'onCreateFile']);
    }
361804
public function setUseCapture(MvcEvent $e)
    {
        if (!$e->getRequest() instanceof HttpRequest || !($options = $e->getParam('module-options'))) {
            return;
        }

        if ($options instanceof FormOptionsInterface && null === $options->getUseCaptcha()) {
            $authService = $e->getApplication()->getServiceManager()
                ->get(AuthenticationServiceInterface::class);
            $options->setUseCaptcha(!$authService->hasIdentity());
        }
    }
1050611
public function onRequestBeforeSend(Event $event)
    {
        if (!strlen($this->config['access_token'])) {
          return;
        }

        switch ($this->config['authorize_location']) {
          case 'query':
            $event['request']->getQuery()->set(
              $this->config['query_param_key'],
              $this->config['access_token']
            );
            break;

          default:
            $authorizationParams = array(
                'access_token'     => $this->config['access_token'],
                'token_type'       => $this->config['token_type'],
            );

            $event['request']->setHeader(
                'Authorization',
                $this->buildAuthorizationHeader($authorizationParams)
            );
            break;
        }
    }
304213
public function routeEvent(MvcEvent $event)
    {
        $this->doLogout($event);

        /** @var \Rcm\EventListener\RouteListener $routeListener */
        $routeListener = $this->serviceLocator->get(
            \Rcm\EventListener\RouteListener::class
        );

        $return = $routeListener->checkRedirect($event);

        if (!empty($return)) {
            return $return;
        }

        $return = $routeListener->checkDomain($event);

        if (!empty($return)) {
            return $return;
        }

        $return = $routeListener->addLocale($event);

        if (!empty($return)) {
            return $return;
        }

        return null;
    }
664223
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 (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);
    }
370372
public function routeLoad(MvcEvent $event)
    {
        $request = $event->getRequest();
        if(!(
            $request instanceof HttpRequest &&
            $request->isGet() &&
            $request->getQuery()->count() == 0
        )) {
            // We do not cache route match for requests that can produce
            // different match.
            return;
        }

        $event->setParam('route-cacheable', true);

        // check if we have data in our cache
        $path = $request->getUri()->getPath();

        $services = $event->getApplication()->getServiceManager();

        $cacheName = $services->get(RouterCacheOptions::class)->getCache();
        $cache = $services->get($cacheName);

        $cacheKey = $this->getCacheKey($path);
        $cachedData = $cache->getItem($cacheKey);

        if($cachedData) {
            $event->setParam('route-cached', true);
            $router = $event->getRouter();
            $router->addRoute($cachedData['name'], $cachedData['spec'], round(PHP_INT_MAX/2));
        }
    }
1053781
public function onKernelRequest(GetResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        if (!$this->csrfTokenManager instanceof CsrfTokenManagerInterface) {
            return;
        }

        $request = $event->getRequest();

        if ($request->isMethodCacheable()) {
            return;
        }

        if ($request->attributes->get('_route') !== $this->routeName) {
            return;
        }

        $session = $event->getRequest()->getSession();
        if (!$session->isStarted()) {
            return;
        }

        if ($request->headers->get('X-CSRF-Token') !== null) {
            return;
        }

        $csrfToken = $this->csrfTokenManager->getToken($this->csrfTokenId)->getValue();

        $request->headers->set('X-CSRF-Token', $csrfToken);
    }
122554
public function routeSave(MvcEvent $event)
    {
        $match = $event->getRouteMatch();
        if(!$match) {
            return;
        }
    
        if($event->getParam('route-cached') || !$event->getParam('route-cacheable')) {
            return;
        }
    
        $path = $event->getRequest()
                      ->getUri()
                      ->getPath();
    
        // save the route match into the cache.
        $cache = $event->getApplication()->getServiceManager()->get('var-cache');
        $cacheKey = $this->getCacheKey($path);
        $data = array (
            'name'  => $event->getRouteMatch()->getMatchedRouteName(),
            'route' => $path,
            'defaults' => $event->getRouteMatch()->getParams(),
        );
        $cache->setItem($cacheKey, $data);
    }
811790
public function onDispatchError( MvcEvent $event )
    {
        /* @var $exception \Exception  */
        $exception = $event->getParam( 'exception' );

        if ( $exception && $exception instanceof Exception )
        {
            $this->exceptionHandler( $exception, false );
        }

        if ( $this->response )
        {
            $event->stopPropagation();
            return $this->response;
        }
    }