Parse the Request Intercept map

@param Environment $env Slim environment
@return void
@throws Exception
961086
private function _parseInterceptMap($env)
    {
        // Set up authN/authZ if an URL mapping was given.
        if (isset($env['auth.interceptUrlMap']) && is_array($env['auth.interceptUrlMap'])) {
            // We may need to modify the intercept map, so make a copy of it
            $interceptMap = $env['auth.interceptUrlMap'];

            // Always allow HEAD requests unless the user specifically blocked them
            if (!array_key_exists('HEAD', $interceptMap)) {
                $interceptMap['HEAD'] = ['/**' => ['authN' => 'permitAll', 'authZ' => 'permitAll']];
            }

            // If the request method is not in the Intercept Map, throw an exception
            if (!array_key_exists($env['REQUEST_METHOD'], $interceptMap)) {
                throw new \Exception(
                    "Request Type: " . $env['REQUEST_METHOD'] . " does not exist in Auth Intercept Map"
                );
            }

            $antPathMatcher = new AntPathMatcher();
            foreach ($interceptMap[$env['REQUEST_METHOD']] as $pattern => $auth_array) {
                // Break out of the foreach loop if this URL matches the pattern.
                if ($antPathMatcher->match($pattern, $env['PATH_INFO'])) {
                    $this->authN_type = $auth_array['authN'];
                    $this->authZ_roles = $auth_array['authZ'];
                    break;
                }
            }
        }
    }
654613
protected function parseEnv(
        array $envs,
        /*# string */ $path,
        /*# bool */ $overload
    )/*# : array */ {
        foreach ($envs as $key => $val) {
            // source another env file
            if ($this->source_marker === $val) {
                $src = $this->expandPath($this->deReference($key), $path);
                $this->load($src, $overload);

            // set env
            } else {
                $this->setEnv($key, $this->deReference($val), $overload);
            }
        }
        return $this;
    }
1299918
private function _authenticate($env)
    {
        switch (strtolower($this->authN_type)) {

            case 'cas':
                // Use CAS authentication.
                $casAuth = new UsfAuthCAS($env['auth.config.cas']);
                $casAuth->auth();

                //Add the username and attributes to the Slim environment
                $env['principal.name'] = $casAuth->getPrincipal();
                $env['principal.attributes'] = $casAuth->getAttributes();
                $env['principal.entitlements'] = $casAuth->getEntitlements();

                //Authorization check
                if (!$casAuth->isAuthorized($this->authZ_roles)) {
                    $this->_denyAccess();
                }

                break;

            case 'token':
                // Use the USF Token Auth library.
                $tokenAuth = new UsfAuthToken(
                    $env['auth.config.token']['app_id'],
                    $env['auth.config.token']['token_url']
                );

                $tokenAuth->setRequestMethod($env['REQUEST_METHOD']);
                $tokenAuth->setReferrer($env['HTTP_REFERER']);

                // Setup CORS headers
                $cors_config = $this->_corsConfig($env);
                $tokenAuth->setCorsConfig($cors_config);

                //Validate request token
                $tokenAuth->validateRequest($env['HTTP_X_AUTH_TOKEN']);

                //Add the username and attributes to the Slim environment
                $env['principal.name'] = $tokenAuth->getPrincipal();
                $env['principal.attributes'] = $tokenAuth->getAttributes();
                $env['principal.entitlements'] = $tokenAuth->getEntitlements();

                //Authorization check
                if (!$tokenAuth->isAuthorized($this->authZ_roles)) {
                    $this->_denyAccess();
                }

                //Add CORS headers
                $tokenAuth->addCorsHeaders();
                break;

            case 'hmac':
                // HMAC authentication: https://github.com/acquia/http-hmac-spec
                $hmacAuth = new UsfAuthHmac($env['auth.hmac.keyRegistry']);
                if (!empty($env['auth.hmac.timeout'])) {
                    $hmacAuth->setTimeout($env['auth.hmac.timeout']);
                }

                $hmacAuth->setRequestWrapper(new Slim2Request($this->app->request));

                try {
                    $hmacAuth->authenticate();
                } catch (Exception $exception) {
                    throw new Exception(
                        'Resource '.$this->app->request->getResourceUri().' using '.$this->app->request->getMethod().' authentication failed.',
                        401
                    );
                }

                //Add the username to the Slim environment
                $env['principal.name'] = $hmacAuth->getPrincipal();
                break;

            case 'permitall':
                // No authentication - let everyone in.
                break;

            case 'denyall':
                // No authentication - keep everyone out.
                $this->_denyAccess();
                break;

            default:
                throw new Exception("Unknown Authentication type: " . $this->authN_type, 500);
                break;
        }
    }
