@param       $contactSourceId
@param int   $contactId
@param array $options

@return array
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;
    }
1300474
public function getPreferencesForContact($contactId)
    {
        $url = $this->getApiEndpoint() . "/v2/contact/" . $contactId . "/preferences";

        $response = $this->setUrl($url)
            ->setVerb('GET')
            ->execute();

        if (isset($response->message)) {
            $this->helper->log('GET PREFERENCES FOR CONTACT: ' . $response->message);
        }

        return $response;
    }
1211989
protected function getContactcd($contactId)
    {
        $pattern = '//epp:epp/epp:response/epp:resData/contact:chkData/contact:cd[contact:id[php:functionString("XPath\quote", text()) = \'%s\']]';
        $query = sprintf($pattern, XPath\quote($contactId));
        $node = $this->getFirst($query);

        if ($node === null) {
            throw new UnexpectedValueException(sprintf('Contact with ID [%s] not found.', $contactId));
        }

        return $node;
    }
1040811
public function addCampaignAction($contactSourceId)
    {
        $campaignSettingsModel = $this->container->get('mautic.contactsource.model.campaign_settings');
        $parameters            = $this->request->request->all();

        if (!isset($parameters['campaignId']) || empty($parameters['campaignId'])) {
            return $this->notFound();
        }

        $valid = $this->validateBatchPayload($parameters);
        if ($valid instanceof Response) {
            return $valid;
        }

        /** var ContactSource $sourceEntity */
        $sourceEntity = $this->model->getEntity($contactSourceId);

        if (!$this->checkEntityAccess($sourceEntity, 'edit')) {
            return $this->accessDenied();
        }

        $campaignModel  = $this->container->get('mautic.campaign.model.campaign');
        $campaignEntity = $campaignModel->getEntity($parameters['campaignId']);
        if (empty($campaignEntity)) {
            return $this->returnError('mautic.contactsource.api.error.error.add_campaign.not_found', Codes::HTTP_BAD_REQUEST);
        }
        $campaignSettingsModel->setContactSource($sourceEntity);
        $campaignSettings = $campaignSettingsModel->getCampaignSettings();
        $existingCampaign = $campaignSettingsModel->getCampaignSettingsById($parameters['campaignId']);

        $requestCampaign             = new \stdClass();
        $requestCampaign->campaignId = $parameters['campaignId'];
        $requestCampaign->cost       = isset($parameters['cost']) ? number_format(
            (float) $parameters['cost'],
            3,
            '.',
            ''
        ) : 0;
        $requestCampaign->realTime   = isset($parameters['realTime']) && ('false' === $parameters['realTime'] || '0' === $parameters['realTime']) ? false : true;
        $requestCampaign->scrubRate  = isset($parameters['scrubRate']) ? (int) $parameters['scrubRate'] : 0;
        $requestCampaign->limits     = [];

        if (empty($existingCampaign)) {
            $campaignSettings->campaigns[] = $requestCampaign;
        } else {
            return $this->returnError('mautic.contactsource.api.add_campaign.bad_request', Codes::HTTP_BAD_REQUEST);
        }
        $campaignSettingsJSON = json_encode($campaignSettings);
        $sourceEntity->setCampaignSettings($campaignSettingsJSON);

        $this->model->saveEntity($sourceEntity);

        $headers = [];
        //return the newly created entities location if applicable

        $route               = (null !== $this->get('router')->getRouteCollection()->get(
                'mautic_api_'.$this->entityNameMulti.'_getone'
            ))
            ? 'mautic_api_'.$this->entityNameMulti.'_getone' : 'mautic_api_get'.$this->entityNameOne;
        $headers['Location'] = $this->generateUrl(
            $route,
            array_merge(['id' => $sourceEntity->getId()], $this->routeParams),
            true
        );

        $this->preSerializeEntity($sourceEntity, 'edit');

        $view = $this->view([$this->entityNameOne => $sourceEntity], Codes::HTTP_OK, $headers);

        $this->setSerializationContext($view);

        return $this->handleView($view);
    }
