@param Campaign $campaign

@throws Exception

API documentation: https://whatcounts.zendesk.com/hc/en-us/articles/204669985
8090
public function launchCampaign(Campaign &$campaign)
		{
			$form_data = array(
				'list_id' => $campaign->getListId(),
				'template_id' => $campaign->getTemplateId(),
				'subject' => $campaign->getSubject(),
				'seed_list_id' => $campaign->getSeedListId(),
				'segmentation_id' => $campaign->getSegmentationId(),
				'format' => $campaign->getFormat(),
				'campaign_alias' => $campaign->getAlias(),
				'target_rss' => $campaign->getRss(),
				'vmta' => $campaign->getVmta(),
				'ab_definition_id' => $campaign->getAbDefinitionId(),
				'deployed_by_email' => $campaign->getDeployedByEmail(),
				'return_task_id' => $campaign->getReturnTaskId(),
				'delivery' => $campaign->getSeedDelivery(),
				'notify_email' => $campaign->getSendNotification()
			);
			$data = $this->call('launch', $form_data);

			if ($campaign->getReturnTaskId())
			{
				$campaign->setTaskId(trim($data[2]));
			}

		}
53189
public function getCampaignRevenueData(
        Campaign $campaign,
        \DateTime $dateFrom,
        \DateTime $dateTo,
        $unit,
        $dbunit,
        $cache_dir = __DIR__
    ) {
        $builder = $this->getEntityManager()->getConnection()->createQueryBuilder();
        $builder
            ->select(
                'DATE_FORMAT(DATE_ADD(date_added, INTERVAL :interval SECOND), :dbUnit) as label',
                'SUM(IFNULL(cost, 0.0))                                                as cost',
                'SUM(IFNULL(revenue, 0.0))                                             as revenue',
                'SUM(IFNULL(revenue, 0.0))-SUM(IFNULL(cost, 0.0))                      as profit'
            )
            ->from('contact_ledger')
            ->where(
                $builder->expr()->eq('campaign_id', ':campaignId'),
                $builder->expr()->gte('date_added', 'FROM_UNIXTIME(:dateFrom)'),
                $builder->expr()->lte('date_added', 'FROM_UNIXTIME(:dateTo)')
            )
            ->groupBy('label');

        // query the database
        $builder->setParameter(':interval', (new \DateTime())->getOffset(), Type::INTEGER);
        $builder->setParameter(':dbUnit', $dbunit, Type::STRING);
        $builder->setParameter(':campaignId', $campaign->getId(), Type::INTEGER);
        $builder->setParameter(':dateFrom', $dateFrom->getTimestamp(), Type::INTEGER);
        $builder->setParameter(':dateTo', $dateTo->getTimestamp(), Type::INTEGER);

        $cache = new FilesystemCache($cache_dir.'/sql');

        $stmt = $builder->getConnection()->executeCacheQuery(
            $builder->getSQL(),
            $builder->getParameters(),
            $builder->getParameterTypes(),
            new QueryCacheProfile(900, 'campaign-revenue-queries', $cache)
        );

        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stmt->closeCursor();

        // Sort and pad-out the results to match the other charts.
        $intervalMap = [
            'H' => ['hour', 'Y-m-d H:00'],
            'd' => ['day', 'Y-m-d'],
            'W' => ['week', 'Y \w\e\e\k W'],
            'Y' => ['year', 'Y'],
            'm' => ['minute', 'Y-m-d H:i'],
            's' => ['second', 'Y-m-d H:i:s'],
        ];
        $interval    = \DateInterval::createFromDateString('1 '.$intervalMap[$unit][0]);
        $periods     = new \DatePeriod($dateFrom, $interval, $dateTo);
        $updatedData = [];
        foreach ($periods as $period) {
            $dateToCheck   = $period->format($intervalMap[$unit][1]);
            $dataKey       = array_search($dateToCheck, array_column($data, 'label'));
            $updatedData[] = [
                'label'   => $dateToCheck,
                'cost'    => (false !== $dataKey) ? $data[$dataKey]['cost'] : 0,
                'revenue' => (false !== $dataKey) ? $data[$dataKey]['revenue'] : 0,
                'profit'  => (false !== $dataKey) ? $data[$dataKey]['profit'] : 0,
            ];
        }

        return $updatedData;
    }
