Handles redirects in case of dispatch errors caused by unauthorized access

@param \Zend\Mvc\MvcEvent $event
181236
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;
        }

        $routeName       = $routeMatch->getMatchedRouteName();
        $areaName        = (strpos($routeName, '/'))?substr($routeName, 0, strpos($routeName, '/')):$routeName;
        $areaName        = ($areaName === 'frontend' || $areaName === 'admin')? $areaName : 'frontend';

        if (null === $url) {
            if ($areaName === 'admin') {
                $url = $router->assemble(array(), array('name' => $this->redirectAdminRoute));
            } else {
                $url = $router->assemble($this->redirectRouteArray, array('name' => $this->redirectRoute));
            }
        }

        $response = $response ?: new Response();

        $response->getHeaders()->addHeaderLine('Location', $url);
        $response->setStatusCode(302);
        $response->sendHeaders();
        $event->stopPropagation();
        $event->setResponse($response);
    }
1268318
public function onDispatch(MvcEvent $e)
    {
        if (!$e->getRequest() instanceof HttpRequest) {
            return;
        }

        $sem = $e->getApplication()->getEventManager()->getSharedManager();
        $sem->attach('UploadableManager', 'createFile', [$this, 'onCreateFile']);
    }
814291
public function handle($event)
    {
        $guard = null;

        // We'll retrieve the auth guard if available.
        if (property_exists($event, 'guard')) {
            $guard = $event->guard;
        }

        // Before we bind the users LDAP model, we will verify they are using
        // the Adldap authentication provider, and the required trait.
        if ($this->isUsingAdldapProvider($guard) && $this->canBind($event->user)) {
            $event->user->setLdapUser(
                Resolver::byModel($event->user)
            );
        }
    }
215453
public function handleXmlHttpRequest(MvcEvent $event)
	{
		$request = $event->getRequest();
		if ($request->isXMLHttpRequest()) {
			$dispatchResult = $event->getResult();
			if ($dispatchResult instanceof ViewModel) {
				$dispatchResult->setTerminal(true);
			}
		}
	}
439725
public function beforeRedirect(Event $event)
    {
        $subject = $event->getSubject();

        $redirects = $this->_action()->redirectConfig();
        if (empty($redirects)) {
            return;
        }

        foreach ($redirects as $redirect) {
            if (!$this->_getKey($subject, $redirect['reader'], $redirect['key'])) {
                continue;
            }

            $subject->url = $this->_getUrl($subject, $redirect['url']);
            break;
        }
    }
553664
public function onDispatch( MvcEvent $event )
    {
        $this->paragraphId = (int) $this->params()
                                        ->fromRoute( 'paragraphId' );

        if ( empty( $this->paragraphId ) )
        {
            $this->paragraphId = null;
        }

        return parent::onDispatch( $event );
    }
704998
public function onBootstrap(MvcEvent $event)
    {
        $sharedEventManager = $event->getApplication()->getEventManager()->getSharedManager();
        $sharedEventManager->attach(
            AbstractActionController::class,
            MvcEvent::EVENT_DISPATCH,
            [$this, 'onDispatchedListener'],
            self::DISPATCH_PRIORITY
        );
    }
1196949
public function checkRedirect(MvcEvent $event)
    {
        if ($this->isConsoleRequest()) {
            return null;
        }

        // User defaults
        $redirectUrl = $this->redirectService->getRedirectUrl();

        if (empty($redirectUrl)) {
            return null;
        }


        $queryParams = $event->getRequest()->getQuery()->toArray();

        header(
            'Location: ' . $redirectUrl . (count($queryParams) ? '?' . http_build_query($queryParams) : null),
            true,
            302
        );
        exit;

        /* Below is the ZF2 way but Response is not short-circuiting the event like it should *
        $response = new Response();
        $response->setStatusCode(302);
        $response->getHeaders()
            ->addHeaderLine(
                'Location',
                $redirect->getRedirectUrl()
            );
        $event->stopPropagation(true);

        return $response;
        */
    }
921818
public function onDispatchError(MvcEvent $e)
    {
        $ex = $e->getParam('exception');
        $model = $e->getResult();

        if ($model instanceof ViewModel
            && Application::ERROR_EXCEPTION == $e->getError()
            && 0 === strpos($ex->getMessage(), 'Your application id and secret')
        ) {
            $model->setTemplate('auth/error/social-profiles-unconfigured');
        }
    }
263233
public static function beforeActionAccess($event)
    {
        $controller = $event->sender;
        $permissionName = AuthItem::createPermissionName([$controller->module->id, $controller->id, $controller->action->id]);
        if (!AuthItem::checkAccess($permissionName, Yii::$app->user)) {
            throw new HttpException(403, Yii::t('modules/rbac', 'Access denied'));
        }
    }