861019
public function evaluate(EnvironmentInterface $env)
    {
        $qb = $env->queryBuilder;

        $paramTemplate = $env->newParamName();
        $paramValue = $env->newParamName();
        $paramVs = $env->newParamName();

        $rootAliases = $qb->getRootAliases();
        
        $qb->innerJoin($rootAliases[0] . '.valueSet', $paramVs)
            ->innerJoin($paramVs . '.template', $paramTemplate);

        switch ($this->operator) {
            case 'in':
                $qb->andWhere($paramTemplate . '.id IN (:' . $paramValue . ')');
                break;
            case 'notin':
                $qb->andWhere($paramTemplate . '.id NOT IN (:' . $paramValue . ')');
                break;
        }

        $qb->setParameter($paramValue, $this->getRight()->getValue());
    }
460751
private function deleteCache(string $env)
    {
        Output::displayAsSuccess("Hey, I delete cache from $env environment ", "none");
        $this->callDelCreaServer($env);
        if (in_array("--noexit", $this->options["options"])) {
            Output::displayAsEndSuccess("Cache delete for $env environment is successfull.", "none");
        } else {
            Output::displayAsNormal("Cache delete for $env environment is successfull.");
        }
    }
15861
public function getCoreErrors($env = null)
    {
        $env = $env ?: $this->running_env;
        return isset($this->errors[$env]) ? $this->errors[$env] : 0;
    }
727126
public function env($env, $value = null)
    {
        if (! is_array($env)) {
            $env = [$env => $value];
        }

        foreach ($env as $key => $value) {
            $this->env[$key] = $value;
        }

        return $this;
    }
290492
protected function setEnvironment(Application $app, ?string $env = null): void
    {
        $app->detectEnvironment(function () use ($env) {
            return $env ?: env('APP_ENV', 'production');
        });
    }
600099
public function clearActivity(string $env):Renderer
    {
        if (!in_array($env, array("dev", "prod"))) {
            throw new Server500(new \ArrayObject(array("explain" => "Bad environment name $env",
                "solution" => "Environment must be 'dev' or 'prod' ")));
        }
        Server::delete(FEnv::get("framework.logs").strtolower($env).".log", 'file');
        @Server::create(FEnv::get("framework.logs").strtolower($env).".log", 'file');

        return ((new Renderer())->jsonRenderer(array("code" => 200, "msg" => "OK")));
    }
1165679
public function setup($environment = null, $default = 'development')
    {
        if (Configure::read('Environment.setup')) {
            return false;
        }

        $current = $this->currentEnvironment($environment, $default);

        if (!isset($this->environments[$current])) {
            throw new Exception(sprintf('Environment %s does not exist.', $current));
        }

        $config = array_merge(
            $this->environments[$current]['config'],
            ['Environment.name' => $current]
        );
        foreach ($config as $param => $value) {
            Configure::write($param, $value);
        }

        if (is_callable($this->environments[$current]['callable'])) {
            $this->environments[$current]['callable']();
        }

        Configure::write('Environment.setup', true);

        return true;
    }