534952
private function getActivities($campaignId) {
    $activities = [];

    $categories = $this->getCategories($campaignId);

    foreach (array_keys($categories) as $categoryId) {
      $topTerm = $this->taxonomyStorage->load($categoryId);

      $terms = $this->taxonomyStorage->loadTree($topTerm->getVocabularyId(), $categoryId, 1, TRUE);
      /** @var \Drupal\taxonomy\Entity\Term $term */
      foreach ($terms as $term) {
        if (!$term->field_enable_activities_counter->value) {
          continue;
        }
        $activities[$term->id()] = $term->getName();
      }
    }
    asort($activities);

    return $activities;
  }
288735
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
      throws RemoteException {
    // Get the CampaignService.
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    // Get the CustomerSyncService.
    CustomerSyncServiceInterface customerSyncService =
        adWordsServices.get(session, CustomerSyncServiceInterface.class);

    // Get a list of all campaign IDs.
    List<Long> campaignIds = new ArrayList<>();
    Selector selector = new SelectorBuilder()
        .fields(CampaignField.Id)
        .build();
    CampaignPage campaigns = campaignService.get(selector);
    if (campaigns.getEntries() != null) {
      Arrays.stream(campaigns.getEntries()).forEach(campaign -> campaignIds.add(campaign.getId()));
    }

    // Create date time range for the past 24 hours.
    DateTimeRange dateTimeRange = new DateTimeRange();
    dateTimeRange.setMin(new SimpleDateFormat("yyyyMMdd HHmmss").format(new Date(System
        .currentTimeMillis() - 1000L * 60 * 60 * 24)));
    dateTimeRange.setMax(new SimpleDateFormat("yyyyMMdd HHmmss").format(new Date()));

    // Create selector.
    CustomerSyncSelector customerSyncSelector = new CustomerSyncSelector();
    customerSyncSelector.setDateTimeRange(dateTimeRange);
    customerSyncSelector
        .setCampaignIds(ArrayUtils.toPrimitive(campaignIds.toArray(new Long[] {})));

    // Get all account changes for campaign.
    CustomerChangeData accountChanges = customerSyncService.get(customerSyncSelector);

    // Display changes.
    if (accountChanges != null && accountChanges.getChangedCampaigns() != null) {
      System.out.printf("Most recent change: %s%n", accountChanges.getLastChangeTimestamp());
      for (CampaignChangeData campaignChanges : accountChanges.getChangedCampaigns()) {
        System.out.printf("Campaign with ID %d was changed:%n", campaignChanges.getCampaignId());
        System.out.printf("\tCampaign changed status: '%s'%n", 
            campaignChanges.getCampaignChangeStatus());
        if (!ChangeStatus.NEW.equals(campaignChanges.getCampaignChangeStatus())) {
          System.out.printf("\tAdded campaign criteria: %s%n",
              getFormattedList(campaignChanges.getAddedCampaignCriteria()));
          System.out.printf("\tRemoved campaign criteria: %s%n",
              getFormattedList(campaignChanges.getRemovedCampaignCriteria()));

          if (campaignChanges.getChangedAdGroups() != null) {
            for (AdGroupChangeData adGroupChanges : campaignChanges.getChangedAdGroups()) {
              System.out.printf("\tAd group with ID %d was changed:%n",
                  adGroupChanges.getAdGroupId());
              System.out.printf("\t\tAd group changed status: %s%n",
                  adGroupChanges.getAdGroupChangeStatus());
              if (!ChangeStatus.NEW.equals(adGroupChanges.getAdGroupChangeStatus())) {
                System.out.printf("\t\tAds changed: %s%n",
                    getFormattedList(adGroupChanges.getChangedAds()));
                System.out.printf("\t\tCriteria changed: %s%n",
                    getFormattedList(adGroupChanges.getChangedCriteria()));
                System.out.printf("\t\tCriteria removed: %s%n",
                    getFormattedList(adGroupChanges.getRemovedCriteria()));
              }
            }
          }
        }
        System.out.println("");
      }
    } else {
      System.out.println("No account changes were found.");
    }
  }
