/*
Joomla Compatibility

For Joomla 3.x : Re-run the routing and add returned keys to the $_GET request. This is done because Joomla 3
sets the results of the router in $_REQUEST and not in $_GET
555923
public function onAfterApplicationRoute(KEventInterface $event)
    {
        $request = $this->getObject('request');

        $app = JFactory::getApplication();
        if ($app->isSite())
        {
            $uri     = clone JURI::getInstance();

            $router = JFactory::getApplication()->getRouter();
            $result = $router->parse($uri);

            foreach ($result as $key => $value)
            {
                if (!$request->query->has($key)) {
                    $request->query->set($key, $value);
                }
            }
        }

        if ($request->query->has('limitstart')) {
            $request->query->offset = $request->query->limitstart;
        }
    }
990527
public function __doRequest($request, $location, $action, $version, $oneWay = 0)
    {
        $aFind = [':ns1', 'ns1:', "\n", "\r"];
        $sReplace = '';
        $newrequest = str_replace($aFind, $sReplace, $request);

        return parent::__doRequest($newrequest, $location, $action, $version, $oneWay);
    }
437432
protected function rewriteRoutingSetUpCurrentRouteByRequest () {
		$request = & $this->request;
		$toolClass = self::$toolClass;
		$this->currentRoute
			->SetController(str_replace(['/', '\\\\'], ['\\', '//'],
				$toolClass::GetPascalCaseFromDashed($request->GetControllerName())
			))
			->SetAction(
				$toolClass::GetPascalCaseFromDashed($request->GetActionName())
			);
	}
1345679
public function indexAction()
    {
        /* @todo: move this into a listener.
         *
         * The following lines allow to override get param[q] with the
         * param from route. This feature is needed for a landing-page feature, where
         * human readable urls like http://yawik.org/demo/de/jobs/sales.html
         *
         * move the Logic into a Listener, which can be activated, if needed
         */
        $request = $this->getRequest();
        $getParams = $request->getQuery();
        $routeParams = $this->params()->fromRoute();
        if (isset($routeParams['q']) && !isset($getParams['q'])) {
            $getParams['q']=$routeParams['q'];
        }

        $result = $this->pagination([
                'params' => ['Jobs_Board', [
                    'q',
                    'count' => $this->options['count'],
                    'page' => 1,
                    'l',
                    'd' => 10]
                ],
                'form' => ['as' => 'filterForm', 'Jobs/JobboardSearch'],
                'paginator' => ['as' => 'jobs', 'Jobs/Board']
            ]);

        $organizationImageCache = $this->imageFileCacheManager;

        $result['organizationImageCache'] = $organizationImageCache;

        return new ViewModel($result);
    }
414485
public static function route(Http\Request $request)
    {
        $path = $request->REQUEST_URI;
        $key = $request->getMethod().'@'.$path;
        $keyAny = 'ANY@'.$path;

        $matchedRoute = null;
        $matchedScore = 0;

        if (isset(self::$routes[$key])) {
            $matchedRoute = self::$routes[$key];
        } elseif (isset(self::$routes[$keyAny])) {
            $matchedRoute = self::$routes[$keyAny];
        } else {
            foreach (self::$routes as $key2 => $route) {
                if ($route->getMethod() != 'ANY' && $route->getMethod() != $request->getMethod()) {
                    continue;
                }

                $score = $route->getScore($path, $request->getMethod());
                if ($score > $matchedScore) {
                    $matchedRoute = $route;
                    $matchedScore = $score;
                }
            }
        }

        if ($matchedRoute) {
            $matchedRoute->setUrl($path);
        } elseif (self::$_404route) {
            $matchedRoute = self::$_404route;
        } else {
            throw new Exceptions\RouteException('Route not found');
        }
        return $matchedRoute;
    }
