Check the valid from and until dates in the track

@param \Gems_Tracker_RespondentTrack $respTrack The respondent track to check
@param int $userId Id of the user who takes the action (for logging)
@return int The number of tokens changed by this code
171930
public function checkTokensFromStart(\Gems_Tracker_RespondentTrack $respTrack, $userId)
    {
        $token = $respTrack->getFirstToken();
        if ($token instanceof \Gems_Tracker_Token) {
            return $this->checkTokensFrom($respTrack, $respTrack->getFirstToken(), $userId);
        } else {
            return 0;
        }
    }
336394
private function _update(array $values, $userId)
    {
        if ($this->tracker->filterChangesOnly($this->_trackData, $values)) {

            if (\Gems_Tracker::$verbose) {
                $echo = '';
                foreach ($values as $key => $val) {
                    $echo .= $key . ': ' . $this->_trackData[$key] . ' => ' . $val . "\n";
                }
                \MUtil_Echo::r($echo, 'Updated values for ' . $this->_trackId);
            }

            if (! isset($values['gto_changed'])) {
                $values['gtr_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
            }
            if (! isset($values['gtr_changed_by'])) {
                $values['gtr_changed_by'] = $userId;
            }

            // Update values in this object
            $this->_trackData = $values + $this->_trackData;

            // return 1;
            return $this->db->update('gems__tracks', $values, array('gtr_id_track = ?' => $this->_trackId));

        } else {
            return 0;
        }
    }
871691
protected function _ensureRespondentData()
    {
        if (! isset($this->_respTrackData['grs_id_user'], $this->_respTrackData['gr2o_id_user'], $this->_respTrackData['gco_code'])) {
            $sql = "SELECT *
                FROM gems__respondents INNER JOIN
                    gems__respondent2org ON grs_id_user = gr2o_id_user INNER JOIN
                    gems__consents ON gr2o_consent = gco_description
                WHERE gr2o_id_user = ? AND gr2o_id_organization = ? LIMIT 1";

            $respId = $this->_respTrackData['gr2t_id_user'];
            $orgId  = $this->_respTrackData['gr2t_id_organization'];

            if ($row = $this->db->fetchRow($sql, array($respId, $orgId))) {
                $this->_respTrackData = $this->_respTrackData + $row;
            } else {
                $trackId = $this->_respTrackId;
                throw new \Gems_Exception("Respondent data missing for track $trackId.");
            }
        }
    }
939684
public function execute($tokenData = null, $userId = null)
    {
        $batch   = $this->getBatch();
        $tracker = $this->loader->getTracker();

        $batch->addToCounter('checkedTokens');
        $token = $tracker->getToken($tokenData);

        $wasAnswered = $token->isCompleted();

        if ($result = $token->checkTokenCompletion($userId)) {
            if ($result & \Gems_Tracker_Token::COMPLETION_DATACHANGE) {
                $i = $batch->addToCounter('resultDataChanges');
                $batch->setMessage('resultDataChanges', sprintf(
                        $this->_('Results and timing changed for %d tokens.'),
                        $i
                        ));

                if ($wasAnswered) {
                    $action  = 'token.data-changed';
                    $message = sprintf($this->_("Token '%s' data has changed."), $token->getTokenId());
                } else {
                    $action  = 'token.answered';
                    $message = sprintf($this->_("Token '%s' was answered."), $token->getTokenId());
                }
                if (! $this->request instanceof \Zend_Controller_Request_Abstract) {
                    $this->request = \Zend_Controller_Front::getInstance()->getRequest();
                }
                $this->accesslog->logEntry(
                        $this->request,
                        $action,
                        true,
                        $message,
                        $token->getArrayCopy(),
                        $token->getRespondentId()
                        );

            }
            if ($result & \Gems_Tracker_Token::COMPLETION_EVENTCHANGE) {
                $i = $batch->addToCounter('surveyCompletionChanges');
                $batch->setMessage('surveyCompletionChanges', sprintf(
                        $this->_('Answers changed by survey completion event for %d tokens.'),
                        $i
                        ));
            }
        }

        if ($token->isCompleted()) {
            $batch->setTask('Tracker_ProcessTokenCompletion', 'tokproc-' . $token->getTokenId(), $tokenData, $userId);
        }

        $batch->setMessage('checkedTokens', sprintf(
                $this->_('Checked %d tokens.'),
                $batch->getCounter('checkedTokens')
                ));

        // Free memory
        $tracker->removeToken($token);
    }
1294304
def count_of_user(user_id):
        '''
        
        '''
        return TabCollect.select(
            TabCollect, TabPost.uid.alias('post_uid'),
            TabPost.title.alias('post_title'),
            TabPost.view_count.alias('post_view_count')
        ).where(
            TabCollect.user_id == user_id
        ).join(
            TabPost, on=(TabCollect.post_id == TabPost.uid)
        ).count()
725667
protected function _isTrackInFilter(\Gems_Tracker_RespondentTrack $track)
    {
        $result    = false;
        $trackInfo = array(
            'code'        => $track->getCode(),
            'trackid'     => $track->getTrackId(),
            'resptrackid' => $track->getRespondentTrackId(),
            'respid'      => $track->getRespondentId(),
        );

        if (empty($this->trackFilter)) {
            $result = true;
        } else {
            // Now read the filter and split by track code or track id
            foreach($this->trackFilter as $filter) {
                $remaining = array_diff_assoc($filter, $trackInfo);
                if (empty($remaining)) {
                    $result = true;
                    break;
                }
            }
        }

        // Only if track has a success code
        if ($result && $track->getReceptionCode()->isSuccess()) {
            return true;
        }

        return false;
    }
702685
def track(self, tracking_number):
        ""
        resp = self.send_request(tracking_number)
        return self.parse_response(resp)
1057968
public function checkToken($userId = null, $method = null)
    {
        /** @var Input $input */
        $input = $this->input;
        $token = $this->getFormToken($userId);

        if ($method) {
            $input = $input->$method;
        }

        if ($input->get($token, null, InputFilter::ALNUM) !== null) {
            return true;
        }

        if ($input->header->get('X-CSRF-Token') === $token) {
            return true;
        }

        return false;
    }
708125
protected function getGerritTrackingIdByIdentifier($changeSetId, $system, $trackingId)
    {
        $dbHandle = $this->getDatabase()->getDatabaseConnection();

        $query = 'SELECT `id`, `changeset`, `system`, `number`
                  FROM ' . Database::TABLE_TRACKING_ID . '
                  WHERE `changeset` = :changeset
                        AND `system` = :system
                        AND `number` = :number';
        $statement = $dbHandle->prepare($query);

        $statement->bindParam(':changeset', $changeSetId, \PDO::PARAM_INT);
        $statement->bindParam(':system', $system, \PDO::PARAM_INT);
        $statement->bindParam(':number', $trackingId, \PDO::PARAM_STR);
        $executeResult = $statement->execute();

        $statement = $this->getDatabase()->checkQueryError($statement, $executeResult);
        return $statement->fetch(\PDO::FETCH_ASSOC);
    }
326403
public function setReceptionCode($newCode, $userId)
    {
        $oldCode = $this->respondentTrack->getReceptionCode();
        
        if (! $newCode instanceof \Gems_Util_ReceptionCode) {
            $newCode = $this->util->getReceptionCode($newCode);
        }

        // Use the repesondent track function as that cascades the consent code
        $changed = $this->respondentTrack->setReceptionCode($newCode, $this->formData['gr2t_comment'], $userId);

        if ($this->unDelete) {
            $this->addMessage($this->_('Track restored.'));

            if (isset($this->formData['restore_tokens']) && $this->formData['restore_tokens']) {                
                $count = $this->respondentTrack->restoreTokens($oldCode, $newCode);
                
                $this->addMessage(sprintf($this->plural(
                        '%d token reception codes restored.',
                        '%d tokens reception codes restored.',
                        $count
                        ), $count));
            }
        } else {
            if ($newCode->isStopCode()) {
                $this->addMessage($this->_('Track stopped.'));
            } else {
                $this->addMessage($this->_('Track deleted.'));
            }
        }

        return $changed;
    }
1027253
private function checkSession($user_id, $user_sid, $touch = false)
    {
        $user_id = (int)$user_id;
        if (!defined('USER_ID')) {
            define('USER_ID', $user_id);
        }

        // Prolong session
        if ($touch) {
            $sessions = new UsersSessionEntityRepository();
            $sessions->setWhereSid($user_sid);
            /**
             * @var UsersSessionEntity $session
             */
            $session = $sessions->getFirstObjectFromCollection();
            if ($session) {
                $session->setTs(NOW);
                $session->save();
            }
        }

        // Check session for current user exists
        $sessions = new UsersSessionEntityRepository();
        $sessions->setWhereUserId($user_id);
        $sessions->setWhereSid($user_sid);
        $sessions->addWhereFieldIsHigherOrEqual('ts', NOW - CFG_SESSION_KEEP_ALIVE_SECONDS);

        return $sessions->hasAnyObjectInCollection();
    }
170591
private function checkTwoStepAuthStatus(int $userId)
    {
        $twoStepAuth = TwoStepAuth::firstOrCreate(
            [
                'userId' => $userId,
            ],
            [
                'userId'    => $userId,
                'authCode'  => $this->generateCode(),
                'authCount' => 0,
            ]
        );

        return $twoStepAuth;
    }
803823
protected function _exportTrackTokens(\Gems_Tracker_RespondentTrack $track)
    {
        $groupSurveys = $this->_group;
        $token        = $track->getFirstToken();
        $engine       = $track->getTrackEngine();
        $surveys      = array();

        $table = $this->html->table(array('class' => 'browser table'));
        $table->th($this->_('Survey'))
              ->th($this->_('Round'))
              ->th($this->_('Token'))
              ->th($this->_('Status'));
        $this->html->br();

        while ($token) {
            //Should this token be in the list?
            if (!$this->_isTokenInFilter($token)) {
                $token = $token->getNextToken();
                continue;
            }

            $table->tr()->td($token->getSurveyName())
                        ->td(($engine->getTrackType() == 'T' ? $token->getRoundDescription() : $this->_('Single Survey')))
                        ->td(strtoupper($token->getTokenId()))
                        ->td($token->getStatus());

            //Should we display the answers?
            if (!$this->_displayToken($token)) {
                $token = $token->getNextToken();
                continue;
            }

            $showToken = false;
            if (! $groupSurveys) {
                // For single survey tracks or when $groupSurvey === false we show all tokens
                $showToken = true;
            } else {
                // For multi survey tracks and $groupSurveys === true, we show only the first token
                // as the snippet takes care of showing the other tokens
                if (!isset($surveys[$token->getSurveyId()])) {
                    $showToken = true;
                    $surveys[$token->getSurveyId()] = 1;
                }
            }

            if ($showToken) {
                $params = array(
                    'token'          => $token,
                    'tokenId'        => $token->getTokenId(),
                    'showHeaders'    => false,
                    'showButtons'    => false,
                    'showSelected'   => false,
                    'showTakeButton' => false,
                    'grouped'        => $groupSurveys);

                $snippets = $token->getAnswerSnippetNames();

                if (!is_array($snippets)) {
                    $snippets = array($snippets);
                }

                list($snippets, $snippetParams) = \MUtil_Ra::keySplit($snippets);
                $params = $params + $snippetParams;

                $this->html->snippet('Export_SurveyHeaderSnippet', 'token', $token);

                foreach($snippets as $snippet) {
                    $this->html->snippet($snippet, $params);
                }

                $this->html->br();
            }

            $token = $token->getNextToken();
        }
    }
97004
def check_token(self, user, token):
        
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS:
            return False

        return True
847738
public function trackNodeView(PostResponseEvent $event) {
    // If the response is a success (e.g. status code 200) we can proceed.
    if ($event->getResponse()->isSuccessful()) {
      // Check if we're on a node page.
      if ($this->routeMatcher->getRouteName() === 'entity.node.canonical') {
        $node = $this->routeMatcher->getParameter('node');
        if ($node instanceof NodeInterface) {
          $config = \Drupal::config('social_node_statistics.settings');
          // Check if we should log for this node bundle.
          if (in_array($node->bundle(), $config->get('node_types'), FALSE)) {
            $now = $this->time->getRequestTime();

            // Insert the event in the table.
            $this->database->insert('node_statistics')
              ->fields([
                'uid' => $this->account->id(),
                'nid' => $node->id(),
                'timestamp' => $now,
              ])
              ->execute();

            // Get latest timestamp for possible cache invalidation.
            $latest = $this->database->select('node_statistics', 'n')
              ->fields('n', ['timestamp'])
              ->condition('n.nid', $node->id())
              ->orderBy('n.timestamp', 'DESC')
              ->range('1', '1')
              ->execute()
              ->fetchField();

            // Get count of views for possible cache invalidation.
            $count = $this->database->select('node_statistics', 'n')
              ->condition('n.nid', $node->id())
              ->countQuery()
              ->execute()
              ->fetchField();

            // Clear render cache only if max age is reached and the count is of
            // a certain predefined number.
            if (($now - $latest) >= $config->get('max_age') && $count % $config->get('min_views') === 0) {
              Cache::invalidateTags(['node:' . $node->id() . ':views_count']);
            }
          }
        }
      }
    }
  }
1046913
static function updateLastVisit( $userID, $updateLoginCount = false )
    {
        if ( isset( $GLOBALS['eZUserUpdatedLastVisit'] ) )
            return;
        $db = eZDB::instance();
        $userID = (int) $userID;
        $userVisitArray = $db->arrayQuery( "SELECT 1 FROM ezuservisit WHERE user_id=$userID" );
        $time = time();

        if ( isset( $userVisitArray[0] ) )
        {
            $loginCountSQL = $updateLoginCount ? ', login_count=login_count+1' : '';
            $db->query( "UPDATE ezuservisit SET last_visit_timestamp=ABS(current_visit_timestamp), current_visit_timestamp=$time$loginCountSQL WHERE user_id=$userID" );
        }
        else
        {
            $intialLoginCount = $updateLoginCount ? 1 : 0;
            $db->query( "INSERT INTO ezuservisit ( current_visit_timestamp, last_visit_timestamp, user_id, login_count ) VALUES ( $time, $time, $userID, $intialLoginCount )" );
        }
        $GLOBALS['eZUserUpdatedLastVisit'] = true;
    }
1143136
public function checkHeaderInTracker(&$exclude)
    {
        if ($exclude) {
            Common::printDebug("Visit is already excluded, no need to check DoNotTrack support.");
            return;
        }

        $exclude = $this->isDoNotTrackFound();

        if($exclude) {

            IgnoreCookie::deleteThirdPartyCookieUIDIfExists();

            // this is an optional supplement to the site's tracking status resource at:
            //     /.well-known/dnt
            // per Tracking Preference Expression
            
            //Tracking Perference Expression has been updated to require Tk: N rather than Tk: 1
            Common::sendHeader('Tk: N');
        }
    }