618971
private function calculateTrackedActivities(NodeInterface $node) {
    // Fetch all members from the current campaign.
    /** @var \Drupal\Core\Database\Query\Select $query */
    $query = $this->connection->select('openy_campaign_memb_camp_actv', 'mca');
    $query->addField('mca', 'id', 'mca_id');
    $query->addField('mca', 'activity', 'mca_activity');
    $query->join('openy_campaign_member_campaign', 'mc', 'mc.id = mca.member_campaign');
    $query->addField('mc', 'id');
    $query->condition('mc.campaign', $node->id());

    $activities = $query->execute()->fetchAll();
    $data = [];

    $data['totalActivities'] = count($activities);
    /** @var \Drupal\taxonomy\TermStorageInterface $termStorage */
    $termStorage = $this->entityTypeManager->getStorage('taxonomy_term');

    foreach ($activities as $activity) {
      // Fetch subcategory.
      $subcategory = $termStorage->load($activity->mca_activity);
      // In case if some categories have been removed during the challenge, we need to skip it from the calculation.
      if (empty($subcategory)) {
        --$data['totalActivities'];
        continue;
      }

      // Fetch category.
      $ancestors = $termStorage->loadAllParents($subcategory->id());
      $ancestors = array_reverse($ancestors);
      /** @var \Drupal\taxonomy\Entity\Term $category */
      $category = reset($ancestors);

      // Calculate amount of activities in the category.
      $categories = &$data['categories'][$category->id()];
      if (!isset($categories['amount'])) {
        $categories['amount'] = 1;
      }
      else {
        ++$categories['amount'];
      }

      $categories['term'] = $category;

      // Calculate amount of activities in the subcategory.
      $subcategories = &$data['categories'][$category->id()]['subcategories'];
      if (!isset($subcategories[$subcategory->id()]['amount'])) {
        $subcategories[$subcategory->id()]['amount'] = 1;
      }
      else {
        ++$subcategories[$subcategory->id()]['amount'];
      }
      $subcategories[$subcategory->id()]['term'] = $subcategory;

    }

    return $data;
  }
