Evaluate Source & Campaign limits using the Cache.

@throws ContactSourceException
@throws \Exception
14907
private function evaluateLimits()
    {
        $limits        = new \stdClass();
        $limits->rules = $this->limits;

        $this->excludeIrrelevantRules($limits);

        $this->getCacheModel()->evaluateLimits($limits, $this->campaignId);
    }
553233
public function getEventsForTimelineExport($contactSourceId, array $options = [], $count)
    {
        $query = $this->getEntityManager()->getConnection()->createQueryBuilder()
            ->from(MAUTIC_TABLE_PREFIX.'contactsource_events', 'c');
        if ($count) {
            $query->select('COUNT(c.id) as count');
        } else {
            $query->select('c.id, c.type, c.date_added, c.message, c.contact_id, c.logs');
        }

        $query->where(
            $query->expr()->eq('c.contactsource_id', ':contactSourceId')
        )
            ->setParameter('contactSourceId', (int) $contactSourceId);

        if (!empty($options['dateFrom']) && !empty($options['dateTo'])) {
            $options['dateTo']->modify('+1 day - 1 second');
            $query->andWhere('c.date_added BETWEEN FROM_UNIXTIME(:dateFrom) AND FROM_UNIXTIME(:dateTo)')
                ->setParameter('dateFrom', $options['dateFrom']->setTime(00, 00, 00)->getTimestamp())
                ->setParameter('dateTo', $options['dateTo']->setTime(23, 59, 59)->getTimestamp());
        } elseif (!empty($options['dateFrom'])) {
            $query->andWhere($query->expr()->gte('c.date_added', 'FROM_UNIXTIME(:dateFrom)'))
                ->setParameter('dateFrom', $options['dateFrom']->setTime(00, 00, 00)->getTimestamp());
        } elseif (!empty($options['dateTo'])) {
            $options['dateTo']->modify('+1 day - 1 second');
            $query->andWhere($query->expr()->lte('c.date_added', 'FROM_UNIXTIME(:dateTo)'))
                ->setParameter('dateTo', $options['dateTo']->setTime(23, 59, 59)->getTimestamp());
        }

        if (isset($options['message']) && !empty($options['message'])) {
            $query->andWhere('c.message LIKE :message')
                ->setParameter('message', '%'.trim($options['message']).'%');
        }

        if (isset($options['contact_id']) && !empty($options['contact_id'])) {
            $query->andWhere('c.contact_id = :contact')
                ->setParameter('contact', trim($options['contact_id']));
        }

        if (isset($options['type']) && !empty($options['type'])) {
            $query->andWhere('c.type = :type')
                ->setParameter('type', trim($options['type']));
        }

        if (isset($options['campaignId']) && !empty($options['campaignId'])) {
            $query->join(
                'c',
                'contactsource_stats', 's',
                'c.contactsource_id = s.contactsource_id AND c.contact_id = s.contact_id'
            )
                ->andWhere($query->expr()->eq('s.campaign_id', ':campaignId'))
                ->setParameter('campaignId', $options['campaignId']);
        }

        $query->orderBy('c.date_added', 'DESC');

        if (!empty($options['limit'])) {
            $query->setMaxResults($options['limit']);
            if (!empty($options['start'])) {
                $query->andWhere('c.id > :offset')
                    ->setParameter('offset', $options['start']);
            }
        }

        $results = $query->execute()->fetchAll();

        return $results;
    }
891013
public function evaluateLimits()
    {
        $limits = $this->getRepository()->findLimit(
            $this->contactClient,
            $this->getLimitRules(),
            $this->getTimezone(),
            $this->dateSend
        );
        if ($limits) {
            throw new ContactClientException(
                'Not able to send contact to client due to an exceeded budget.',
                Codes::HTTP_TOO_MANY_REQUESTS,
                null,
                Stat::TYPE_LIMITS,
                false,
                null,
                $limits
            );
        }
    }
