Returns the activities the user had access to between a time period.

@param int $sampleid
@param string $tablename
@param int $starttime
@param int $endtime
@return array
976369
protected function get_student_activities($sampleid, $tablename, $starttime, $endtime) {

        // May not be available.
        $user = $this->retrieve('user', $sampleid);

        if ($this->course === null) {
            // The indicator scope is a range, so all activities belong to the same course.
            $this->course = \core_analytics\course::instance($this->retrieve('course', $sampleid));
        }

        if ($this->activitylogs === null) {
            // Fetch all activity logs in each activity in the course, not restricted to a specific sample so we can cache it.

            $courseactivities = $this->course->get_all_activities($this->get_activity_type());

            // Null if no activities of this type in this course.
            if (empty($courseactivities)) {
                $this->activitylogs = false;
                return null;
            }
            $this->activitylogs = $this->fetch_activity_logs($courseactivities, $starttime, $endtime);
        }

        if ($this->grades === null) {
            // Even if this is probably already filled during fill_per_analysable_caches.
            $this->fetch_student_grades($this->course);
        }

        if ($cm = $this->retrieve('cm', $sampleid)) {
            // Samples are at cm level or below.
            $useractivities = array(\context_module::instance($cm->id)->id => $cm);
        } else {
            // Activities that should be completed during this time period.
            $useractivities = $this->get_activities($starttime, $endtime, $user);
        }

        return $useractivities;
    }
231445
public function usage($start = false, $end = false, $period = null)
    {
        $params = array();

        if ($start) {
            $params['start'] = $start;
        }
        if ($end) {
            $params['end'] = $end;
        }
        if (isset($period)) {
            $params['period'] = $period;
        }

        return $this->_user->get('account/usage', $params);
    }
710506
public function visitsByPeriod($startDate, $endDate, GetVisitByPeriod $getVisitByPeriod)
    {
        $startDate = Carbon::createFromFormat('Y-m-d', $startDate);
        $endDate = Carbon::createFromFormat('Y-m-d', $endDate);

        return $getVisitByPeriod->fire($startDate, $endDate);
    }
207749
protected function calculate_sample($sampleid, $sampleorigin, $starttime = false, $endtime = false) {

        if (!$starttime || !$endtime) {
            return null;
        }

        $select = '';
        $params = array();

        if ($user = $this->retrieve('user', $sampleid)) {
            $select .= "userid = :userid AND ";
            $params = $params + array('userid' => $user->id);
        }

        if (!$logstore = \core_analytics\manager::get_analytics_logstore()) {
            throw new \coding_exception('No available log stores');
        }

        // Filter by context to use the logstore_standard_log db table index.
        $context = $this->retrieve('context', $sampleid);
        $select .= "contextlevel = :contextlevel AND contextinstanceid = :contextinstanceid AND " .
            "crud = 'r' AND timecreated > :starttime AND timecreated <= :endtime";
        $params = $params + array('contextlevel' => $context->contextlevel,
            'contextinstanceid' => $context->instanceid, 'starttime' => $starttime, 'endtime' => $endtime);
        $nrecords = $logstore->get_events_select_count($select, $params);
        // We define a list of ranges to fit $nrecords into it
        // # Done absolutely nothing
        // # Not much really, just accessing the course once a week
        // # More than just accessing the course, some interaction
        // # Significant contribution, will depend on the course anyway.

        // We need to adapt the limits to the time range duration.
        $nweeks = $this->get_time_range_weeks_number($starttime, $endtime);

        // Careful with this, depends on the course.
        $limit = $nweeks * 3 * 10;
        $ranges = array(
            array('eq', 0),
            // 1 course access per week (3 records are easily generated).
            array('le', $nweeks * 3),
            // 3 course accesses per week doing some stuff.
            array('le', $limit),
            array('gt', $limit)
        );
        return $this->classify_value($nrecords, $ranges);
    }
564022
public function sample_description($sampleid, $contextid, $sampledata) {
        $description = fullname($sampledata['user']);
        return [$description, new \user_picture($sampledata['user'])];
    }
1305320
public function getMostVisitedPagesForPeriod($startDate, $endDate, $maxResults = 20)
    {
        $pagesData = [];

        $answer = $this->performQuery($startDate, $endDate, 'ga:pageviews', ['dimensions' => 'ga:pagePath', 'sort' => '-ga:pageviews', 'max-results' => $maxResults]);

        if (is_null($answer->rows)) {
            return new Collection([]);
        }

        foreach ($answer->rows as $pageRow) {
            $pagesData[] = ['url' => $pageRow[0], 'pageViews' => $pageRow[1]];
        }

        return new Collection($pagesData);
    }