694490
public function send()
    {
        if (php_sapi_name() == 'cli') {
            return true;
        }

        // We add of the X-Powered-By header when disable_x_powered_by is true
        if (!$this->disable_x_powered_by) {
            $this->response->addHeader('X-Powered-By', 'Bow Framework');
        }

        $this->prefix = '';

        $method = $this->request->method();

        // We verify the existence of a special method DELETE, PUT
        if ($method == 'POST') {
            if ($this->special_method !== null) {
                $method = $this->special_method;
            }
        }

        // We verify the existence of the method of the request in
        // the routing collection
        if (!isset($this->routes[$method])) {
            // We verify and call function associate by 404 code
            $this->response->status(404);

            if (empty($this->error_code)) {
                $this->response->send(
                    sprintf('Cannot %s %s 404', $method, $this->request->path())
                );
            }

            return false;
        }

        $response = null;

        $error = true;

        foreach ($this->routes[$method] as $key => $route) {
            // The route must be an instance of Route
            if (!($route instanceof Route)) {
                continue;
            }

            // We launch the search of the method that arrived in the query
             // then start checking the url of the request
            if (!$route->match($this->request->path())) {
                continue;
            }

            $this->current['path'] = $route->getPath();

            // We call the action associate with the route
            $response = $route->call();
            $error = false;

            break;
        }

        // Error management
        if (!$error) {
            return $this->sendResponse($response);
        }

        // We apply the 404 error code
        $this->response->status(404);

        if (array_key_exists(404, $this->error_code)) {
            $response = Actionner::execute($this->error_code[404], []);

            return $this->sendResponse($response);
        }

        if (is_string($this->config['view.404'])) {
            $response = $this->response->render($this->config['view.404']);

            return $this->sendResponse($response);
        }

        throw new RouterException(
            sprintf('La route "%s" n\'existe pas', $this->request->path()),
            E_ERROR
        );
    }
1010014
protected function runRoute()
  {
    # Get Method and URI
    $httpMethod = $this->getRequest()->getMethod();
    $path = $this->getRequest()->getUri()->getPath();
    $routeInfo = null;
    $response = null;

    # Find route match in groups
    foreach ($this->getRouteGroups() as $routeGroup)
    {
      # Match the METHOD and URI to the routes in this group
      $routeInfo = $routeGroup->matchRoute($httpMethod,$path);

      if ( \count($routeInfo)>0 ) {
        # Debug log
        $this->getLogger()->debug('Route matched ',['path'=>$path,'handler'=>$routeInfo['handler']]);

        # Run Before Hooks
        // $ok = $this->runHooks('OnBeforeRequest');

        $beforeResult = true; // assume all before handlers succeed
        $routeResult = false;
        $afterResult = true; // assume all after handlers succeed

        #
        # Run the Common AND Groups Before Middlewares (ServerRequestInterface)
        #
        $beforeMiddleware = \array_merge($this->beforeMiddleware, $routeGroup->getBeforeMiddleware());

        foreach ($beforeMiddleware as $middleware)
        {
          if (\class_exists($middleware) ) {
            $beforeHandler = new $middleware($routeInfo['args']);

            # Debug log
            $this->getLogger()->debug('Initialize Before middleware',['rid'=>container('requestId'),'middleware'=>$middleware]);

            # Initialize
            $beforeHandler->initialize($routeInfo['args']);

            # Debug log
            $this->getLogger()->debug('Running Before middleware',['rid'=>container('requestId'),'middleware'=>$middleware]);

            if (!$beforeHandler->handle($routeInfo['args'])) {
              # Record outcome
              $beforeResult = false;

              # Stop processing more middleware
              break;
            }
          } else {
            # Log
            $this->getLogger()->warning('Before Middleware not found',['rid'=>container('requestId'),'middleware'=>$middleware]);
          }
        }

        #
        # Create & Run the Controller Class - If the Before Middlewares where ok!
        #
        if ($beforeResult) {
          # Extract class & method
          $arr = \explode('@',$routeInfo['handler']);
          $handlerClass = $arr[0];
          $handlerMethod = ($arr[1] ?? 'handle');

          # Check existance of handler class
          if (\class_exists($handlerClass))
          {
            # Create the class
            $routeHandler = new $handlerClass( $routeInfo['args'] );

            # Check method existance
            if ($routeHandler && \method_exists($routeHandler,'initialize') && \method_exists($routeHandler,$handlerMethod))
            {
              # Debug log
              $this->getLogger()->debug('Running controller->initialize()',[
                'rid' => \container('requestId'),
                'controller'=>$handlerClass
              ]);

              # Initialize
              $routeHandler->initialize($routeInfo['args']);

              # Debug log
              $this->getLogger()->debug('Running controller->handle()',[
                'rid' => \container('requestId'),
                'method'=>$handlerMethod
              ]);

              # Run Controller's method
              $response = $routeHandler->$handlerMethod($routeInfo['args']);

              # Set it
              if ($response)
                $this->setResponse($response);

            } else {
              # Log
              $this->getLogger()->error('Method not found in controller ',[
                'rid' => \container('requestId'),
                'controller'=>$handlerClass,
                'method'=>$handlerMethod
              ]);
            }

          } else {
            # Debug log
            $this->getLogger()->error('Controller not found ',[
              'rid' => \container('requestId'),
              'controller'=>$handlerClass
            ]);

            # Attempt to run the 404 error controller (if set by user in config)
            $this->runErrorController('',404);
          }
        }

        #
        # Run the After Middlewares (ServerRequestInterface)
        #
        $afterMiddleware = \array_merge($this->afterMiddleware,$routeGroup->getAfterMiddleware());
        foreach ($afterMiddleware as $middleware)
        {
          if (\class_exists($middleware) ) {
            $afterHandler = new $middleware($routeInfo['args']);

            # Debug log
            $this->getLogger()->debug('Initialize After middleware',[
              'rid' => \container('requestId'),
              'middleware'=>$middleware
            ]);

            # Initialize
            $afterHandler->initialize($routeInfo['args']);

            # Debug log
            $this->getLogger()->debug('Running After middleware',[
              'rid' => \container('requestId'),
              'middleware'=>$middleware
            ]);

            if (!$afterHandler->handle($routeInfo['args'])) {

              return false;
            }

          } else {
            # Log
            $this->getLogger()->warning('After Middleware not found',[
              'rid' => \container('requestId'),
              'middleware'=>$middleware
            ]);
          }
        }

        # Run After Hooks
        // $ok = $this->runHooks('OnAfterRequest');

        # Return the generated response
        return $this->getResponse();

      } // if count() ...

    } // foreach routeGroup

    ##
    ## No route matched the request ?!
    ##
    $this->getLogger()->notice('No route matched the request',[
      'method' => $this->getRequest()->getMethod(),
      'path' => $path,
      'ip' => \getClientIp(),
    ]);

    ##
    ## Try to load the "errors" controllers in the routes-{env}.json file
    ## and run the appropriate HTTP Code controller. If not found
    #W we will try to load the 4xx or 5xx generic controller (if defined)
    ##

    return $this->runErrorController('', 404);
  }
