Add contact to a campaign, and optionally run in real-time.

@param Campaign $campaign
@param array    $contacts
@param bool     $manuallyAdded

@throws \Exception
559271
private function addContactsToCampaign(
        Campaign $campaign,
        $contacts = [],
        $manuallyAdded = false
    ) {
        foreach ($contacts as $contact) {
            $campaignContact = new CampaignContact();
            $alreadyExists   = false;
            if (!null == $contact->getDateModified(
                )) { // see if New Contact b/c isNew() is unreliable on PostSave Event
                $leadRepository = $this->em->getRepository('MauticCampaignBundle:Lead');
                $alreadyExists  = $leadRepository->checkLeadInCampaigns(
                    $contact,
                    ['campaigns' => [$campaign->getId()]]
                );
            }
            if (!$alreadyExists) {
                $campaignContact->setCampaign($campaign);
                $campaignContact->setDateAdded(new \DateTime());
                $campaignContact->setLead($contact);
                $campaignContact->setManuallyAdded($manuallyAdded);
                $saved = $this->campaignModel->saveCampaignLead($campaignContact);
            }

            // @todo - Support non realtime event firing.
            // if (!$realTime) {
            //     // Only trigger events if not in realtime where events would be followed directly.
            //     if ($saved && $this->campaignModel->hasListeners(CampaignEvents::CAMPAIGN_ON_LEADCHANGE)) {
            //         $event = new CampaignLeadChangeEvent($campaign, $contact, 'added');
            //         $this->dispatcher->dispatch(CampaignEvents::CAMPAIGN_ON_LEADCHANGE, $event);
            //         unset($event);
            //     }
            // }
            $this->em->detach($campaignContact);
        }
        unset($campaign, $campaignContact, $contacts);
    }
829358
public function addEntry(
        Lead $lead,
        Campaign $campaign = null,
        $actor = null,
        $activity = null,
        $cost = null,
        $revenue = null,
        $memo = null
    ) {
        if (null === $lead) {
            $this->logger->warning('Cannot create a ledger entry without a Contact');

            return;
        }

        $bundleName = $className = $objectId = null;

        if (is_array($actor)) {
            list($bundleName, $className, $objectId) = $this->getActorFromArray($actor);
        } elseif (is_object($actor)) {
            list($bundleName, $className, $objectId) = $this->getActorFromObject($actor);
        }

        $entry = new LedgerEntry();
        $entry
            ->setDateAdded(new \DateTime())
            ->setContact($lead)
            ->setCampaign($campaign)
            ->setBundleName($bundleName)
            ->setClassName($className)
            ->setObjectId($objectId)
            ->setActivity($activity)
            ->setMemo($memo)
            ->setCost($cost)
            ->setRevenue($revenue);

        $this->getRepository()->saveEntity($entry);
        $this->em->clear('MauticPlugin\MauticContactLedgerBundle\Entity\LedgerEntry');
    }
142265
private function setCampaignSettings($campaignSettings = null)
    {
        if (!$campaignSettings) {
            throw new \Exception('Campaigns have not been mapped to this source.');
        }

        $jsonHelper             = new JSONHelper();
        $this->campaignSettings = $jsonHelper->decodeObject($campaignSettings, 'CampaignSettings');

        return $this;
    }
1231280
private function processRealTime()
    {
        if (!$this->realTime || !$this->campaign || !$this->contact) {
            return;
        }

        $this->campaignExecutioner->execute($this->campaign, [$this->contact->getId()]);
        $this->contactCampaigns[$this->campaign->getId()] = true;

        // Retrieve events fired by MauticContactClientBundle (if any)
        $events = $this->session->get('mautic.contactClient.events', []);
        if (!empty($events)) {
            $this->eventErrors = [];
            foreach ($events as $event) {
                if (isset($event['contactId']) && $event['contactId'] !== $this->contact->getId()) {
                    // For not ignore/exclude all events not relating to the current contact.
                    continue;
                }
                $this->events[] = $event;
                if (!empty($event['error'])) {
                    $eventName = !empty($event['name']) ? $event['name'] : '';
                    if (!is_array($event['errors'])) {
                        $event['errors'] = [$event['errors']];
                    }
                    $this->eventErrors[] = $eventName.' ('.$event['id'].'): '.implode(', ', $event['errors']);
                }
                if (isset($event['valid']) && $event['valid']) {
                    // One valid Contact Client was found to accept the lead.
                    $this->status = Stat::TYPE_ACCEPTED;
                    $this->valid  = true;
                    break;
                }
            }
        }

        // There was no accepted client hit, consider this a rejection.
        // @todo - This is highly dependent on the contact client plugin, thus should be made configurable, or we can make the realTime mode only available to those with both plugins.
        if (!$this->valid) {
            // If one or more clients were found, but none accepted.
            // This should be considered a rejected contact.
            $this->status = Stat::TYPE_REJECT;
        }

        // Apply scrub only to accepted contacts in real-time mode after evaluation.
        if ($this->valid && $this->isScrubbed()) {
            $this->status = Stat::TYPE_SCRUBBED;
            $this->valid  = false;
        }
    }