1057533
public function scanCompleted(Event $event, $startTime, $endTime, ResultScan $ResultScan)
    {
        if ($this->args->getOption('verbose')) {
            $this->io->hr();
        }

        $endTime = new Time($endTime);
        $elapsedTime = $endTime->diffForHumans(new Time($startTime), true);

        $this->io->out(__d('link-scanner', 'Scan completed at {0}', $endTime->i18nFormat('yyyy-MM-dd HH:mm:ss')));
        $this->io->out(__d('link-scanner', 'Elapsed time: {0}', $elapsedTime));
        $this->io->out(__d('link-scanner', 'Total scanned links: {0}', $ResultScan->count()));

        if ($this->args->getOption('verbose')) {
            $this->io->hr();
        }

        return true;
    }
204158
public function getVisitorsAndPageViewsForPeriod($startDate, $endDate, $groupBy = 'date')
    {
        $visitorData = [];
        $answer = $this->performQuery($startDate, $endDate, 'ga:visits,ga:pageviews', ['dimensions' => 'ga:'.$groupBy]);

        foreach ($answer->rows as $dateRow) {
            $visitorData[] = [$groupBy => Carbon::createFromFormat(($groupBy == 'yearMonth' ? 'Ym' : 'Ymd'), $dateRow[0]), 'visitors' => $dateRow[1], 'pageViews' => $dateRow[2]];
        }

        return new Collection($visitorData);
    }
681660
public function getTopReferrersForPeriod($startDate, $endDate, $maxResults)
    {
        $referrerData = [];

        $answer = $this->performQuery($startDate, $endDate, 'ga:pageviews', ['dimensions' => 'ga:fullReferrer', 'sort' => '-ga:pageviews', 'max-results' => $maxResults]);

        if (is_null($answer->rows)) {
            return new Collection([]);
        }

        foreach ($answer->rows as $pageRow) {
            $referrerData[] = ['url' => $pageRow[0], 'pageViews' => $pageRow[1]];
        }

        return new Collection($referrerData);
    }
47091
public function getRecurringEvents($starttime = null, $endtime = null) {

		if (is_null($starttime)) {
			$starttime = time();
		}
		if (is_null($endtime)) {
			$endtime = strtotime('+1 year', $starttime);
		}

		$starttime = sanitize_int($starttime);
		$endtime = sanitize_int($endtime);
		$relationship_name = sanitize_string(self::EVENT_CALENDAR_RELATIONSHIP);

		$dbprefix = elgg_get_config('dbprefix');

		// for performance we'll denormalize metastrings first
		$mdr_name = elgg_get_metastring_id('repeat');
		$mdr_val = elgg_get_metastring_id(1);
		$mds_name = elgg_get_metastring_id('start_timestamp');
		$mdre_name = elgg_get_metastring_id('repeat_end_timestamp');
		$options = array(
			'type' => 'object',
			'subtype' => Event::SUBTYPE,
			'joins' => array(
				"JOIN {$dbprefix}entity_relationships er ON er.guid_one = e.guid", // calendar relationship
				"JOIN {$dbprefix}metadata mdr ON mdr.entity_guid = e.guid", // repeating metadata
				"JOIN {$dbprefix}metadata mds ON mds.entity_guid = e.guid", // start time metadata
				"JOIN {$dbprefix}metastrings mss ON mss.id = mds.value_id", // start time metastring
				"JOIN {$dbprefix}metadata mdre ON mdre.entity_guid = e.guid", // repeat end time metadata
				"JOIN {$dbprefix}metastrings msre ON msre.id = mdre.value_id" // repeat end time metastring
			),
			'wheres' => array(
				"er.guid_two = {$this->guid} AND er.relationship = '{$relationship_name}'",
				"mdr.name_id = {$mdr_name} AND mdr.value_id = {$mdr_val}",
				"mds.name_id = {$mds_name}",
				"mdre.name_id = {$mdre_name}",
				// event start is before our endtime AND (repeat end is after starttime, or there is no repeat end)
				"((CAST(mss.string AS SIGNED) < {$endtime}) AND (CAST(msre.string AS SIGNED) > {$starttime} OR CAST(msre.string AS SIGNED) = 0))"
			),
			'limit' => false
		);

		$events = new ElggBatch('elgg_get_entities', $options);

		// these entities may not actually show up in our range yet, need to filter
		$recurring_events = array();
		foreach ($events as $event) {
			/* @var Event $event */
			if ($event->getStartTimes($starttime, $endtime)) {
				// hey, we have a hit!
				$recurring_events[] = $event;
			}
		}

		return $recurring_events;
	}