115090
function ContactsGroupsMembersAdd(options, groupId, contactId) {
    ActionAbstract.call(this, options);
    this._groupId = groupId;
    this._contactId = contactId;
}
334451
private function sendSubscribedContactsToAutomation($contactsArray, $websiteId)
    {
        if (!empty($contactsArray) &&
            $this->checkCampignEnrolmentActive($this->programId, $websiteId)
        ) {
            $result = $this->sendContactsToAutomation(
                array_values($contactsArray),
                $websiteId
            );
            //check for error message
            if (isset($result->message)) {
                $this->programStatus = 'Failed';
                $this->programMessage = $result->message;
            }
            //program is not active
        } elseif ($this->programMessage
            == 'Error: ERROR_PROGRAM_NOT_ACTIVE '
        ) {
            $this->programStatus = 'Deactivated';
        }
    }
1001841
public function getContactAddressesFromContactId( $ContactEntryId){
        $service = sprintf( self::API_CONTACT_ADDRESSES, $ContactEntryId);
        $rest = $this->getService( $service);
        $rest->GET();

        return $rest->getResultAsArray( models\Call\ContactAddress::class);
    }
1282262
function ContactsGroupsMembersGet(options, groupId, contactId) {
    ActionAbstract.call(this, options);
    this._groupId = groupId;
    this._contactId = contactId;
}
1321595
public function sendToContact($id, $contactId, $parameters = array())
    {
        return $this->makeRequest($this->endpoint.'/'.$id.'/contact/'.$contactId.'/send', $parameters, 'POST');
    }
83006
protected function getAllEngagements(
        array $contactSources,
        array $filters = null,
        array $orderBy = null,
        $page = 1,
        $limit = 25
    ) {
        $session = $this->get('session');

        if (null == $filters) {
            $filters = $session->get(
                'mautic.plugin.timeline.filters',
                [
                    'search'        => '',
                    'includeEvents' => [],
                    'excludeEvents' => [],
                ]
            );
        }
        $filters = $this->sanitizeEventFilter(InputHelper::clean($this->request->get('filters', [])));

        if (null == $orderBy) {
            if (!$session->has('mautic.plugin.timeline.orderby')) {
                $session->set('mautic.plugin.timeline.orderby', 'timestamp');
                $session->set('mautic.plugin.timeline.orderbydir', 'DESC');
            }

            $orderBy = [
                $session->get('mautic.plugin.timeline.orderby'),
                $session->get('mautic.plugin.timeline.orderbydir'),
            ];
        }

        // prepare result object
        $result = [
            'events'   => [],
            'filters'  => $filters,
            'order'    => $orderBy,
            'types'    => [],
            'total'    => 0,
            'page'     => $page,
            'limit'    => $limit,
            'maxPages' => 0,
        ];

        // get events for each contact
        foreach ($contactSources as $contactSource) {
            //  if (!$contactSource->getEmail()) continue; // discard contacts without email

            /** @var ContactSourceModel $model */
            $model       = $this->getModel('contactSource');
            $engagements = $model->getEngagements($contactSource, $filters, $orderBy, $page, $limit);
            $events      = $engagements['events'];
            $types       = $engagements['types'];

            // inject contactSource into events
            foreach ($events as &$event) {
                $event['contactSourceId']    = $contactSource->getId();
                $event['contactSourceEmail'] = $contactSource->getEmail();
                $event['contactSourceName']  = $contactSource->getName() ? $contactSource->getName(
                ) : $contactSource->getEmail();
            }

            $result['events'] = array_merge($result['events'], $events);
            $result['types']  = array_merge($result['types'], $types);
            $result['total'] += $engagements['total'];
        }

        $result['maxPages'] = ($limit <= 0) ? 1 : round(ceil($result['total'] / $limit));

        usort($result['events'], [$this, 'cmp']); // sort events by

        // now all events are merged, let's limit to   $limit
        array_splice($result['events'], $limit);

        $result['total'] = count($result['events']);

        return $result;
    }
101070
public function updateContactField($contactFieldId, array $data = [])
	{
		return $this->sendRequest(
			$this->createRequest('PATCH', sprintf('contact_fields/%d', $contactFieldId), [], $data)
		);
	}
