Access a given campaign resource
@param string $CampaignId
@return array
499790
public function findByCampaignId($CampaignId) {
        $response = $this->mailjet->get(Resources::$Campaign, ['id' => $CampaignId]);
        if (!$response->success()) {
            $this->throwError("CampaignManager:findByCampaignId() failed", $response);
        }

        return $response->getData();
    }
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;
    }
1105616
public static function isLoggedIn($campaignID) {
    $campaignIDs = [];
    $request = \Drupal::request();
    $session = $request->getSession();
    if (!empty($session->get('openy_campaign'))) {
      $openyCampaignSession = $session->get('openy_campaign');
      $campaignIDs = $openyCampaignSession['campaign_ids'];
    }

    return in_array($campaignID, $campaignIDs);
  }
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]));
			}

		}
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;
    }
751424
public function getOutlet($outletId)
    {
        $resource = 'campaigns/' . $this->campaignId . '/outlets/' . $outletId . '.json';

        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));

        $decodedResponseBody = $this->getDecodedBody($response->getBody());

        $getOrderResponse = new Models\GetOutletResponse($decodedResponseBody);
        return $getOrderResponse->getOutlet();
    }
1918
public static function getMemberCampaignData($campaignId) {
    $request = \Drupal::request();
    $session = $request->getSession();

    $openyCampaignSession = $session->get('openy_campaign', [
      'campaign_ids' => [],
      'member_ids' => [],
      'membership_ids' => [],
      'full_names' => [],
    ]);

    $membershipIDs = $openyCampaignSession['membership_ids'];
    $fullNames = $openyCampaignSession['full_names'];
    $memberIDs = $openyCampaignSession['member_ids'];

    return [
      'campaign_id' => $campaignId,
      'membership_id' => !empty($membershipIDs[$campaignId]) ? $membershipIDs[$campaignId] : '',
      'full_name' => !empty($fullNames[$campaignId]) ? $fullNames[$campaignId] : '',
      'member_id' => !empty($memberIDs[$campaignId]) ? $memberIDs[$campaignId] : '',
    ];
  }
1143238
public function showWinnersBlock($campaignId, $branchId) {
    $winners = $this->getCampaignWinners($campaignId, $branchId);
    $prizes = $this->getCampaignPrizes($campaignId);

    // Group prizes by titles and select all winners for these titles.
    // This grouping is needed if the campaign has several identical prizes.
    $prizesMap = [];
    $winnersMap = [];
    foreach ($prizes as $place => $prize) {
      $prizesMap[$prize['title']] = [
        'title' => $prize['title'],
        'description' => $prize['text'],
        'winners' => [],
      ];
      if (!empty($winners[$place])) {
        foreach ($winners[$place] as $winner) {
          $winnersMap[$prize['title']][] = $winner;
        }
      }
    }

    // Sort all winners alphabetically.
    foreach ($winnersMap as &$winners) {
      usort($winners, function ($a, $b) {
        return strcmp($a['name'], $b['name']);
      });
    }

    foreach ($prizesMap as $key => $prize) {
      if (!empty($winnersMap[$key])) {
        $prizesMap[$key]['winners'] = $winnersMap[$key];
      }
    }

    $output = [];
    foreach ($prizesMap as $key => $prize) {
      if (!empty($prize['winners'])) {
        $output[] = [
          '#theme' => 'openy_campaign_winners',
          '#title' => $prize['title'],
          '#prize' => $prize['description'],
          '#winners' => $prize['winners'],
        ];
      }
    }

    $render = $this->renderer->renderRoot($output);

    return $render;
  }
989892
private function processConfirmedCustomerAbandonedCart($storeId, $campaignId)
    {
        $ac1QuoteIdsWithConfirmedContacts = $this->abandonedCollectionFactory->create()
            ->getCollectionByConfirmedStatus($storeId)
            ->getColumnValues('quote_id');

        $quoteCollectionFromIds = $this->orderCollection->create()
            ->getStoreQuotesFromQuoteIds($ac1QuoteIdsWithConfirmedContacts, $storeId);
        return $this->createCustomerFirstAbandonedCart(
            $quoteCollectionFromIds,
            $storeId,
            $campaignId
        );
    }
33155
public function AddAgentGroups($CampaignId, Request\AddAgentGroups $AddAgentGroups = null)
    {
        $uri = $this->getUri('/ccc/%s/agent-group', array($CampaignId));

        return $this->post($uri, $AddAgentGroups);
    }
398816
private function getCategories($campaignId) {
    $categories = [];

    /** @var \Drupal\node\Entity\Node $campaign */
    $campaign = $this->entityTypeManager->getStorage('taxonomy_vocabulary')->load($campaignId);

    /** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
    $vocabulary = $campaign->field_campaign_fitness_category->entity;
    /** @var \Drupal\taxonomy\VocabularyStorageInterface $vocabularyStorage */
    $vocabularyStorage = $this->entityTypeManager->getStorage('taxonomy_vocabulary');
    $tids = $vocabularyStorage->getToplevelTids([$vocabulary->id()]);

    $terms = $this->taxonomyStorage->loadMultiple($tids);
    /** @var \Drupal\taxonomy\Entity\Term $term */
    foreach ($terms as $term) {
      $categories[$term->id()] = $term->getName();
    }
    return $categories;
  }