1282774
public function getEvents(\DateTime $begin, \DateTime $end, array $options = array())
    {
        $events = array();

        foreach ($this->providers as $provider) {
            $events = array_merge($events, $provider->getEvents($begin, $end, $options));
        }

        return $events;
    }
762840
protected function social_calculate_sample($sampleid, $tablename, $starttime = false, $endtime = false) {

        // May not be available.
        $user = $this->retrieve('user', $sampleid);

        if (!$useractivities = $this->get_student_activities($sampleid, $tablename, $starttime, $endtime)) {
            // Null if no activities.
            return null;
        }

        $scoreperactivity = (self::get_max_value() - self::get_min_value()) / count($useractivities);

        $score = self::get_min_value();

        foreach ($useractivities as $contextid => $cm) {

            $potentiallevel = $this->get_social_breadth_level($cm);
            if (!is_int($potentiallevel)
                    || $potentiallevel > self::MAX_SOCIAL_LEVEL
                    || $potentiallevel < self::SOCIAL_LEVEL_1) {
                throw new \coding_exception('Activities\' potential social breadth go from 1 to ' .
                    community_of_inquiry_activity::MAX_SOCIAL_LEVEL . '.');
            }
            $scoreperlevel = $scoreperactivity / $potentiallevel;
            switch ($potentiallevel) {
                case self::SOCIAL_LEVEL_2:
                case self::SOCIAL_LEVEL_3:
                case self::SOCIAL_LEVEL_4:
                case self::SOCIAL_LEVEL_5:
                    // Core activities social breadth only reaches level 2, until core activities social
                    // breadth do not reach level 5 we limit it to what we currently support, which is level 2.

                    // Social breadth level 2 is to view feedback. (Same as cognitive level 3).

                    if ($this->any_feedback('viewed', $cm, $contextid, $user)) {
                        // Max score for level 2.
                        $score += $scoreperlevel * 2;
                        break;
                    }
                    // The user didn't reach the activity max social breadth, continue with level 1.

                case self::SOCIAL_LEVEL_1:
                    // Social breadth level 1 is just accessing the activity.
                    if ($this->any_log($contextid, $user)) {
                        $score += $scoreperlevel;
                    }
            }

        }

        // To avoid decimal problems.
        if ($score > self::MAX_VALUE) {
            return self::MAX_VALUE;
        } else if ($score < self::MIN_VALUE) {
            return self::MIN_VALUE;
        }
        return $score;
    }
705832
public function getData(int $type, int $startTime, int $endTime, array $userIdList): array
    {
        return $this->httpClient->postJson('checkin/getcheckindata', [
            'opencheckindatatype' => $type,
            'starttime' => $startTime,
            'endtime' => $endTime,
            'useridlist' => $userIdList
        ]);
    }
1219490
private function computeTimeForUserAndWorkspace($startDate, $userId, $workspaceId, $time)
    {
        // select first "out of this workspace event" (ie "workspace enter" on another workspace)
        $sql = "SELECT date_log FROM claro_log WHERE action LIKE 'workspace-enter' AND doer_id = :uid  AND date_log > :dateLog ORDER BY date_log ASC LIMIT 1";
        $stmt = $this->em->getConnection()->prepare($sql);
        $stmt->bindValue('uid', $userId);
        $stmt->bindValue('dateLog', $startDate);
        $stmt->execute();
        $action = $stmt->fetch();

        // if there is an action we can compute time
        if ($action['date_log']) {
            $t1 = strtotime($startDate);
            $t2 = strtotime($action['date_log']);
            $seconds = $t2 - $t1;

            // add time only if bewteen 30s and 2 hours <= totally arbitrary !
            if ($seconds > 5 && ($seconds / 60) <= 120) {
                $time += $seconds;
            }
            // get next "enter the requested workspace enter event"
            $sql = "SELECT date_log FROM claro_log WHERE action LIKE 'workspace-enter' AND doer_id = :uid AND date_log > :dateLog AND workspace_id = :wid ORDER BY date_log ASC LIMIT 1";
            $stmt = $this->em->getConnection()->prepare($sql);
            $stmt->bindValue('uid', $userId);
            $stmt->bindValue('dateLog', $action['date_log']);
            $stmt->bindValue('wid', $workspaceId);
            $stmt->execute();
            $nextEnterEvent = $stmt->fetch();
            // if there is an "enter-workspace" action after the current one recall the method
            if ($nextEnterEvent['date_log']) {
                return $this->computeTimeForUserAndWorkspace($nextEnterEvent['date_log'], $userId, $workspaceId, $time);
            } else {
                return $time;
            }
        }

        return $time;
    }