865180
public function getSourcesByClient(
        $contactClientId,
        \DateTime $dateFrom = null,
        \DateTime $dateTo = null,
        $type = null
    ) {
        $q = $this->getEntityManager()->getConnection()->createQueryBuilder();

        $q->select('distinct(s.utm_source)')
            ->from(MAUTIC_TABLE_PREFIX.'contactclient_stats', 's')
            ->where(
                $q->expr()->eq('s.contactclient_id', (int) $contactClientId)
            );

        if (empty($type)) {
            $q->andWhere('s.type !=""');
        } else {
            $q->andWhere('s.type = :type')
                ->setParameter('type', $type);
        }

        if ($dateFrom && $dateTo) {
            $q->andWhere('s.date_added BETWEEN FROM_UNIXTIME(:dateFrom) AND FROM_UNIXTIME(:dateTo)')
                ->setParameter('dateFrom', $dateFrom->getTimestamp(), \PDO::PARAM_INT)
                ->setParameter('dateTo', $dateTo->getTimestamp(), \PDO::PARAM_INT);
        }

        $utmSources = [];
        foreach ($q->execute()->fetchAll() as $row) {
            $utmSources[] = $row['utm_source'];
        }

        return $utmSources;
    }
531066
public function evaluateAllCampaignLimits(ContactSource $contactSource)
    {
        $container = $this->dispatcher->getContainer();
        /** @var CampaignSettings $campaignSettingsModel */
        $campaignModel         = $container->get('mautic.campaign.model.campaign');
        $campaignSettingsModel = $container->get('mautic.contactsource.model.campaign_settings');
        $campaignSettingsModel->setContactSource($contactSource);
        $campaignSettingsAll = $campaignSettingsModel->getCampaignSettings();

        $campaignLimits = [];
        if (!empty($campaignSettingsAll->campaigns)) {
            /* @var \MauticPlugin\MauticContactSourceBundle\Model\Cache $cacheModel */
            $cacheModel = $container->get('mautic.contactsource.model.cache');
            $cacheModel->setContactSource($contactSource);

            foreach ($campaignSettingsAll->campaigns as $campaign) {
                // Establish parameters from campaign settings.
                if (!empty($campaign->limits) && isset($campaign->campaignId)) {
                    $id                = intval($campaign->campaignId);
                    $name              = $campaignModel->getEntity($id)->getName();
                    $limitRules        = new \stdClass();
                    $limitRules->rules = $campaign->limits;
                    $limits            = $cacheModel->evaluateLimits($limitRules, $id, false, true);
                    if ($limits) {
                        $campaignLimits[] = [
                            'campaignId' => $id,
                            'limits'     => $limits,
                            'name'       => $name,
                            'link'       => $this->buildUrl(
                                'mautic_campaign_action',
                                ['objectAction' => 'view', 'objectId' => $id]
                            ),
                        ];
                    }
                }
            }
        }

        return $campaignLimits;
    }
357
public static function add_contact(int $userid, int $contactid) {
        global $DB;

        $messagecontact = new \stdClass();
        $messagecontact->userid = $userid;
        $messagecontact->contactid = $contactid;
        $messagecontact->timecreated = time();
        $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);

        $eventparams = [
            'objectid' => $messagecontact->id,
            'userid' => $userid,
            'relateduserid' => $contactid,
            'context' => \context_user::instance($userid)
        ];
        $event = \core\event\message_contact_added::create($eventparams);
        $event->add_record_snapshot('message_contacts', $messagecontact);
        $event->trigger();
    }
440331
public function addContacts($contacts, $id = null)
    {
        if (!is_array($contacts)) {
            throw new  InvalidArgumentException('No array with contacts provided.');
        }
        if (is_null($id)) {
            throw new InvalidArgumentException('No group id provided.');
        }

        $ResourceName = $this->resourceName . ($id ? '/' . $id . '/contacts' : null);
        $contacts = json_encode($contacts);
        list($responseStatus, , $responseBody) = $this->HttpClient->performHttpRequest(
            Common\HttpClient::REQUEST_PUT,
            $ResourceName,
            false,
            $contacts
        );
        if ($responseStatus !== Common\HttpClient::HTTP_NO_CONTENT) {
            return json_decode($responseBody);
        }
    }
1176242
public function createContactInList($contactListId, array $data = [])
	{
		return $this->sendRequest(
			$this->createRequest('POST', sprintf('contact_lists/%d/contacts', $contactListId), [], $data)
		);
	}
22298
function Contacts(options) {
    ActionFactoryAbstract.call(this, options);

    this.groups = new ContactsGroups(options);
    this.fields = new ContactsFields(options);
}