224608
public function showMultipleCampaginStatistics($campaign_ids)
		{
			$form_data = array(
				'campaigns' => implode(',', $campaign_ids),
				'headers' => 1
			);
			$data = $this->call('show_campaign_stats_multi', $form_data, 'csv');
			$csv = new \parseCSV($data);

			$campaign_statistics = array();

			foreach ($csv->data as $campaign_statistic_item) {
				$campaign = new Report();
				$campaign
					->setCampaignId((int)$campaign_statistic_item['Campaign ID'])
					->setListName((string)$campaign_statistic_item['List Name'])
					->setListId((int)$campaign_statistic_item['List ID'])
					->setSubject((string)$campaign_statistic_item['Subject'])
					->setDate(\DateTime::createFromFormat('m/d/y h:i A', $campaign_statistic_item['Date']))
					->setRecipients($this->groupedNumberToInt($campaign_statistic_item['Recipients']))
					->setAlias((string)$campaign_statistic_item['Alias'])
					->setTemplateName((string)$campaign_statistic_item['Template Name'])
					->setSegmentation((string)$campaign_statistic_item['Segmentation'])
					->setActive((string)$campaign_statistic_item['Active'])
					->setSetMacroId((int)$campaign_statistic_item['Set Macro ID'])
					->setCharacterSet((string)$campaign_statistic_item['Character Set'])
					->setUnicode((string)$campaign_statistic_item['Unicode'])
					->setQuotedPrintable((string)$campaign_statistic_item['Quoted Printable'])
					->setForcedFormat((string)$campaign_statistic_item['Forced Format'])
					->setDeployedBy((string)$campaign_statistic_item['Deployed By'])
					->setAutoMultipart((boolean)$this->stringToBoolean($campaign_statistic_item['Auto Multipart']))
					->setWrapPlain((boolean)$this->stringToBoolean($campaign_statistic_item['Wrap Plain']))
					->setWrapHtml((boolean)$this->stringToBoolean($campaign_statistic_item['Wrap HTML']))
					->setTrackOpens((boolean)$this->stringToBoolean($campaign_statistic_item['Track Opens']))
					->setTrackClicks((boolean)$this->stringToBoolean($campaign_statistic_item['Track Clicks']))
					->setDeliverability((boolean)$this->stringToBoolean($campaign_statistic_item['Deliverability']))
					->setHardBounces((int)$campaign_statistic_item['Hard Bounces'])
					->setSoftBounces((int)$campaign_statistic_item['Soft Bounces'])
					->setUnsubscribes((int)$campaign_statistic_item['Unsubscribes'])
					->setDisplayMessageCount((int)$campaign_statistic_item['Display Message Count'])
					->setTotalOpened((int)$campaign_statistic_item['Total Opened'])
					->setTotalClicks((int)$campaign_statistic_item['Total Clicks'])
					->setTotalFtafs((int)$campaign_statistic_item['Total FTAFs'])
					->setTotalOpenedUnique((int)$campaign_statistic_item['Total Opened Unique'])
					->setComplaintBounces((int)$campaign_statistic_item['Complaint Bounces'])
					->setBlockedBounces((int)$campaign_statistic_item['Blocked Bounces'])
					->setSocialShares((int)$campaign_statistic_item['Social Shares'])
					->setSocialViews((int)$campaign_statistic_item['Social Views'])
					->setSocialClicks((int)$campaign_statistic_item['Social Clicks'])
					->setSocialProviderCount((int)$campaign_statistic_item['Social Provider Count'])
					->setDiggClicks((int)$campaign_statistic_item['Digg Clicks'])
					->setDiggShares((int)$campaign_statistic_item['Digg Shares'])
					->setDiggViews((int)$campaign_statistic_item['Digg Views'])
					->setFacebookClicks((int)$campaign_statistic_item['Facebook Clicks'])
					->setFacebookShares((int)$campaign_statistic_item['Facebook Shares'])
					->setFacebookViews((int)$campaign_statistic_item['Facebook Views'])
					->setLinkedinClicks((int)$campaign_statistic_item['LinkedIn Clicks'])
					->setLinkedinShares((int)$campaign_statistic_item['LinkedIn Shares'])
					->setLinkedinViews((int)$campaign_statistic_item['LinkedIn Views'])
					->setMyspaceClicks((int)$campaign_statistic_item['Myspace Clicks'])
					->setMyspaceShares((int)$campaign_statistic_item['Myspace Shares'])
					->setMyspaceViews((int)$campaign_statistic_item['Myspace Views'])
					->setTwitterClicks((int)$campaign_statistic_item['Twitter Clicks'])
					->setTwitterShares((int)$campaign_statistic_item['Twitter Shares'])
					->setTwitterViews((int)$campaign_statistic_item['Twitter Views'])
					->setGooglePlusClicks((int)$campaign_statistic_item['Google+ Clicks'])
					->setGooglePlusShares((int)$campaign_statistic_item['Google+ Shares'])
					->setGooglePlusViews((int)$campaign_statistic_item['Google+ Views'])
					->setStumbleuponClicks((int)$campaign_statistic_item['StumbleUpon Clicks'])
					->setStumbleuponShares((int)$campaign_statistic_item['StumbleUpon Shares'])
					->setStumbleuponViews((int)$campaign_statistic_item['StumbleUpon Views'])
					->setPinterestClicks((int)$campaign_statistic_item['Pinterest Clicks'])
					->setPinterestShares((int)$campaign_statistic_item['Pinterest Shares'])
					->setPinterestViews((int)$campaign_statistic_item['Pinterest Views']);
				$campaign_statistics[] = $campaign;
			}
			return $campaign_statistics;
		}
737542
private static function deleteCampaignFeed(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        $campaignFeed
    ) {
        $campaignFeedService = $adWordsServices->get($session, CampaignFeedService::class);

        printf(
            "Deleting association of feed ID %d and campaign ID %d...\n",
            $campaignFeed->getFeedId(),
            $campaignFeed->getCampaignId()
        );

        $operation = new CampaignFeedOperation();
        $operation->setOperand($campaignFeed);
        $operation->setOperator(Operator::REMOVE);

        return $campaignFeedService->mutate([$operation]);
    }