631054
private static List<CampaignFeed> getCampaignFeeds(AdWordsServicesInterface adWordsServices,
      AdWordsSession session, Feed feed, int placeholderType) throws RemoteException {
    // Get the CampaignFeedService.
    CampaignFeedServiceInterface campaignFeedService =
        adWordsServices.get(session, CampaignFeedServiceInterface.class);

    String query = String.format(
        "SELECT CampaignId, MatchingFunction, PlaceholderTypes WHERE Status = 'ENABLED' "
        + "AND FeedId = %d AND PlaceholderTypes CONTAINS_ANY [%d]", feed.getId(), placeholderType);

    List<CampaignFeed> campaignFeeds = new ArrayList<>();
    int offset = 0;
    CampaignFeedPage campaignFeedPage;

    do {
      String pageQuery = String.format(query + " LIMIT %d, %d", offset, PAGE_SIZE);
      campaignFeedPage = campaignFeedService.query(pageQuery);
      if (campaignFeedPage.getEntries() != null) {
        campaignFeeds.addAll(Arrays.asList(campaignFeedPage.getEntries()));
      }
      offset += PAGE_SIZE;
    } while (offset < campaignFeedPage.getTotalNumEntries());

    return campaignFeeds;
  }
866461
public function findByNewsletterId($NewsletterId) {
        $response = $this->mailjet->get(Resources::$Campaign, ['mj.nl' => $NewsletterId]);
        if (!$response->success()) {
            $this->throwError("CampaignService:findByNewsletterId() failed", $response);
        }

        return $response->getData();
    }
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;
    }
1239295
public function getCampaignNodeFromRoute() {
    $node = $this->routeMatch->getParameter('node');
    // For custom routes - get campaign_id.
    if ($node instanceof NodeInterface !== TRUE) {
      $campaignId = $this->routeMatch->getParameter('campaign_id');
      if (is_null($campaignId)) {
        $campaignId = $this->container->get('request_stack')->getCurrentRequest()->get('campaign_id');
      }
      $node = !empty($campaignId) ? $this->entityTypeManager->getStorage('node')->load($campaignId) : FALSE;
    }
    if (empty($node)) {
      return FALSE;
    }
    /** @var \Drupal\node\NodeInterface $campaign */
    $campaign = $this->getNodeCampaignNode($node);

    return !empty($campaign) && ($campaign->getType() == 'campaign') ? $campaign : FALSE;
  }
1258995
private function getPublishedEvents($eventId = null)
    {
        if (!$this->publishedEvents) {
            $campaignIds = array_keys($this->getPublishedCampaigns());
            if ($campaignIds) {
                foreach ($this->eventModel->getRepository()->getEntities(
                    [
                        'filter' => [
                            'force' => [
                                [
                                    'column' => 'IDENTITY(e.campaign)',
                                    'expr'   => 'in',
                                    'value'  => $campaignIds,
                                ],
                            ],
                        ],
                    ]
                ) as $event) {
                    $this->publishedEvents[$event->getId()] = $event->getName();
                }
            }
        }
        if ($eventId) {
            return isset($this->publishedEvents[$eventId]) ? $this->publishedEvents[$eventId] : null;
        } else {
            return $this->publishedEvents;
        }
    }
460384
protected function getOrCreateCampaign($data)
    {
        // Create new campaign if selected
        if (is_array($data) && !empty($data['AddNewSelect']) // Explicitly click "Add to a new campaign"
            || (is_array($data) && !isset($data['Campaign']) && isset($data['NewTitle'])) // This is the only option
        ) {
            // Permission
            if (!ChangeSet::singleton()->canCreate()) {
                throw $this->validationResult(
                    _t(__CLASS__ . '.CREATE_DENIED', 'You do not have permission to create campaigns')
                );
            }

            // Check title is valid
            $title = $data['NewTitle'];
            if (empty($title)) {
                throw $this->validationResult(
                    _t(__CLASS__ . '.MISSING_TITLE', 'Campaign name is required'),
                    'NewTitle'
                );
            }

            // Prevent duplicates
            $hasExistingName = Changeset::get()
                    ->filter('Name:nocase', $title)
                    ->count() > 0;

            if ($hasExistingName) {
                throw $this->validationResult(
                    _t(
                        'SilverStripe\\CampaignAdmin\\CampaignAdmin.ERROR_DUPLICATE_NAME',
                        'Name "{Name}" already exists',
                        ['Name' => $title]
                    ),
                    'NewTitle'
                );
            }

            // Create and return
            $campaign = ChangeSet::create();
            $campaign->Name = $title;
            $campaign->write();
            return $campaign->ID;
        }

        // Get selected campaign ID
        $campaignID = null;
        if (is_array($data) && !empty($data['Campaign'])) {
            $campaignID = $data['Campaign'];
        } elseif (is_numeric($data)) {
            $campaignID = (int)$data;
        }
        if (empty($campaignID)) {
            throw $this->validationResult(_t(__CLASS__ . '.NONE_SELECTED', 'No campaign selected'));
        }
        return $campaignID;
    }