1033008
protected function getVisitsViewsUsersForPeriod(
        DateTime $startDate,
        DateTime $endDate
    ) {
        $cacheName = md5(serialize('visits-views-users'
            .$startDate->format('Y-m-d').$endDate->format('Y-m-d')));

        $urlParams = [
            'ids'        => $this->counter_id,
            'date1'      => $startDate->format('Y-m-d'),
            'date2'      => $endDate->format('Y-m-d'),
            'metrics'    => 'ym:s:visits,ym:s:pageviews,ym:s:users',
            'dimensions' => 'ym:s:date',
            'sort'       => 'ym:s:date',
        ];

        $this->data = $this->request($urlParams, $cacheName);
    }
382461
public function getOccurrencesBetween($startDate, $endDate, $limit = NULL)
    {

        $thisClone = clone $this;

        // Enforce consistent time zones. Date comparisons don't require them, but +P1D loop does.
        if ($tz = $thisClone->getTimeZone())
        {
            $startDate->setTimeZone($tz);
            $endDate->setTimeZone($tz);
        }

        $occurrences = [];

        if ($endDate <= $startDate)
        {
            return $occurrences;
        }

        // if existing UNTIL < startDate - we have nothing
        if (isset($thisClone->until) && $thisClone->until < $startDate)
        {
            return $occurrences;
        } // prevent unnecessary leg-work - our endDate is our new UNTIL
        elseif (!isset($thisClone->until))
        {
            $thisClone->until = $endDate;
        }

        $thisClone->generateOccurrences();
        $all_occurrences = $thisClone->occurrences;

        // nothing found in $thisClone->generateOccurrences();
        if (empty($all_occurrences))
        {
            return $occurrences;
        }

        $last_occurrence = end($all_occurrences);

        // if we've hit the rangeLimit, restart looking but start at this last_occurrence
        if ($thisClone->rangeLimit == count($all_occurrences)
            && $thisClone->startDate != $last_occurrence)
        {
            $thisClone->startDate = clone $last_occurrence;

            if (isset($thisClone->limit))
            {
                $thisClone->limit = $thisClone->limit - 200;
            }

            // clear all occurrences before our start date
            foreach ($thisClone->occurrences as $key => $occurrence)
            {
                if ($occurrence < $startDate)
                {
                    unset($thisClone->occurrences[$key]);
                }
            }

            return $thisClone->getOccurrencesBetween($startDate, $endDate, $limit);
        }

        // if our last occurrence is is before our startDate, we have nothing
        if ($last_occurrence < $startDate)
        {
            return $occurrences;
        }

        // we have something to report, so reset our array pointer
        reset($all_occurrences);

        $count = 0;

        foreach ($all_occurrences as $occurrence)
        {
            // fastforward our pointer to where it's >= startDate
            if ($occurrence < $startDate)
            {
                continue;
            }
            // if current occurence is past our endDate - we're done
            if ($occurrence > $endDate)
            {
                break;
            }
            // if we reach getOccurrencesBetween()'s limit - we're done
            if (NULL != $limit && ++$count > $limit)
            {
                break;
            }

            $occurrences[] = $occurrence;
        }

        return $occurrences;
    }
1244310
public function getParticipationsByDayByRangeDate($startDate = '', $endDate = '')
    {
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
        $emConfig = $em->getConfiguration();
        $emConfig->addCustomDatetimeFunction('DATE', '\DoctrineExtensions\Query\Mysql\Date');

        $startDateTime = \DateTime::createFromFormat('d/m/Y', $startDate);
        $endDateTime = \DateTime::createFromFormat('d/m/Y', $endDate);

        if ($startDate != '' && $endDate != '') {
            $dateRange = "(e.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0' AND e.created_at <= '" . $endDateTime->format('Y-m-d') . " 23:59:59')";
        } elseif ($startDate == '' && $endDate != '') {
            $dateRange = "e.created_at <= '" . $endDateTime->format('Y-m-d') . " 23:59:59'";
        } elseif ($startDate != '' && $endDate == '') {
            $dateRange = "e.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0'";
        } else {
            $dateRange = "e.created_at IS NOT NULL";
        }

        $query = $em->createQuery('
            SELECT DATE(e.created_at) as date, COUNT(e.id) as qty FROM PlaygroundGame\Entity\Entry e
			WHERE ' . $dateRange . '
            AND e.active=0
            GROUP BY date
        ');
        $result = $query->getResult();
        return $result;
    }