Common handler utility to initialize tokens from parameters

@return boolean True if there is a real token specified in the request
347965
protected function _initToken()
    {
        if ($this->tracker) {
            return $this->token && $this->token->exists;
        }

        $this->tracker = $this->loader->getTracker();
        $this->tokenId = $this->tracker->filterToken($this->_getParam(\MUtil_Model::REQUEST_ID));
        // Now check if the token is valid
        $validator = $this->tracker->getTokenValidator();

        if (! $this->tokenId || $validator->isValid($this->tokenId) === false) {
            return false;
        }

        $this->token = $this->tracker->getToken($this->tokenId);

        if (! $this->token->exists) {
            return false;
        }

        if (! ($this->currentUser->isActive() || $this->token->getSurvey()->isTakenByStaff())) {
            $tokenLang = strtolower($this->token->getRespondentLanguage());
            // \MUtil_Echo::track($tokenLang, $this->locale->getLanguage());
            if ($tokenLang != $this->locale->getLanguage()) {
                $this->currentUser->switchLocale($tokenLang);
            }

            $currentOrg = $this->loader->getOrganization();
            $tokenOrgId = $this->token->getOrganizationId();

            if ($tokenOrgId != $currentOrg->getId()) {
                $this->loader->getOrganization($tokenOrgId)
                        ->setAsCurrentOrganization();
            }
        }

        return true;
    }
1152624
private function _initialize()
    {
        list($status, $reason, $etag, $last_modified, $content_type,
            $content_length, $metadata) =
                $this->container->cfs_http->head_object($this);
        #if ($status == 401 && $this->_re_auth()) {
        #    return $this->_initialize();
        #}
        if ($status == 404) {
            return False;
        }
        if ($status < 200 || $status > 299) {
            throw new InvalidResponseException("Invalid response (".$status."): "
                . $this->container->cfs_http->get_error());
        }
        $this->etag = $etag;
        $this->last_modified = $last_modified;
        $this->content_type = $content_type;
        $this->content_length = $content_length;
        $this->metadata = $metadata;
        return True;
    }
28321
public function loadUserFromToken()
    {
        $token = $this->httpCookie()->get($this->getTokenName());
        if (!$token) {
            return false;
        }

        return $this->decryptUserData($token);
    }
226701
public function initialize()
    {
        static::addFilterDefinition('required', array($this, 'filterRequired'));
        static::addFilterDefinition('string', array($this, 'filterString'));
        static::addFilterDefinition('boolean', array($this, 'filterBoolean'));
        static::addFilterDefinition('confirm', array($this, 'filterConfirm'));
        static::addFilterDefinition('validate_regexp', array($this, 'filterValidateRegexp'));
        static::addFilterDefinition('validate_url', array($this, 'filterValidateUrl'));
        static::addFilterDefinition('validate_date', array($this, 'filterValidateDate'));
        static::addFilterDefinition('php', array($this, 'filterPHP'));
        static::addFilterDefinition('max_length', array($this, 'filterMaxLength'));
        static::addFilterDefinition('min_length', array($this, 'filterMinLength'));
        static::$isInitialized = TRUE;
    }
511779
public function initialize($csrf = false)
    {
        $this->_tokenRequired = $csrf;
        if ($csrf) {
            // get current token value from session
            $currentToken = App::$Session->get('_csrf_token', false);
            // set new token value to session
            $newToken = Crypt::randomString(mt_rand(32, 64));
            App::$Session->set('_csrf_token', $newToken);
            // if request is submited for this model - try to validate input data
            if ($this->send()) {
                // token is wrong - update bool state
                if ($currentToken !== $this->getRequest('_csrf_token')) {
                    $this->_tokenOk = false;
                }
            }
            // set token data to display
            $this->_csrf_token = $newToken;
        }
    }
1233359
public function getRequestToken()
    {
        // Nullify any request token we already have
        $this->storage->set(null, 'request_token');
        $url = API::API_URL . self::REQUEST_TOKEN_METHOD;
        $response = $this->fetch('POST', $url, '');
        $token = $this->parseTokenString($response['body']);
        $this->storage->set($token, 'request_token');
    }