980911
public function init()
    {
        $request =& $this->request;
        $route = '/:controller/:action';
        $opts = array('controller' => 'Home', 'action' => 'index');

        // Inlined as a closure to fix "using $this when not in object context" on 5.3
        $validateSession = function () {
            if (!empty($_SESSION['phpci_user_id'])) {
                $user = b8\Store\Factory::getStore('User')->getByPrimaryKey($_SESSION['phpci_user_id']);

                if ($user) {
                    $_SESSION['phpci_user'] = $user;
                    return true;
                }

                unset($_SESSION['phpci_user_id']);
            }

            return false;
        };

        $skipAuth = array($this, 'shouldSkipAuth');

        // Handler for the route we're about to register, checks for a valid session where necessary:
        $routeHandler = function (&$route, Response &$response) use (&$request, $validateSession, $skipAuth) {
            $skipValidation = in_array($route['controller'], array('session', 'webhook', 'build-status'));

            if (!$skipValidation && !$validateSession() && (!is_callable($skipAuth) || !$skipAuth())) {
                if ($request->isAjax()) {
                    $response->setResponseCode(401);
                    $response->setContent('');
                } else {
                    $_SESSION['phpci_login_redirect'] = substr($request->getPath(), 1);
                    $response = new RedirectResponse($response);
                    $response->setHeader('Location', PHPCI_URL.'session/login');
                }

                return false;
            }

            return true;
        };

        $this->router->clearRoutes();
        $this->router->register($route, $opts, $routeHandler);
    }
441433
protected function processRoute(): bool
    {
        $uri = $this->getCleanUri();
        $uri = trim($uri, '/');
        $raw = explode('/', $uri);

        // rewrite module from request
        if (\count($raw)) {
            $this->setParam('_module', array_shift($raw));
        }
        // rewrite module from controller
        if (\count($raw)) {
            $this->setParam('_controller', array_shift($raw));
        }
        if ($size = \count($raw)) {
            // save raw
            $this->rawParams = $raw;

            // save as index params
            foreach ($raw as $i => $value) {
                $this->setParam($i, $value);
            }

            // remove tail
            if ($size % 2 === 1) {
                array_pop($raw);
                $size = \count($raw);
            }
            // or use array_chunk and run another loop?
            for ($i = 0; $i < $size; $i += 2) {
                $this->setParam($raw[$i], $raw[$i + 1]);
            }
        }
        return true;
    }