212513
public function renderBody(&$env, $exception)
    {
        $title   = 'Slimore Application ErrorException';
        $code    = $exception->getCode();
        $message = $exception->getMessage();
        $file    = $exception->getFile();
        $line    = $exception->getLine();
        $type    = get_class($exception);
        $trace   = str_replace(array('#', "\n"), array('<div class="trace-line">#', '</div>'), $exception->getTraceAsString());

        $html = html($title, [
            '<meta http-equiv="X-UA-Compatible" content="IE=edge" />',
            '<meta name="renderer" content="webkit" />',
            '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />',
            style([
                '*{margin:0;padding:0;}',
                'html {font-size: 62.5%;}',
                'html, body {max-width: 100%;width: 100%;}',
                'body {font-size: 1.4rem;font-family: "Microsoft Yahei", Helvetica, Tahoma, STXihei, arial,verdana,sans-serif;background:#fff;color:#555;}',
                'img {border: none;}',
                'pre, pre code {font-family:Consolas, arial,verdana,sans-serif;}',
                '#layout {padding: 6rem;}',
                '#main {margin: 0 auto;line-height: 1.5;}',
                '#main > h1 {font-size: 10rem;margin-bottom: 1rem;}',
                '#main > h3 {margin-bottom: 2rem; font-size: 1.8rem;}',
                '#main > h4 {margin-bottom: 1rem; font-size: 1.8rem;}',
                '#main pre {margin: 1.5rem 0;white-space: pre-wrap;word-wrap: break-word;}',
                '#main > p {white-space: pre-wrap;word-wrap: break-word;line-height: 1.3;margin-bottom: 0.6rem;}',
                '#main > p > strong {width: 7rem;display:inline-block;}',
                '.logo {text-align: left;border-top:1px solid #eee;margin-top: 5rem;padding: 3rem 0 0;color: #ccc;}',
                '.logo > h1 {font-weight: normal;font-size: 5rem;}',
                '.logo img {margin-left: -2rem;}',
                '.trace-line {padding: 0.3rem 0.6rem;margin-left:-0.6rem;-webkit-transition: background-color 300ms ease-out;transition: background-color 300ms ease-out;}',
                '.trace-line:hover {background:#fffccc;}'
            ])
        ], [
            '<div id="layout">',
                '<div id="main">',
                    '<h1>:(</h1>',
                    '<h3>' . $type . '</h3>',
                    '<h4>Details ：</h4>',
                    '<p><strong>Type: </strong> ' . $type . '</p>',
                    '<p><strong>Message: </strong> ' . $message . '</p>',
                    '<p><strong>File: </strong> ' . $file . '</p>',
                    '<p><strong>Line: </strong> ' . $line . '</p>',
                    '<br/>',
                    '<h4>Trace：</h4>',
                    '<pre>' . $trace . '</pre>',
                    '<div class="logo">',
                        '<h1>Slimore</h1>',
                        '<p>The fully (H)MVC framework, based on the Slim PHP Framwork.</p>',
                    '</div>',
                '</div>',
            '</div>'
        ]);

        return $html;
    }
1050934
public function evaluate(EnvironmentInterface $env)
    {
        $qb = $env->queryBuilder;
        
        $value = $env->newParamName();

        $joins = $qb->getDqlPart('join');
        if (!isset($joins[$this->relation])) {
            $qb->leftJoin('a.'.$this->relation, $this->relation);
        }

        switch ($this->operator) {
            case 'equals':
                $qb->andWhere($this->relation.'.'.$this->attribute.' = :'.$value);
                $qb->setParameter($value, $this->getRight()->getValue());
                break;
            case 'notequals':
                $qb->andWhere($this->relation.'.'.$this->attribute.' <> :'.$value);
                $qb->setParameter($value, $this->getRight()->getValue());
                break;
            case 'contains':
                $qb->andWhere($this->relation.'.'.$this->attribute.' LIKE :'.$value);
                $qb->setParameter($value, '%'. $this->getRight()->getValue().'%');
                break;
            case 'greaterthan':
                $qb->andWhere($this->relation.'.'.$this->attribute.' > :'.$value);
                $qb->setParameter($value, $this->getRight()->getValue());
                break;
            case 'lessthan':
                $qb->andWhere($this->relation.'.'.$this->attribute.' < :'.$value);
                $qb->setParameter($value, $this->getRight()->getValue());
                break;
        }
    }
636202
public function is(string $env): bool
    {
        return $this->env === $env || str_starts_with($this->env, "$env.");
    }