633760
private function parseItem()
    {
        $subparser = new StringValue($this->parser, ($this->level + 1));
        $subparser->parse();

        $key = $subparser->getValue();

        $this->debug('key: ' . var_export($key, true));

        if ($this->tokenIs(T_DOUBLE_ARROW)) {
            // We MUST have an key when double arrow is encountered.
            if ($key === null) {
                $this->bailUnexpectedToken();
            }

            $this->pushStack($key);
            $this->parseValue();
            $this->popStack();
        } elseif ($this->tokenIs(',') || $this->tokenIs(')') || $this->tokenIs(']')) {
            // String item without key.
            $this->debug('String item without key.');
            $this->pushStack($this->counter++);
            $this->parser->setValue($this->parser->getStack(), $key);
            $this->popStack();
        }

        if ($this->tokenIs(',')) {
            $this->getNextToken();
            return true;
        }
        if ($this->tokenIs(')') || $this->tokenIs(']')) {
            $this->debug('closing bracket.');
            $this->getNextToken();

            return false;
        }

        return true;
    }
584808
protected function Init()
    {
        $this->confirm = ContentRegisterConfirm::Schema()->ByContent($this->Content());
        $this->confirmer = new Confirmer();
        $this->isValid = $this->confirmer->Check(Request::GetArray());
        if ($this->isValid)
        {
            $this->OnSuccess();
        }
        else if ($this->confirm->GetErrorUrl())
        {
            Response::Redirect(FrontendRouter::Url($this->confirm->GetErrorUrl()));
            return true;
        }
        return parent::Init();
    }
366454
public function validateCsrf()
    {
        $tokenService = $this->getServiceLocator()->get(TokenService::SERVICE_ID);

        $tokenName = $tokenService->getTokenName();
        $token = $this->getRequestParameter($tokenName);

        if ( $tokenService->checkToken($token) ) {
            $tokenService->revokeToken($token);
            $newToken = $tokenService->createToken();
            $this->setCookie($tokenName, $newToken, null, '/');
            return true;
        }

        \common_Logger::w('Csrf validation failed');
        throw new \common_exception_Unauthorized();
    }
335134
final public function validate(): bool
    {
        // validate csrf token if required
        if ($this->_tokenRequired && !$this->_tokenOk) {
            App::$Session->getFlashBag()->add('warning', __('Hack attention: security token is wrong!'));
            return false;
        }
        // get all rules as array from method rules()
        $rules = $this->rules();
        // get default values of attributes
        $defaultAttr = $this->getAllProperties();

        // start validation: on this step class attribute values will be changed to input data if it valid
        $success = $this->runValidate($rules);

        // get not-passed validation fields as array
        $badAttributes = $this->getBadAttributes();
        // prevent warnings
        if (Any::isArray($badAttributes) && count($badAttributes) > 0) {
            foreach ($badAttributes as $attr) {
                if (Str::contains('.', $attr)) { // sounds like dot-separated array attr
                    $attrName = strstr($attr, '.', true); // get attr name
                    $attrArray = trim(strstr($attr, '.'), '.'); // get dot-based array path

                    $defaultValue = new DotData($defaultAttr); // load default attr

                    $dotData = new DotData($this->{$attrName}); // load local attr variable
                    $dotData->set($attrArray, $defaultValue->get($attr)); // set to local prop. variable default value

                    $this->{$attrName} = $dotData->export(); // export to model
                } else {
                    $this->{$attr} = $defaultAttr[$attr]; // just set ;)
                }
                // add message about wrong attribute to session holder, later display it
                $attrLabel = $attr;
                if ($this->getLabel($attr) !== null) {
                    $attrLabel = $this->getLabel($attr);
                }

                App::$Session->getFlashBag()->add('warning', __('Field "%field%" is incorrect', ['field' => $attrLabel]));
            }
        }

        return $success;
    }