859153
public function getCampaignLeadIdsForExport($campaignId, $dateFrom, $dateTo, $first = 0, $limit = 1000)
    {
        $contactIds = [];
        /** @var QueryBuilder $q */
        $q = $this->get('doctrine.orm.entity_manager')->getConnection()->createQueryBuilder();
        $q->select('cl.lead_id')
            ->from('campaign_leads', 'cl')
            ->where(
                $q->expr()->eq('cl.manually_removed', ':false'),
                $q->expr()->eq('cl.campaign_id', ':campaign'),
                $q->expr()->gte('cl.date_added', 'FROM_UNIXTIME(:dateFrom)'),
                $q->expr()->lt('cl.date_added', 'FROM_UNIXTIME(:dateTo)')
            )
            ->setParameter('false', false, 'boolean')
            ->setParameter('campaign', $campaignId)
            ->setParameter('dateFrom', $dateFrom)
            ->setParameter('dateTo', $dateTo)
            ->setFirstResult($first)
            ->setMaxResults($limit);

        $result = $q->execute()->fetchAll();
        if (!empty($result)) {
            $contactIds = array_column($result, 'lead_id');
        }

        return $contactIds;
    }
1359864
public function getSourcesByCampaign($campaignId)
    {
        // WHERE campaign_settings REGEXP '\"campaignId\":\s*\"' . campaing_id . '\",';
        //       $where = 'l.'.$field.' REGEXP  :value';

        $q = $this->_em->getConnection()->createQueryBuilder()
            ->select('cs.*')
            ->from(MAUTIC_TABLE_PREFIX.'contactsource', 'cs');

        $where = 'REPLACE(cs.campaign_settings, " ", "") REGEXP  :regex';
        $q->where(
                $q->expr()->eq('cs.is_published', true),
                $q->expr()->andX($where)
        );

        $q->setParameter('regex', '"campaignId\":"'.$campaignId.'"');

        $results = $q->execute()->fetchAll();

        return $results;
    }