625961
public function getRoute($url = '', $fqr = true)
    {
        if (!is_array($url)) {
            if (strpos($url, 'http') === 0) {
                return $url;
            }

            if (strpos($url, '/') === 0) {
                return route($url);
            }

            $url = str_replace('index.php?', '', trim($url));
            $vars = array();
            parse_str($url, $vars);
            $url = $vars;
        }

        $parts = array();

        if (!isset($url['option'])) {
            $parts['option'] = AnRequest::get('get.option', 'cmd');
        }

        //if not view is set the set
        if (!isset($url['view'])) {
            $parts['view'] = AnRequest::get('get.view', 'cmd');

            //only try to set the layout if we are setting the view
            if (!isset($url['layout']) && AnRequest::has('get.layout')) {
                $parts['layout'] = AnRequest::get('get.layout', 'cmd');
            }
        }

        //carry format
        if (!isset($url['format']) && AnRequest::has('get.format')) {
            $parts['format'] = AnRequest::get('get.format', 'cmd');
        }

        foreach ($parts as $key => $value) {
            $url[$key] = $value;
        }

        //unset html format since it's a default
        if (isset($url['format']) && $url['format'] == 'html') {
            unset($url['format']);
        }

        //unset default lyout since it's a default
        if (isset($url['layout']) && $url['layout'] == 'default') {
            unset($url['layout']);
        }

        $parts = 'index.php?'.http_build_query($url);
        
        $route = $this->getService('application')->getRouter()->build($parts, $fqr);

        return $route;
    }
1282923
public function dispatch($request, $ignore_qs = false){
    if(strpos($request,'#') !== false){
      $request = substr($request, 0, strpos($request,'#')); //no fragments.
    }
  	if($ignore_qs && strpos($request, '?') !== false){
  		$request = substr($request, 0, strpos($request,'?')); //no QS
  	}
    if($this->router === null){
      throw new BadMethodCallException("You are missing a router. Set a router");
    }
    $bindings = $this->router->toArray();
    $routes = array_keys($bindings);
    $lot_size = ((int)self::$ROUTES_PER_LOT) > 0? ((int)self::$ROUTES_PER_LOT) : 35;
    $chunks = array_chunk($routes, $lot_size);
    foreach($chunks as $pack){
      $as_one_regex = self::asJoinedRegex($pack);

      preg_match_all($as_one_regex, $request, $one_regex);
      $matched = self::clearNonMatched($one_regex);
      $compiled = self::compileFound($pack, $matched);
      $bound_key = key($compiled);
      if($bound_key === null){
        continue;
      }
      $bound = $bindings[$bound_key];

      $vars = array_pop($compiled);
      $request_object = ((object) $vars);
      if($bound_key !== null){
        return call_user_func($bound, $request_object);
      }
    }
    return $this->fail($request);
  }
512763
function callHook() {
		global $default; // Should take care of this later.
		$queryString = array();

		if (!isset($this->url)) {

			$controller = $this->routes['default']['controller'];
			$action = $this->routes['default']['action'];
		} else {
			//print "URL: " . $this->url . "<br>";
			$this->routeURL(); // Replace the URL with something else based on preg_matches defined in the routing
			//print "URL: " . $this->url . "<br>";
			$urlArray = array();
			$urlArray = explode("/",$this->url);
			$controller = $urlArray[0];
			array_shift($urlArray); // Pop the first element
			if (!$controller){
				$controller="index";  // Default Controller
			}

			if (isset($urlArray[0])) {
				$action = $urlArray[0];
				array_shift($urlArray); // pop the second element
			} else {
				$action = 'index'; // Default Action
			}
			$queryString = $urlArray;
		}

		$controllerName = ucfirst($controller).'Controller';
		//print "Calling $controllerName with $controller and $action at ";
		$this->runControllerAction($controller, $action, $queryString, $controllerName, $action);

	}
266752
public function route(Request $request) : Response
    {
        $method = $request->getMethod();

        /** @var ParsedRoute $route */
        foreach ($this->routeCollection->get($method) as $route) {
            $compiledRoute = $this->compiler->compile($route, $request);

            if ($compiledRoute->isMatch()) {
                $this->matchedRoute = $compiledRoute;

                return $this->dispatcher->dispatch($this->matchedRoute, $request, $this->matchedController);
            }
        }

        // If we've gotten here, we've got a missing route
        throw new HttpException(404);
    }