1337103
protected function isTokenValid() {
    if ($this->isTokenValid) {
      // already validated
      return true;
    }
    $request = ObjectFactory::getInstance('request');
    $token = $request->hasHeader(self::TOKEN_HEADER) ? $request->getHeader(self::TOKEN_HEADER) :
        $request->getValue(self::TOKEN_HEADER, null);
    $this->isTokenValid = $token != null && $token == $_COOKIE[$this->tokenName];
    return $this->isTokenValid;
  }
765300
public static function checkToken()
    {
        $token = Input::postString('CML_TOKEN');
        if (empty($token)) return false;
        if ($token !== self::getToken()) return false;
        unset($_COOKIE['CML_TOKEN']);
        return true;
    }
669500
public function InParameter()
    {
        if ($this->lexer->lookahead['type'] == Lexer::T_INPUT_PARAMETER) {
            return $this->InputParameter();
        }

        return $this->Literal();
    }
126837
public function tokenAction()
    {
        // Can't do anything if not HTTP request...
        if (!$this->request instanceof HttpRequest) {
            return null;
        }

        // Currently, ZF2 Http Request object is not PSR-7 compliant, therefore we need to create a new one from
        // globals, and then convert the response back to ZF2 format

        $request  = ServerRequestFactory::fromGlobals();
        $response = $this->authorizationServer->handleTokenRequest($request);

        return $this->convertToZfResponse($response);
    }
367916
public function token()
    {
        $inputs = $this->getInputs();
        $headers = $this->headers();

        // Read token from request custom header
        if (isset($headers['X-Auth-Token'])) {
            return $headers['X-Auth-Token'];
        }

        // Read token from request input
        if (isset($inputs['token'])) {
            return $inputs['token'];
        }

        // Otherwise, return false
        return false;
    }
118296
private function initContext()
    {
        //request instance;
        $req=new Request();

        //request headers
        $req->headers=[];
        foreach ($_SERVER as $name => $value){
            if(strpos($name, "HTTP_")===0){
                $key=str_replace(" ", "-", ucwords(str_replace("_", " ", substr(strtolower($name), 5))));
                $req->headers[$key]=$value;
            }
        }
        if (isset($_SERVER["PHP_AUTH_DIGEST"])) {
            $req->headers["Authorization"] = $_SERVER["PHP_AUTH_DIGEST"];
        } elseif (isset($_SERVER["PHP_AUTH_USER"]) && isset($_SERVER["PHP_AUTH_PW"])) {
            $req->headers["Authorization"] = base64_encode($_SERVER["PHP_AUTH_USER"] . ":" . $_SERVER["PHP_AUTH_PW"]);
        }
        if (isset($_SERVER["CONTENT_LENGTH"])) {
            $req->headers["Content-Length"] = $_SERVER["CONTENT_LENGTH"];
        }
        if (isset($_SERVER["CONTENT_TYPE"])) {
            $req->headers["Content-Type"] = $_SERVER["CONTENT_TYPE"];
        }
        $req->charset=array_key_exists("HTTP_ACCEPT_CHARSET", $req->headers)?$req->headers["HTTP_ACCEPT_CHARSET"]:"utf-8";
        $req->contentType=array_key_exists("CONTENT_TYPE", $req->headers)?$req->headers["CONTENT_TYPE"]:"text/html";
        $req->contentLength=array_key_exists("CONTENT_LENGTH", $req->headers)?$req->headers["CONTENT_LENGTH"]:0;

        $req->method=$_SERVER["REQUEST_METHOD"];
        $req->protocol=$_SERVER["SERVER_PROTOCOL"];
        $req->scheme=$_SERVER["REQUEST_SCHEME"];
        $req->host=$_SERVER["HTTP_HOST"];
        $req->port=$_SERVER["SERVER_PORT"];
        $req->uri=$_SERVER["REQUEST_URI"];
        $req->get=$_GET;
        $req->post=$_POST;

        //response
        $rsp=new Response();
        $rsp->setCharset($req->charset);

        //context
        $this->m_context=new Context($req,$rsp);
    }
680127
public function initialize()
    {
        if (is_null($value = $this->getValue())) {
            $value = request()->input($this->getAlias());
        }

        $this->setValue($value);
    }