486793
function handleResource( $tpl, &$resourceData, $method, &$extraParameters )
    {
        $path = $resourceData['template-name'];

        $matchKeys = $this->Keys;
        if ( isset( $GLOBALS['eZDesignKeys'] ) )
        {
            $matchKeys = array_merge( $matchKeys, $GLOBALS['eZDesignKeys'] );
            unset( $GLOBALS['eZDesignKeys'] );
            $this->Keys = $matchKeys;
        }
        if ( is_array( $extraParameters ) and
             isset( $extraParameters['ezdesign:keys'] ) )
        {
            $this->mergeKeys( $matchKeys, $extraParameters['ezdesign:keys'] );
        }
        $this->KeyStack[] = $this->Keys;
        $this->Keys = $matchKeys;

        eZDebug::accumulatorStart( 'override_cache', 'Override', 'Cache load' );

        if( !isset( $GLOBALS['eZOverrideTemplateCacheMap'] ) )
        {
            $overrideCacheFile = $this->createOverrideCache();

            if ( $overrideCacheFile )
            {
                include_once( $overrideCacheFile );
            }
        }

        if ( isset( $GLOBALS['eZOverrideTemplateCacheMap'] ) )
        {
            if( isset( $GLOBALS['eZOverrideTemplateCacheMap'][md5( '/' . $path )] ) )
            {
                $cacheMap = $GLOBALS['eZOverrideTemplateCacheMap'][md5( '/' . $path )];
                if ( !is_string( $cacheMap ) and trim( $cacheMap['code'] ) )
                {
                    eval( "\$matchFile = " . $cacheMap['code'] . ";" );
                }
                else
                {
                    $matchFile = $cacheMap;
                }
                $match['file'] = $matchFile;
            }
        }
        else
        {
            $template = "/" . $path;
            $matchFileArray = eZTemplateDesignResource::overrideArray( $this->OverrideSiteAccess );

            $matchFile = $matchFileArray[$template];

            if ( isset( $matchFile['custom_match'] ) )
            {
                $matchFound = false;
                foreach ( $matchFile['custom_match'] as $customMatch )
                {
                    $matchOverride = true;
                    if ( count( $customMatch['conditions'] ) > 0 )
                    {
                        foreach ( array_keys( $customMatch['conditions'] ) as $conditionKey )
                        {
                            // Create special substring match for subtree override
                            if ( $conditionKey == 'url_alias' )
                            {
                                if ( strpos( $matchKeys['url_alias'], $customMatch['conditions'][$conditionKey] ) === 0 )
                                {
                                }
                                else
                                {
                                    $matchOverride = false;
                                }
                            }
                            else if ( isset( $matchKeys[$conditionKey] ) and
                                      isset( $customMatch['conditions'][$conditionKey] ) )
                            {
                                if ( is_array( $matchKeys[$conditionKey] ) )
                                {
                                    if ( !in_array( $customMatch['conditions'][$conditionKey], $matchKeys[$conditionKey] ) )
                                    {
                                        $matchOverride = false;
                                    }
                                }
                                else if ( $matchKeys[$conditionKey] != $customMatch['conditions'][$conditionKey] )
                                {
                                    $matchOverride = false;
                                }
                            }
                            else
                            {
                                $matchOverride = false;
                            }
                        }
                        if ( $matchOverride == true )
                        {
                            $match['file'] = $customMatch['match_file'];
                            $matchFound = true;
                            break;
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                        // Default match without conditions
                        $match['file'] = $customMatch['match_file'];
                        $matchFound = true;
                    }
                }
                if ( !$matchFound )
                    $match['file'] = $matchFile['base_dir'] . $matchFile['template'];
            }
            else
            {
                $match['file'] = $matchFile['base_dir'] . $matchFile['template'];
            }
        }
        eZDebug::accumulatorStop( 'override_cache' );
        if ( isset( $match ) )
        {
            $file = $match["file"];

            $matchedKeys = array();
            $usedKeys = array();
            foreach ( $matchKeys as $matchKeyName => $matchKeyValue )
            {
                $usedKeys[$matchKeyName] = $matchKeyValue;
            }
            $extraParameters['ezdesign:used_keys'] = $usedKeys;
            $extraParameters['ezdesign:matched_keys'] = $matchedKeys;
            $tpl->setVariable( 'used', $usedKeys, 'DesignKeys' );
            $tpl->setVariable( 'matched', $matchedKeys, 'DesignKeys' );
            $resourceData['template-filename'] = $file;
            $result = eZTemplateFileResource::handleResourceData( $tpl, $this, $resourceData, $method, $extraParameters );
        }
        else
        {
            $result = false;
        }
        $this->Keys = array_pop( $this->KeyStack );
        return $result;
    }
859739
public function findRelatedSourceRecords(int $sourceId, int $limit = null): array
    {
        /** @var Relations $relations */
        $relations = $this->framework->getAdapter(Relations::class);

        if (false === ($relation = $relations->getRelation($this->sourceTable, $this->sourceField))) {
            throw new \RuntimeException(\sprintf('The field %s.%s is not related', $this->sourceTable, $this->sourceField));
        }

        /** @var Model $relationsModel */
        $relationsModel = $this->framework->getAdapter(Model::class);

        $tagIds = $relationsModel->getRelatedValues($this->sourceTable, $this->sourceField, $sourceId);
        $tagIds = \array_values(\array_unique($tagIds));
        $tagIds = \array_map('intval', $tagIds);

        // Return if there are no tags
        if (0 === \count($tagIds)) {
            return [];
        }

        $query = \sprintf(
            'SELECT %s, COUNT(*) AS relevance FROM %s WHERE %s IN (%s) AND %s != ? GROUP BY %s ORDER BY relevance DESC',
            $relation['reference_field'],
            $relation['table'],
            $relation['related_field'],
            \implode(',', $tagIds),
            $relation['reference_field'],
            $relation['reference_field']
        );

        // Set the limit
        if ($limit > 0) {
            $query .= \sprintf(' LIMIT %s', $limit);
        }

        $related = [];

        // Generate the related records
        foreach ($this->db->fetchAll($query, [$sourceId]) as $record) {
            $related[$record[$relation['reference_field']]] = [
                'total' => \count($tagIds),
                'found' => $record['relevance'],
                'prcnt' => ($record['relevance'] / \count($tagIds)) * 100,
            ];
        }

        return $related;
    }
1225140
public function getEventsForTimeline($contactSourceId, array $options = [], $count = false)
    {
        $query = $this->getEntityManager()->getConnection()->createQueryBuilder()
            ->from(MAUTIC_TABLE_PREFIX.'contactsource_events', 'c')
            ->select('c.*');

        $query->where(
            $query->expr()->eq('c.contactsource_id', ':contactSourceId')
        )
            ->setParameter('contactSourceId', $contactSourceId);

        if (null != Request::createFromGlobals()->get('campaign') && !empty(Request::createFromGlobals()->get('campaign'))) {
            $campaignId = Request::createFromGlobals()->get('campaign');
        } elseif (isset($options['filters']['campaignId']) && !empty($options['filters']['campaignId'])) {
            $campaignId = $options['filters']['campaignId'];
        }
        if (isset($campaignId) && !empty($campaignId)) {
            $query->join(
                'c',
                'contactsource_stats', 's',
                'c.contactsource_id = s.contactsource_id AND c.contact_id = s.contact_id'
            )
            ->andWhere($query->expr()->eq('s.campaign_id', ':campaignId'))
            ->setParameter('campaignId', $campaignId);
        }

        if (isset($options['filters']['message']) && !empty($options['filters']['message'])) {
            $query->andWhere('c.message LIKE :message')
                ->setParameter('message', '%'.trim($options['filters']['message']).'%');
        }
        if (isset($options['filters']['contact_id']) && !empty($options['filters']['contact_id'])) {
            $query->andWhere('c.contact_id = :contact')
                ->setParameter('contact', trim($options['filters']['contact_id']));
        }
        if (isset($options['filters']['type']) && !empty($options['filters']['type'])) {
            $query->andWhere('c.type = :type')
                ->setParameter('type', trim($options['filters']['type']));
        }

        if (isset($options['dateFrom'])) {
            $query->andWhere('c.date_added >= :dateFrom')
                ->setParameter(
                    'dateFrom',
                    $options['dateFrom']->setTimeZone(new \DateTimeZone('UTC'))->format('Y-m-d H:i:s')
                );
        }

        if (!empty($options['fromDate']) && !empty($options['toDate'])) {
            $query->andWhere('c.date_added BETWEEN FROM_UNIXTIME(:dateFrom) AND FROM_UNIXTIME(:dateTo)')
                ->setParameter('dateFrom', $options['fromDate']->getTimestamp())
                ->setParameter('dateTo', $options['toDate']->getTimestamp());
        } elseif (!empty($options['fromDate'])) {
            $query->andWhere($query->expr()->gte('c.date_added', 'FROM_UNIXTIME(:dateFrom)'))
                ->setParameter('dateFrom', $options['fromDate']->getTimestamp());
        } elseif (!empty($options['toDate'])) {
            $query->andWhere($query->expr()->lte('c.date_added', 'FROM_UNIXTIME(:dateTo)'))
                ->setParameter('dateTo', $options['toDate']->getTimestamp());
        }

        if (isset($options['order']) && !empty($options['order'])) {
            list($orderBy, $orderByDir) = $options['order'];
            $query->orderBy('c.'.$orderBy, $orderByDir);
        }

        if (!empty($options['limit'])) {
            $query->setMaxResults($options['limit']);
            if (!empty($options['start'])) {
                $query->setFirstResult($options['start']);
            }
        }

        $results = $query->execute()->fetchAll();

        if (!empty($options['paginated'])) {
            // Get a total count along with results
            $query->resetQueryParts(['select', 'orderBy'])
                ->setFirstResult(null)
                ->setMaxResults(null)
                ->select('count(*)');
            // unjoin if possible for perf reasons
            if ($count && (!isset($campaignId) || empty($campaignId))) {
                $query->resetQueryParts(['join']);
            }

            $total = $query->execute()->fetchColumn();

            return [
                'total'   => $total,
                'results' => $results,
            ];
        }

        return $results;
    }
751747
protected function validateLimit(): void
    {
        $limit = $this->getArrayValue($this->joryArray, ['lmt', 'limit']);

        // No limit set, that's ok. return.
        if ($limit === null) {
            return;
        }

        if (! is_int($limit)) {
            throw new JoryException('The limit parameter should be an integer value. (Location: '.$this->address.'limit)');
        }
    }
403317
public static PoliciesCache fromSources(final Iterable<CacheableYamlSource> sources) {
        return fromSourceProvider(
                new SourceProvider() {
                    @Override
                    public Iterator<CacheableYamlSource> getSourceIterator() {
                        return sources.iterator();
                    }
                }
        );
    }
944691
private function parseFieldsProvided()
    {
        if (null === $this->fieldsProvided) {
            $fieldsProvided = [];
            foreach ($this->request->request->all() as $k => $v) {
                $k = trim($k);
                if ('' !== $k) {
                    $v = trim($v);
                    if ('' !== $v) {
                        $fieldsProvided[$k] = $v;
                    }
                }
            }
            // Some inputs do not pertain to contact fields.
            unset($fieldsProvided['token'], $fieldsProvided['sourceId'], $fieldsProvided['campaignId']);
            $this->fieldsProvided = $fieldsProvided;
        }
        if (!count($this->fieldsProvided)) {
            throw new ContactSourceException(
                'No fields were posted. Did you mean to do that?',
                Codes::HTTP_I_AM_A_TEAPOT,
                null,
                Stat::TYPE_INVALID
            );
        }

        return $this;
    }
241296
public function setSource($source): void
    {
        if (!\is_array($source) && !($source instanceof \ArrayAccess)) {
            throw new Grid\GridException('Source of `ArraySource` should be array or implement ArrayAccess interface');
        }
        parent::setSource($source);
    }
173264
public function getCampaignSourceStatsData($params, $bySource = false, $cache_dir = __DIR__, $realtime = true)
    {
        $statBuilder = $this->getEntityManager()->getConnection()->createQueryBuilder();
        $statBuilder
            ->select(
                'ss.campaign_id',
                'ss.date_added',
                'c.is_published',
                'c.name',
                'SUM(IF(ss.type IS NULL                     , 0, 1)) AS received',
                "SUM(IF(ss.type IN ('accepted' , 'scrubbed'), 0, 1)) AS rejected",
                "SUM(IF(ss.type = 'accepted'                , 1, 0)) AS converted",
                "SUM(IF(ss.type = 'scrubbed'                , 1, 0)) AS scrubbed",
                'IFNULL(clc.cost, 0)                                 AS cost',
                'IFNULL(clr.revenue, 0)                              AS revenue'
            )
            ->from(MAUTIC_TABLE_PREFIX.'contactsource_stats', 'ss')
            ->join('ss', MAUTIC_TABLE_PREFIX.'leads', 'l', 'l.id = ss.contact_id')
            ->join('ss', MAUTIC_TABLE_PREFIX.'campaigns', 'c', 'c.id = ss.campaign_id')
            ->where('ss.type <> :invalid AND l.date_identified BETWEEN :dateFrom AND :dateTo')
            ->groupBy('ss.campaign_id')
            ->orderBy('COUNT(ss.campaign_id)', 'ASC');
        $costBuilder = $this->getEntityManager()->getConnection()->createQueryBuilder();
        $costBuilder
            ->select('lc.campaign_id', 'SUM(lc.cost) AS cost')
            ->from(MAUTIC_TABLE_PREFIX.'contact_ledger', 'lc')
            ->groupBy('lc.campaign_id');
        $costJoinCond = 'clc.campaign_id = ss.campaign_id AND ss.date_added BETWEEN :dateFrom AND :dateTo';
        $revBuilder   = $this->getEntityManager()->getConnection()->createQueryBuilder();
        $revBuilder
            ->select('lr.campaign_id', 'SUM(lr.revenue) AS revenue')
            ->from(MAUTIC_TABLE_PREFIX.'contact_ledger', 'lr')
            ->groupBy('lr.campaign_id');
        $revJoinCond = 'clr.campaign_id = ss.campaign_id AND ss.date_added BETWEEN :dateFrom AND :dateTo';
        if ($bySource) {
            $statBuilder
                ->addSelect('ss.contactsource_id', 'cs.name as source', 'cs.utm_source as utm_source')
                ->join('ss', MAUTIC_TABLE_PREFIX.'contactsource', 'cs', 'cs.id = ss.contactsource_id')
                ->addGroupBy('ss.contactsource_id, cs.utm_source');
        }
        $costBuilder
            ->addSelect('sc.contactsource_id')
            ->innerJoin(
                'lc',
                'contactsource_stats',
                'sc',
                'lc.campaign_id = sc.campaign_id AND lc.contact_id = sc.contact_id AND sc.date_added BETWEEN :dateFrom AND :dateTo'
            )
            ->addGroupBy('sc.contactsource_id');
        $costJoinCond .= ' AND clc.contactsource_id = ss.contactsource_id';
        $revBuilder
            ->addSelect('sr.contactsource_id')
            ->innerJoin(
                'lr',
                'contactsource_stats',
                'sr',
                'lr.campaign_id = sr.campaign_id AND lr.contact_id = sr.contact_id AND sr.date_added BETWEEN :dateFrom AND :dateTo'
            )
            ->addGroupBy('sr.contactsource_id');
        $revJoinCond .= ' AND clr.contactsource_id = ss.contactsource_id';

        $statBuilder
            ->leftJoin('ss', '('.$costBuilder->getSQL().')', 'clc', $costJoinCond)
            ->leftJoin('ss', '('.$revBuilder->getSQL().')', 'clr', $revJoinCond);
        $statBuilder
            ->setParameter('invalid', 'invalid')
            ->setParameter('dateFrom', $params['dateFrom'])
            ->setParameter('dateTo', $params['dateTo']);
        if (isset($params['limit']) && (0 < $params['limit'])) {
            $statBuilder->setMaxResults($params['limit']);
        }
        $results         = ['rows' => []];
        $resultsWithKeys = [];

        // setup cache
        $cache = new FilesystemCache($cache_dir.'/sql');
        $statBuilder->getConnection()->getConfiguration()->setResultCacheImpl($cache);
        $stmt       = $statBuilder->getConnection()->executeCacheQuery(
            $statBuilder->getSQL(),
            $statBuilder->getParameters(),
            $statBuilder->getParameterTypes(),
            new QueryCacheProfile(900, 'dashboard-revenue-queries', $cache)
        );
        $financials = $stmt->fetchAll();
        $stmt->closeCursor();

        // get utm_source data for leads with NO Contact Source Stat record (direct API, manually created, imports etc)
        $otherFinancials = $this->getAlternateCampaignSourceData($params, $bySource, $cache_dir, $realtime);
        $financials      = array_merge($financials, $otherFinancials);

        if (empty($financials)) {
            // no data for the time period, so return empty row values
            $financials[0] = [
                'is_published' => 0,
                'campaign_id'  => null,
                'name'         => null,
                'received'     => 0,
                'scrubbed'     => 0,
                'rejected'     => 0,
                'converted'    => 0,
                'revenue'      => 0,
                'cost'         => 0,
            ];
            if ($bySource) {
                $financials[0]['contactsource_id'] = null;
                $financials[0]['source']           = null;
                $financials[0]['utm_source']       = ''; // cant be null
            }
        }

        foreach ($financials as $financial) {
            // must be ordered as active, id, name, received, converted, revenue, cost, gm, margin, ecpm
            $financial['revenue']      = number_format(floatval($financial['revenue']), 2, '.', ',');
            $financial['cost']         = number_format(floatval($financial['cost']), 2, '.', ',');
            $financial['gross_income'] = number_format(
                (float) $financial['revenue'] - (float) $financial['cost'],
                2,
                '.',
                ','
            );

            if ($financial['gross_income'] > 0) {
                $financial['gross_margin'] = number_format(
                    100 * $financial['gross_income'] / $financial['revenue'],
                    0,
                    '.',
                    ','
                );
                $financial['ecpm']         = number_format((float) $financial['gross_income'] / 1000, 4, '.', ',');
            } else {
                $financial['gross_margin'] = 0;
                $financial['ecpm']         = 0;
            }

            $result = [
                $financial['is_published'],
                $financial['campaign_id'],
                $financial['name'],
            ];
            if ($bySource) {
                $result[] = $financial['contactsource_id'];
                $result[] = $financial['source'];
                $result[] = $financial['utm_source'];
            }
            $result[] = $financial['received'];
            $result[] = $financial['scrubbed'];
            $result[] = $financial['rejected'];
            $result[] = $financial['converted'];
            $result[] = $financial['revenue'];
            $result[] = $financial['cost'];
            $result[] = $financial['gross_income'];
            $result[] = $financial['gross_margin'];
            $result[] = $financial['ecpm'];

            $results['rows'][] = $result;
            $resultsWithKeys[] = $financial;
        }

        return true == $realtime ? $results : $resultsWithKeys;
    }
477988
public function addStat(
        ContactSource $contactSource = null,
        $type = null,
        $contact = 0,
        $attribution = 0,
        $campaign = 0
    ) {
        $stat = new Stat();
        if ($contactSource) {
            $stat->setContactSource($contactSource);
        }
        $stat->setDateAdded(new \DateTime());
        $stat->setType($type);
        if ($contact) {
            $stat->setContact($contact);
        }
        if ($attribution) {
            $stat->setAttribution($attribution);
        }
        if ($campaign) {
            $stat->setCampaign($campaign);
        }

        $this->getStatRepository()->saveEntity($stat);
    }
524231
private function determineSourceFolder()
	{
		$this->sourceFolder = JPATH_BASE . "/" . $this->getJConfig()->source;

		if (!is_dir($this->sourceFolder))
		{
			$this->say('Warning - Directory: ' . $this->sourceFolder . ' is not available');
		}
	}
1073400
public function parseSourceCampaignSettings()
    {
        if (isset($this->campaignSettingsParsed[$this->campaignId])) {
            // Campaign settings have already been parsed for this campaign/session, likely due to a batch import.
            return;
        }

        // Check that the campaign is in the whitelist for this source.
        $campaignSettings = $this->campaignSettingsModel->setContactSource($this->contactSource)
            ->getCampaignSettingsById($this->campaignId);

        // @todo - Support or thwart multiple copies of the same campaign, should it occur. In the meantime...
        $campaignSettings = reset($campaignSettings);
        if (
            !$campaignSettings
            && !$this->imported
            && !$this->contactSource->getInternal()
        ) {
            throw new ContactSourceException(
                'The campaignId supplied is not currently in the permitted list of campaigns for this source.',
                Codes::HTTP_GONE,
                null,
                Stat::TYPE_INVALID,
                'campaignId'
            );
        }
        // Establish parameters from campaign settings; skip some settings on contact import from file.
        if (!$this->imported) {
            // Establish defaults (especially for allCampaigns).
            $this->realTime  = isset($campaignSettings->realTime) ? boolval($campaignSettings->realTime) : true;
            $this->limits    = isset($campaignSettings->limits) ? $campaignSettings->limits : [];
            $this->scrubRate = isset($campaignSettings->scrubRate) ? intval($campaignSettings->scrubRate) : 0;
        }
        $this->cost      = isset($campaignSettings->cost) ? (abs(floatval($campaignSettings->cost))) : 0;
        $this->utmSource = !empty($this->contactSource->getUtmSource()) ? $this->contactSource->getUtmSource() : '';

        // Apply field overrides.
        if ($this->utmSource) {
            $this->fieldsProvided['utm_source'] = $this->utmSource;
        }
        $this->addTrace('contactSourceRealTime', $this->realTime);
        $this->addTrace('contactSourceCost', $this->cost);
        $this->addTrace('contactSourceUtmSource', $this->utmSource);

        $this->campaignSettingsParsed[$this->campaignId] = true;
    }
907799
public function initEventLog(ContactSource $source, Contact $contact, $lineNumber)
    {
        $eventLog = new ContactEventLog();
        $eventLog->setUserId($source->getCreatedBy())
            ->setUserName($source->getCreatedByUser())
            ->setBundle('lead')
            ->setObject('import')
            ->setObjectId($contact->getId())
            ->setProperties(
                [
                    'line' => $lineNumber,
                    'file' => $source->getOriginalFile(),
                ]
            );

        return $eventLog;
    }