1259052
private static void updateCampaignDsaSetting(
      AdWordsServicesInterface adWordsServices,
      AdWordsSession session,
      Long campaignId,
      DSAFeedDetails feedDetails)
      throws ApiException, RemoteException {
    // Get the CampaignService.
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    Selector selector =
        new SelectorBuilder()
            .fields(CampaignField.Id, CampaignField.Settings)
            .equalsId(campaignId)
            .build();

    CampaignPage campaignPage = campaignService.get(selector);
    if (campaignPage.getEntries() == null || campaignPage.getTotalNumEntries() == 0) {
      throw new IllegalArgumentException("No campaign found with ID: " + campaignId);
    }
    Campaign campaign = campaignPage.getEntries(0);

    if (campaign.getSettings() == null) {
      throw new IllegalArgumentException(
          "Campaign with ID " + campaignId + " is not a DSA campaign.");
    }

    DynamicSearchAdsSetting dsaSetting =
        (DynamicSearchAdsSetting)
            Arrays.stream(campaign.getSettings())
                .filter(DynamicSearchAdsSetting.class::isInstance)
                .findFirst()
                .orElse(null);

    if (dsaSetting == null) {
      throw new IllegalArgumentException(
          "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 pageFeed = new PageFeed();
    pageFeed.setFeedIds(new long[] {feedDetails.feedId});
    dsaSetting.setPageFeed(pageFeed);

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

    Campaign updatedCampaign = new Campaign();
    updatedCampaign.setId(campaignId);
    updatedCampaign.setSettings(campaign.getSettings());

    CampaignOperation operation = new CampaignOperation();
    operation.setOperand(updatedCampaign);
    operation.setOperator(Operator.SET);

    updatedCampaign = campaignService.mutate(new CampaignOperation[] {operation}).getValue(0);
    System.out.printf(
        "DSA page feed for campaign ID %d was updated with feed ID %d.%n",
        updatedCampaign.getId(), feedDetails.feedId);
  }
996466
public function edit($campaign)
    {
        $this->getLogger()->debug('Getting Resource Owner');
        $this->ownerId = $this->getEntityProvider()->getMe()->getId();
        $this->campaign = $campaign;

        // Rewrite parameter mismatch
        $array = $this->toArray();
        $array['name'] = $array['campaign'];
        $this->getLogger()->info('Editing Campaign ID ' . $this->campaignId);
        $response = $this->doPut($this->url . '/' . $this->campaignId, $array);

        $this->getLogger()->debug('Passing the response to Hydrate');
        return $this->hydrate($response);
    }
36549
public function getMetrics(Campaign $campaign, Activity $activity){
        $qb = $this->em->createQueryBuilder();
        $qb->select('r')
            ->from('CampaignChain\CoreBundle\Entity\ReportAnalyticsActivityFact', 'r')
            ->where('r.activity = :activityId')
            ->andWhere('r.campaign = :campaignId')
            ->groupBy('r.metric')
            ->setParameter('activityId', $activity->getId())
            ->setParameter('campaignId', $campaign->getId());
        $query = $qb->getQuery();
        $this->dimensions = $query->getResult();
        return $this->dimensions;
    }
289633
public function evaluateAllSourceLimits($campaignId)
    {
        $campaignLimits = [];
        $sources        = $this->getRepository()->getSourcesByCampaign($campaignId);

        $container = $this->dispatcher->getContainer();
        /** @var CampaignSettings $campaignSettingsModel */
        $campaignSettingsModel = $container->get('mautic.contactsource.model.campaign_settings');

        foreach ($sources as $source) {
            $sourceEntity = $this->getEntity($source['id']);
            $campaignSettingsModel->setContactSource($sourceEntity);
            $campaignSettings = $campaignSettingsModel->getCampaignSettingsById($campaignId);

            /* @var \MauticPlugin\MauticContactSourceBundle\Model\Cache $cacheModel */
            $cacheModel = $container->get('mautic.contactsource.model.cache');
            $cacheModel->reset();
            $cacheModel->setContactSource($sourceEntity);

            foreach ($campaignSettings as $campaign) {
                // Establish parameters from campaign settings.
                if (!empty($campaign->limits) && isset($campaign->campaignId)) {
                    $id                = intval($campaign->campaignId);
                    $limitRules        = new \stdClass();
                    $limitRules->rules = $campaign->limits;
                    $limits            = $cacheModel->evaluateLimits($limitRules, $id, false, true);
                    if ($limits) {
                        $campaignLimits[] = [
                            'sourceId' => $source['id'],
                            'limits'   => $limits,
                            'name'     => $source['name'],
                            'link'     => $this->buildUrl(
                                'mautic_contactsource_action',
                                ['objectAction' => 'view', 'objectId' => $source['id']]
                            ),
                        ];
                    }
                } else {
                    $limitsPlaceholder = [
                        0 => [
                            'name' => 'Unlimited',
                        ],
                    ];
                    $campaignLimits[]  = [
                        'sourceId' => $source['id'],
                        'limits'   => $limitsPlaceholder,
                        'name'     => $source['name'],
                        'link'     => $this->buildUrl(
                            'mautic_contactsource_action',
                            ['objectAction' => 'view', 'objectId' => $source['id']]
                        ),
                    ];
                }
            }
        }

        return $campaignLimits;
    }
2314
private static function createAdGroup(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        Campaign $campaign
    ) {
        $adGroupService = $adWordsServices->get($session, AdGroupService::class);

        // Create ad group.
        $adGroup = new AdGroup();
        $adGroup->setCampaignId($campaign->getId());
        $adGroup->setName('Ad Group #' . uniqid());

        // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
        $adGroup->setAdGroupType(AdGroupType::SHOPPING_SHOWCASE_ADS);

        // Required: Set the ad group's bidding strategy configuration.
        // Note: Showcase ads require that the campaign has a ManualCpc
        // BiddingStrategyConfiguration.
        $biddingStrategyConfiguration = new BiddingStrategyConfiguration();

        // Optional: Set the bids.
        $bidAmount = new Money();
        $bidAmount->setMicroAmount(100000);
        $cpcBid = new CpcBid();
        $cpcBid->setBid($bidAmount);
        $biddingStrategyConfiguration->setBids([$cpcBid]);

        $adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

        // Create operation.
        $adGroupOperation = new AdGroupOperation();
        $adGroupOperation->setOperand($adGroup);
        $adGroupOperation->setOperator(Operator::ADD);

        // Make the mutate request.
        $adGroupAddResult = $adGroupService->mutate([$adGroupOperation]);
        $adGroup = $adGroupAddResult->getValue()[0];

        return $adGroup;
    }
145869
private function getCampaignParametersForPromoUrl($campaignName, $campaignMedium, $campaignContent = '')
    {
        $campaignName = sprintf('pk_campaign=%s&pk_medium=%s&pk_source=Piwik_App', $campaignName, $campaignMedium);

        if (!empty($campaignContent)) {
            $campaignName .= '&pk_content=' . $campaignContent;
        }

        return $campaignName;
    }
1098487
def campaigns
      response = @@soap.getClientCampaigns(:apiKey => @apiKey, :clientID => @clientID )
      campaign_list = handle_response response.client_GetCampaignsResult
      campaign_list.collect do |campaign|  
        Campaign.new(campaign.campaignID, campaign.subject, campaign.name, campaign.sentDate, campaign.totalRecipients, :apiKey=> @apiKey)
      end
    end
534051
public function postCampaignsSend($campaignId, $contacts)
    {
        $data = [
            'username' => $this->getApiUsername(),
            'password' => $this->getApiPassword(),
            'campaignId' => $campaignId,
            'ContactIds' => $contacts,
        ];
        $this->setUrl($this->getApiEndpoint() . self::REST_CAMPAIGN_SEND)
            ->setVerb('POST')
            ->buildPostBody($data);

        $response = $this->execute();
        if (isset($response->message)) {
            unset($data['password']);
            $message = 'SENDING CAMPAIGN ' . $response->message;
            $this->helper->debug('postCampaignsSend', [$message]);
            $this->helper->debug('postCampaignsSend', $data);
        }

        return $response;
    }
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);
    }