180250
public function onPreRoute(MvcEvent $event)
    {
    	// Get the router object
    	$serviceManager = $event->getApplication()->getServiceManager();
    	$router         = $event->getRouter();
    	
    	// Load the route configuration
    	$config = $serviceManager->get('Config');
	    $config = isset($config['asset_manager']) && (is_array($config['asset_manager']) || $config['asset_manager'] instanceof ArrayAccess)
	              ? $config['asset_manager']
	              : array();
	    $config = isset($config['routes']) && (is_array($config['routes']) || $config['routes'] instanceof ArrayAccess)
	              ? $config['routes']
	              : array();
	    
	    // There can be special routes defined:
	    //    /css
	    //    /js
	    //    ...
	    // This way the asset manager can be hidden
	    if (!empty($config)) {
	    	// Rename all routes so I get an easy base route 
	    	// name called 'asset_manager'
		    $keys   = array_keys($config);
		    array_walk($keys, function($n) {
		    	$n = 'asset_manager/' . $n;
		    });
		    $config = array_combine($keys, array_values($config));
		    
		    // Add the routes
    		$router->addRoutes($config);
	    } else {
	    	// No routes have been configured!
	    	// So I need to create my own
	    	$router->addRoute(
    			'asset_manager',
	    		array(
	    			'type' => 'Zend\Mvc\Router\Http\Literal',
	                'options' => array(
	                    'route'    => '/assets',
	                ),
	                'may_terminate' => true,
	                'child_routes' => array(
	                	'default' => array(
	                		'type' => 'Wildcard'
	                	)
	                )
	    		)
	    	);
	    }
    }
377180
public function storeRoute(MvcEvent $event)
    {
        if ($this->ignore) {
            return;
        }
        
        $request = $event->getRequest();
        if ($request->isXmlHttpRequest()) {
            return;
        }
        
        $appConfig = $event->getApplication()
            ->getServiceManager()
            ->get('config');
        $config = array_key_exists(self::CONFIG_KEY, $appConfig) ? $appConfig[self::CONFIG_KEY] : array();
        if (array_key_exists('blacklist', $config)) {
            $this->setBlacklist($config['blacklist']);
        }
        
        $routeMatch = $event->getRouteMatch();
        if (null === $routeMatch ||
             in_array($routeMatch->getMatchedRouteName(), $this->blacklist)) {
            return;
        }
        
        $this->getSession()->route = $routeMatch;
    }
1065586
public function handlePersistRoute(PublishEvent $event)
    {
        /** @var ResourceSegmentBehavior $document */
        $document = $event->getDocument();

        if (!$this->supports($document)) {
            return;
        }

        if (!$event->getLocale()) {
            return;
        }

        if ($document instanceof HomeDocument) {
            return;
        }

        if ($document instanceof RedirectTypeBehavior && RedirectType::NONE !== $document->getRedirectType()) {
            return;
        }

        $this->persistRoute($document);
    }
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);
    }
434527
public function dispatchEvent($event, ...$arguments)
    {
        $this->dispatchEventToEventCallbacks($event, $arguments);

        $this->dispatchEventToEventHandler($event, $arguments);
    }
555403
public function cleanupRequest(Event $event)
    {
        $params = $event['request']->getParams();
        unset($params[self::REDIRECT_COUNT]);
        unset($params[self::PARENT_REQUEST]);
    }
93272
public function checkDomain(MvcEvent $event)
    {
        if ($this->isConsoleRequest()) {
            return null;
        }

        $currentDomain = $this->siteService->getCurrentDomain();

        $site = $this->siteService->getCurrentSite($currentDomain);

        $redirectUrl = $this->domainRedirectService->getSiteNotAvailableRedirectUrl($site);

        if (!$site->isSiteAvailable() && empty($redirectUrl)) {
            $response = new Response();
            $response->setStatusCode(404);
            $event->stopPropagation(true);

            return $response;
        }

        if ($redirectUrl) {
            $response = new Response();
            $response->setStatusCode(302);
            $response->getHeaders()->addHeaderLine('Location', '//' . $redirectUrl);

            $event->stopPropagation(true);

            return $response;
        }

        $redirectUrl = $this->domainRedirectService->getPrimaryRedirectUrl($site);

        if ($redirectUrl) {
            $response = new Response();
            $response->setStatusCode(302);
            $response->getHeaders()->addHeaderLine('Location', '//' . $redirectUrl);

            $event->stopPropagation(true);

            return $response;
        }

        return null;
    }