281913
public function run(Request $request) {
		$prefs = $this->getServiceContainer()->getPreferenceLoader()->getSystemPreferences();
		$translator = $this->getServiceContainer()->getTranslator();
		$reg = $this->getServiceContainer()->getExtensionRegistry();
		$settings = $reg->getExtensions(AccountModule::EXT_SETTINGS);
		$section = $this->getParam('section');
		$routes = [];

		// build settings routes
		foreach ($settings as $ext) {
			$routes[$translator->trans($ext['slug'])] = $ext;
		}
			
		if (!isset($routes[$section])) {
			$url = $prefs->getAccountUrl() . $translator->trans('slug.settings');
			throw new ResourceNotFoundException(sprintf('No route found for %s/%s', $url, $section));
		}
			
		$ext = $routes[$section];
		$kernel = $this->getServiceContainer()->getKernel();
		$module = $this->getServiceContainer()->getModuleManager()->load($ext['module']);
		$action = $module->loadAction($ext['action'], 'html');
		$response = $kernel->handle($action, $request);
		
		if ($response instanceof RedirectResponse) {
			return $response;
		}
		
		return $this->responder->run($request, new Blank([
			'settings' => $settings, 
			'section' => $response->getContent()
		]));
	}
707485
protected function setAfterSendRoute()
    {
        if ($this->routeAction && ($this->request->getActionName() !== $this->routeAction)) {
            $this->afterSendRouteUrl = array('action' => $this->routeAction);

            $keys  = $this->model->getKeys();
            if (count($keys) == 1) {
                $key = reset($keys);
                if (isset($this->formData[$key])) {
                    $this->afterSendRouteUrl[\MUtil_Model::REQUEST_ID] = $this->formData[$key];
                }
            } else {
                $i = 1;
                foreach ($keys as $key) {
                    if (isset($this->formData[$key])) {
                        $this->afterSendRouteUrl[\MUtil_Model::REQUEST_ID . $i] = $this->formData[$key];
                    }
                    $i++;
                }
            }

            $this->afterSendRouteUrl['controller'] = $this->request->getControllerName();

            $find['action'] = $this->afterSendRouteUrl['action'];
            $find['controller'] = $this->afterSendRouteUrl['controller'];

            if (null == $this->menu->find($find)) {
                $this->afterSendRouteUrl['action'] = 'index';
                $this->resetRoute = true;
            }
        }
    }
841815
protected function getRoute(
        ResultInterface $result,
        /*# string */ $routeKey,
        array $matches
    )/*# : bool */ {
        $request = $result->getRequest();
        $method  = $request->getHttpMethod();

        // matched but method not allowed
        if (!isset($this->routes[$routeKey][$method])) {
            $result->setStatus(Status::METHOD_NOT_ALLOWED);
            return false;
        }

        // get the route
        $route = $this->routes[$routeKey][$method];

        // apply others filters
        if (!$this->filtering($route, $request)) {
            $status = Status::PRECONDITION_FAILED;
            $result->setStatus($status)
                   ->setHandler($route->getHandler($status));
            return false;
        }

        // remember the route
        $result->setRoute($route);

        // set result's parameters
        $result->setParameter(array_replace($route->getDefault(), $matches));

        // set status & handler
        $status = Status::OK;
        $result->setStatus($status)
               ->setHandler($route->getHandler(Status::OK));

        return true;
    }
1084124
public function parse_request() {

    $self = $this;

    $request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
    $dispatcher = \FastRoute\simpleDispatcher(function($r) use ($self) {
      foreach($self->routes as $route) {
        $r->addRoute($route['methods'], $route['route'], $route['callback'], $route['id']);
      }
    }, [
      'routeCollector' => '\Ampersand\\Collector',
    ]);

    // Fetch method and URI from somewhere
    $httpMethod = $_SERVER['REQUEST_METHOD'];
    $uri = $request->getRequestUri();

    // Strip query string (?foo=bar) and decode URI
    if (false !== $pos = strpos($uri, '?')) {
        $uri = substr($uri, 0, $pos);
    }
    $uri = rawurldecode($uri);

    if(strpos($uri, '/wp-admin') > -1) return;

    if($uri == '/404' || $uri == '/404/')
      http_response_code(404);

    $routeInfo = $dispatcher->dispatch($httpMethod, $uri);
    switch ($routeInfo[0]) {
      case \FastRoute\Dispatcher::NOT_FOUND:
        if($uri != '/404' && $uri != '/404/') {
          header("HTTP/1.0 404 Not Found");
          header('Location: '.$this->base.'/404');
          die();
        }
        break;
      case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        $allowedMethods = $routeInfo[1];
        // ... 405 Method Not Allowed
        break;
      case \FastRoute\Dispatcher::FOUND:
        $handler = $routeInfo[1];
        $vars = $routeInfo[2];
        $this->getCallback($handler[1], $handler[0], $vars);
        break;
    }

    Bootstrap::getInstance()->run();
    $this->end();

  }