778231
public function getCampaignRevenueDatatableData(Campaign $campaign, \DateTime $dateFrom, \DateTime $dateTo)
    {
        $response = [];

        $cache_dir = $this->dispatcher->getContainer()->getParameter('kernel.cache_dir');

        $unit             = $this->getTimeUnitFromDateRange($dateFrom, $dateTo);
        $chartQueryHelper = new ChartQuery($this->em->getConnection(), $dateFrom, $dateTo, $unit);
        $dbunit           = $chartQueryHelper->translateTimeUnit($unit);

        $results = $this->getRepository()->getCampaignRevenueData(
            $campaign,
            $dateFrom,
            $dateTo,
            $unit,
            $dbunit,
            $cache_dir
        );

        // Allow other bundles to alter the data before rendering
        $event = new ChartDataAlterEvent(
            'campaign.revenue.datatable',
            [
                'campaign' => $campaign,
                'dateFrom' => $dateFrom,
                'dateTo'   => $dateTo,
                'unit'     => $unit,
                'dbunit'   => $dbunit,
                'cacheDir' => $cache_dir,
            ], $results
        );
        $this->dispatcher->dispatch('mautic.contactledger.chartdata.alter', $event);
        $results = $event->getData();

        foreach ($results as $result) {
            $result['cost']    = self::formatDollar($result['cost']);
            $result['revenue'] = self::formatDollar($result['revenue']);
            $result['profit']  = self::formatDollar($result['profit']);
            $response[]        = $result;
        }

        return $response;
    }