120762
public static function createFromEnvironment(Environment $env)
    {
        // Scheme
        $isSecure = $env->get('HTTPS');
        $scheme = (empty($isSecure) || $isSecure === 'off') ? 'http' : 'https';

        // Authority: Username and password
        $username = $env->get('PHP_AUTH_USER', '');
        $password = $env->get('PHP_AUTH_PW', '');

        // Authority: Host and Port
        if ($env->has('HTTP_HOST')) {
            $host = $env->get('HTTP_HOST');
            // set a port default
            $port = null;
        } else {
            $host = $env->get('SERVER_NAME');
            // set a port default
            $port = (int)$env->get('SERVER_PORT', 80);
        }

        if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', $host, $matches)) {
            $host = $matches[1];

            if (isset($matches[2])) {
                $port = (int) substr($matches[2], 1);
            }
        } else {
            $pos = strpos($host, ':');
            if ($pos !== false) {
                $port = (int) substr($host, $pos + 1);
                $host = strstr($host, ':', true);
            }
        }

        // Path
        $requestScriptName = parse_url($env->get('SCRIPT_NAME'), PHP_URL_PATH);
        $requestScriptDir = dirname($requestScriptName);

        // parse_url() requires a full URL. As we don't extract the domain name or scheme,
        // we use a stand-in.
        $requestUri = parse_url('http://example.com' . $env->get('REQUEST_URI'), PHP_URL_PATH);

        $basePath = '';
        $virtualPath = $requestUri;
        if (stripos($requestUri, $requestScriptName) === 0) {
            $basePath = $requestScriptName;
        } elseif ($requestScriptDir !== '/' && stripos($requestUri, $requestScriptDir) === 0) {
            $basePath = $requestScriptDir;
        }

        if ($basePath) {
            $virtualPath = ltrim(substr($requestUri, strlen($basePath)), '/');
        }

        // Query string
        $queryString = $env->get('QUERY_STRING', '');
        if ($queryString === '') {
            $queryString = parse_url('http://example.com' . $env->get('REQUEST_URI'), PHP_URL_QUERY);
        }

        // Fragment
        $fragment = '';

        // Build Uri
        $uri = new static($scheme, $host, $port, $virtualPath, $queryString, $fragment, $username, $password);
        if ($basePath) {
            $uri = $uri->withBasePath($basePath);
        }

        return $uri;
    }
329730
private function downloadPantheonBackup($env) {
    $project_properties = $this->getProjectProperties();
    $terminus_site_env  = $this->getPantheonSiteEnv($env);

    $terminus_url_request = $this->taskExec('terminus backup:get ' . $terminus_site_env . ' --element="db"')
      ->dir($project_properties['web_root'])
      ->interactive(false)
      ->run();

    if ($terminus_url_request->wasSuccessful()) {
      $terminus_url = $terminus_url_request->getMessage();
    }
    else {
      $this->yell('Failed to find a recent backup for the ' . $terminus_site_env . ' site. Does one exist?');
      return FALSE;
    }

    $wget_database = $this->taskExec('wget -O vendor/database.sql.gz "' . trim($terminus_url) . '"')->run();

    if (!$wget_database->wasSuccessful()) {
      $this->yell('Remote database sync failed.');
      return FALSE;
    }

    return TRUE;
  }
16454
public static function detectEnvironment($request = null)
    {
        if (!empty(static::$env)) {
            return static::$env;
        }

        $rules = self::get('env');

        $request = $request ? $request : Request::createFromGlobals();

        $host = $request->getHost();

        foreach ($rules as $env => $rule) {
            if (is_callable($rule)) {
                static::$env = $env;
            } elseif (preg_match($rule, $host)) {
                static::$env = $env;
                break;
            }
        }

        static::loadEnvironment(static::$env);

        return static::$env;
    }
976383
public function dump(Environment $env, $context)
    {
        if (!$this->isEnabled($env)) {
            return null;
        }

        if (func_num_args() === 2) {
            $vars = [];
            foreach ($context as $key => $value) {
                if (!$value instanceof Template) {
                    $vars[$key] = $value;
                }
            }

            $vars = [$vars];
        } else {
            $vars = func_get_args();
            unset($vars[0], $vars[1]);
        }

        $output = fopen('php://memory', 'r+b');
        $this->dumper->setCharset($env->getCharset());

        foreach ($vars as $value) {
            $this->dumper->dump($this->cloner->cloneVar($value), $output);
        }

        return stream_get_contents($output, -1, 0);
    }