826885
private static function updateCampaignDsaSetting(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        $campaignId,
        DSAFeedDetails $feedDetails
    ) {
        $campaignService = $adWordsServices->get($session, CampaignService::class);

        // Create selector.
        $selector = new Selector();
        $selector->setFields(['Id', 'Settings']);
        $selector->setPredicates(
            [new Predicate('CampaignId', PredicateOperator::IN, [$campaignId])]
        );

        $result = $campaignService->get($selector);
        if (empty($result->getEntries()) || $result->getTotalNumEntries() === 0) {
            throw new InvalidArgumentException(
                'No campaign found with ID: ' . $campaignId
            );
        }
        $campaign = $result->getEntries()[0];

        if ($campaign->getSettings() === null) {
            throw new InvalidArgumentException(
                'Campaign with ID ' . $campaignId . ' is not a DSA campaign.'
            );
        }

        $dsaSetting = null;
        foreach ($campaign->getSettings() as $setting) {
            if ($setting instanceof DynamicSearchAdsSetting) {
                $dsaSetting = $setting;
                break;
            }
        }

        if ($dsaSetting === null) {
            throw new InvalidArgumentException(
                'Campaign with ID ' . $campaignId . ' is not a DSA campaign.'
            );
        }

        // Use a page feed to specify precisely which URLs to use with your
        // Dynamic Search Ads.
        $pageFeed = new PageFeed();
        $pageFeed->setFeedIds([$feedDetails->feedId]);
        $dsaSetting->setPageFeed($pageFeed);

        // Optional: Specify whether only the supplied URLs should be used with your
        // Dynamic Search Ads.
        $dsaSetting->setUseSuppliedUrlsOnly(true);

        $updatedCampaign = new Campaign();
        $updatedCampaign->setId($campaignId);
        $updatedCampaign->setSettings($campaign->getSettings());

        $operation = new CampaignOperation();
        $operation->setOperand($updatedCampaign);
        $operation->setOperator(Operator::SET);

        // Update the campaign on the server and print out some information.
        $result = $campaignService->mutate([$operation]);
        $updatedCampaign = $result->getValue()[0];
        printf(
            "DSA page feed for campaign ID %d was updated with feed ID %d.\n",
            $updatedCampaign->getId(),
            $feedDetails->feedId
        );
    }
838786
public function campaign($campaigns)
    {
        $campaigns = array_slice((array)$campaigns, 0, 3);
        foreach ($campaigns as $campaign) {
            $this->messageBuilder->addCampaignId($campaign);
        }

        return $this;
    }
115090
function ContactsGroupsMembersAdd(options, groupId, contactId) {
    ActionAbstract.call(this, options);
    this._groupId = groupId;
    this._contactId = contactId;
}
1216326
private function dispatchContextCreate()
    {
        $event = new ContactLedgerContextEvent(
            $this->campaign, $this->contactSource, $this->status, 'New contact is being created', $this->contact
        );
        $this->dispatcher->dispatch(
            'mautic.contactledger.context_create',
            $event
        );
    }
947287
public function addCampaign(\CampaignChain\CoreBundle\Entity\Campaign $campaigns)
    {
        $this->campaigns[] = $campaigns;

        return $this;
    }
883021
public function setContacts(array $contacts): SecurityTxt
    {
        if (!$this->validContacts($contacts, true)) {
            throw new Exception('Contacts array must contain well-formed e-mails and/or URLs.');
        }

        $this->contacts = $contacts;

        return $this;
    }
381087
@SuppressWarnings({"unused", "WeakerAccess"})
    public synchronized void pushInstallReferrer(String source, String medium, String campaign) {
        if (source == null && medium == null && campaign == null) return;
        try {
            // If already pushed, don't send it again
            int status = StorageHelper.getInt(context, "app_install_status", 0);
            if (status != 0) {
                Logger.d("Install referrer has already been set. Will not override it");
                return;
            }
            StorageHelper.putInt(context, "app_install_status", 1);

            if (source != null) source = Uri.encode(source);
            if (medium != null) medium = Uri.encode(medium);
            if (campaign != null) campaign = Uri.encode(campaign);

            String uriStr = "wzrk://track?install=true";
            if (source != null) uriStr += "&utm_source=" + source;
            if (medium != null) uriStr += "&utm_medium=" + medium;
            if (campaign != null) uriStr += "&utm_campaign=" + campaign;

            Uri uri = Uri.parse(uriStr);
            pushDeepLink(uri, true);
        } catch (Throwable t) {
            Logger.v("Failed to push install referrer", t);
        }
    }
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;
    }
894981
public function addActivity(\CampaignChain\CoreBundle\Entity\Activity $activities)
    {
        $this->activities[] = $activities;

        return $this;
    }
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();
    }
783140
private static void addCampaignsToGroup(
      AdWordsServicesInterface adWordsServices,
      AdWordsSession session,
      CampaignGroup campaignGroup,
      List<Long> campaignIds)
      throws ApiException, RemoteException {
    // Get the CampaignService.
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    List<CampaignOperation> operations = new ArrayList<>();
    for (Long campaignId : campaignIds) {
      Campaign campaign = new Campaign();
      campaign.setId(campaignId);
      campaign.setCampaignGroupId(campaignGroup.getId());

      CampaignOperation operation = new CampaignOperation();
      operation.setOperand(campaign);
      operation.setOperator(Operator.SET);
      operations.add(operation);
    }

    CampaignReturnValue returnValue =
        campaignService.mutate(operations.toArray(new CampaignOperation[operations.size()]));
    System.out.printf(
        "The following campaign IDs were added to the campaign group with ID %d:%n",
        campaignGroup.getId());
    for (Campaign campaign : returnValue.getValue()) {
      System.out.printf("\t%d%n", campaign.getId());
    }
  }
33155
public function AddAgentGroups($CampaignId, Request\AddAgentGroups $AddAgentGroups = null)
    {
        $uri = $this->getUri('/ccc/%s/agent-group', array($CampaignId));

        return $this->post($uri, $AddAgentGroups);
    }
487712
public function saveContact(Contact $contactMessage)
    {
        /* @var $mapper \SspContact\Mapper\Contact */
        $mapper = $this->getServiceLocator()->get('contact_mapper');
        $mapper->insert($contactMessage);
    }