@param Campaign $campaign

@return bool
@throws Exception

@todo Create test in examples/

API documentation: https://whatcounts.zendesk.com/hc/en-us/articles/204669995
496983
public function scheduleCampaign(Campaign &$campaign)
		{
			$form_data = array(
				'list_id' => $campaign->getListId(),
				'template_id' => $campaign->getTemplateId(),
				'format' => $campaign->getFormat(),
				'segmentation_id' => $campaign->getSegmentationId(),
				'seed_list_id' => $campaign->getSeedListId(),
				'suppression_list' => $campaign->getSupressionList(),
				'set_data_macro_id' => $campaign->getDataMacroId(),
				'campaign_alias' => $campaign->getAlias(),
				'target_rss' => $campaign->getRss(),
				'limit' => $campaign->getLimit(),
				'fillin_name0' => $campaign->getFillinName0(),
				'fillin_value0' => $campaign->getFillinValue0(),
				'fillin_name1' => $campaign->getFillinName1(),
				'fillin_value1' => $campaign->getFillinValue1(),
				'fillin_name2' => $campaign->getFillinName2(),
				'fillin_value2' => $campaign->getFillinValue2(),
				'fillin_name3' => $campaign->getFillinName3(),
				'fillin_value3' => $campaign->getFillinValue3(),
				'fillin_name4' => $campaign->getFillinName4(),
				'fillin_value4' => $campaign->getFillinValue4(),
				'fillin_name5' => $campaign->getFillinName5(),
				'fillin_value5' => $campaign->getFillinValue5(),
				'fillin_name6' => $campaign->getFillinName6(),
				'fillin_value6' => $campaign->getFillinValu60(),
				'fillin_name7' => $campaign->getFillinName7(),
				'fillin_value7' => $campaign->getFillinValue7(),
				'fillin_name8' => $campaign->getFillinName8(),
				'fillin_value8' => $campaign->getFillinValue8(),
				'fillin_name9' => $campaign->getFillinName9(),
				'fillin_value9' => $campaign->getFillinValue9(),
				'delivery' => $campaign->getSeedDelivery(),
				'notify_email' => $campaign->getSendNotification(),
				'start_month' => $campaign->getStartMonth(),
				'start_day' => $campaign->getStartDay(),
				'start_year' => $campaign->getStartYear(),
				'hour' => $campaign->getStartHour(),
				'minute' => $campaign->getStartMinute(),
				'end_month' => $campaign->getEndMonth(),
				'end_day' => $campaign->getEndDay(),
				'end_year' => $campaign->getEndYear(),
				'no_end_date' => $campaign->getNoEndDate(),
				'workflow_send_time' => $campaign->getWorkflowSendTime(),
				'repeat_frequency' => $campaign->getRepeatFrequency()
			);
			$this->call('schedule_deployment', $form_data);

			return TRUE;
		}
407628
public function sendSmsCampaignNowAsyncWithHttpInfo($campaignId)
    {
        $returnType = '';
        $request = $this->sendSmsCampaignNowRequest($campaignId);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    return [null, $response->getStatusCode(), $response->getHeaders()];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        $response->getBody()
                    );
                }
            );
    }
737103
public function preUp(Schema $schema)
    {
        /** @var ManagerRegistry $doctrine */
        $doctrine = $this->container->get('doctrine');
        $em = $doctrine->getManager();

        // Get all Campaigns.
        $campaigns = $em->getRepository('CampaignChain\CoreBundle\Entity\Campaign')
            ->findAll();

        if($campaigns){
            try {
                $em->getConnection()->beginTransaction();

                /** @var Campaign $campaign */
                foreach($campaigns as $campaign){
                    /** @var Action $firstAction */
                    $firstAction = $em->getRepository('CampaignChain\CoreBundle\Entity\Campaign')
                        ->getFirstAction($campaign);
                    if($firstAction && $firstAction->getStartDate() < $campaign->getStartDate()){
                        $campaign->setStartDate($firstAction->getStartDate());
                        $em->persist($campaign);

                        $this->write(
                            'Changed start date of campaign "'.
                            $campaign->getName().'" ('.$campaign->getId().') '.
                            'to date "'.
                            $campaign->getStartDate()->format(\DateTime::ISO8601)
                        );
                    } else {
                        $this->write(
                            'No changes to campaign "'.
                            $campaign->getName().'" ('.$campaign->getId().').'
                        );
                    }
                }

                $em->flush();

                $em->getConnection()->commit();
            } catch (\Exception $e) {
                $em->getConnection()->rollback();
                $this->write($e->getMessage());
            }
        }
    }
1072310
private function getCampaignLeadership($campaignId, $whereAreYouFrom = NULL, $branchFacilityId = NULL, $activityId = NULL, $global = FALSE, $page = 0) {
    /** @var \Drupal\Core\Database\Query\Select $query */
    $query = $this->connection->select('openy_campaign_memb_camp_actv', 'mca');
    $query->join('openy_campaign_member_campaign', 'mc', 'mc.id = mca.member_campaign');
    $query->join('openy_campaign_member', 'm', 'm.id = mc.member');

    $query->condition('mc.campaign', $campaignId);
    if (!empty($whereAreYouFrom)) {
      $query->condition('m.where_are_you_from', $whereAreYouFrom);
    }
    if (!empty($branchFacilityId)) {
      $query->condition('m.branch', $branchFacilityId);
    }
    if (!empty($activityId)) {
      $query->condition('mca.activity', $activityId);
    }
    $query->condition('m.is_employee', FALSE);

    $query->fields('m', ['id', 'first_name', 'last_name', 'membership_id']);
    $query->addField('mc', 'id', 'member_campaign');

    $query->groupBy('mc.id');
    $query->groupBy('m.id');
    $query->groupBy('m.first_name');
    $query->groupBy('m.last_name');
    $query->groupBy('m.membership_id');

    if ($global) {
      $query->leftJoin('taxonomy_term__field_global_goal_activity_worth', 'aw', 'aw.entity_id = mca.activity');
      $query->addExpression('SUM(aw.field_global_goal_activity_worth_value)', 'total');
      $query->having('SUM(aw.field_global_goal_activity_worth_value) > 0');
    }
    else {
      $query->addExpression('SUM(mca.count)', 'total');
      $query->having('SUM(mca.count) > 0');
    }

    $query->orderBy('total', 'DESC');

    $count_query = clone $query;
    $count = $count_query->countQuery()->execute()->fetchField();

    if ($global) {
      $query->range($page * static::MAX_LEADERS, static::MAX_LEADERS);
    }
    else {
      $query->range(0, static::MAX_LEADERS);
    }

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

    $leaders = [];
    $rank = $global ? $page * static::MAX_LEADERS + 1 : 1;
    foreach ($results as $item) {
      $lastNameLetter = !empty($item->last_name) ? ' ' . strtoupper($item->last_name[0]) : '';

      $total = floatval($item->total);

      $leaders[] = [
        'rank' => $rank,
        'member_id' => $item->id,
        'member_campaign_id' => $item->member_campaign,
        'total' => $total,
        'name' => $item->first_name . $lastNameLetter,
        'membership_id' => substr($item->membership_id, -4),
      ];
      $rank++;
    }

    return [
      'leaders' => $leaders,
      'count' => $count,
    ];
  }
804164
def perform(campaign)
      campaign.apply_premailer
      campaign.list.subscriptions.availables.each do |s|
        campaign.push_notification(s)
      end
    end
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]));
			}

		}
678431
private function parseCampaign()
    {
        if (null == $this->campaign) {
            // Check Campaign existence and published status.
            $this->campaign = $this->campaignModel->getEntity($this->campaignId);
            if (!$this->campaign) {
                throw new ContactSourceException(
                    'The campaignId specified does not exist.',
                    Codes::HTTP_GONE,
                    null,
                    Stat::TYPE_INVALID,
                    'campaignId'
                );
            } elseif (
                false === $this->campaign->getIsPublished()
                && !$this->contactSource->getInternal()
            ) {
                throw new ContactSourceException(
                    'The campaignId specified has been unpublished (deactivated).',
                    Codes::HTTP_GONE,
                    null,
                    Stat::TYPE_INVALID,
                    'campaignId'
                );
            }
            $this->addTrace('contactSourceCampaignId', (int) $this->campaignId);
        }

        return $this;
    }
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;
  }
263867
private function getEdgeAction(Campaign $campaign, $position)
    {
        if($position != 'first' && $position != 'last'){
            throw new \Exception('Position must be either "first" or "last"');
        }
        if($position == 'first'){
            $order = 'ASC';
        } else {
            $order = 'DESC';
        }

        // Get first Activity
        /** @var Activity $activity */
        $activity = $this->createQueryBuilder('c')
            ->select('a')
            ->from('CampaignChain\CoreBundle\Entity\Activity', 'a')
            ->where('a.campaign = :campaign')
            ->setParameter('campaign', $campaign)
            ->orderBy('a.startDate', $order)
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();

        // Get first Milestone
        /** @var Milestone $milestone */
        $milestone = $this->createQueryBuilder('c')
            ->select('m')
            ->from('CampaignChain\CoreBundle\Entity\Milestone', 'm')
            ->where('m.campaign = :campaign')
            ->setParameter('campaign', $campaign)
            ->orderBy('m.startDate', $order)
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();

        // Does Activity or Milestone exist?
        if($activity == null && $milestone == null){
            return null;
        }
        if($milestone == null){
            return $activity;
        }
        if($activity == null){
            return $milestone;
        }

        // Does Activity or Milestone come first/last?
        if($position == 'first') {
            if ($activity->getStartDate() < $milestone->getStartDate()) {
                return $activity;
            } else {
                return $milestone;
            }
        } else {
            if ($activity->getStartDate() > $milestone->getStartDate()) {
                return $activity;
            } else {
                return $milestone;
            }
        }
    }
514784
public function isValidTimespan(Campaign $campaign, \DateInterval $campaignInterval)
    {
        /** @var Action $firstAction */
        $firstAction = $this->em->getRepository('CampaignChain\CoreBundle\Entity\Campaign')
            ->getFirstAction($campaign);

        /** @var Action $lastAction */
        $lastAction = $this->em->getRepository('CampaignChain\CoreBundle\Entity\Campaign')
            ->getLastAction($campaign);

        // If no first and last action, any timespan is fine.
        if(!$firstAction && !$lastAction){
            return true;
        }

        /*
         * If first and last action exist, make sure the timespan stretches from
         * the start of the first to the start or end of the last action.
         */
        if($firstAction && $lastAction){
            if($lastAction->getEndDate()){
                $endDate = $lastAction->getEndDate();
            } else {
                $endDate = $lastAction->getStartDate();
            }

            $actionsInterval = $firstAction->getStartDate()->diff($endDate);

            return $campaignInterval >= $actionsInterval;
        }

        /*
         * If only first action or last action, make sure the timespan covers
         * the duration of the action.
         */
        if($firstAction && !$lastAction) {
            $action = $firstAction;
        } else {
            $action = $lastAction;
        }

        // If the action has no end date, then any timespan will do.
        if(!$action->getEndDate()){
            return true;
        }

        $actionInterval = $action->getStartDate()->diff($action->getEndDate());

        return $campaignInterval >= $actionInterval;
    }
617430
private function getUserProgress($campaign_id, $member_campaign_id) {
    /** @var \Drupal\Core\Database\Query\Select $query */
    $query = $this->connection->select('openy_campaign_memb_camp_actv', 'mca');
    $query->join('openy_campaign_member_campaign', 'mc', 'mc.id = mca.member_campaign');
    $query->join('openy_campaign_member', 'm', 'm.id = mc.member');

    $query->condition('mc.campaign', $campaign_id);
    $query->condition('mc.id', $member_campaign_id);

    $query->groupBy('mc.id');

    $query->leftJoin('taxonomy_term__field_global_goal_activity_worth', 'aw', 'aw.entity_id = mca.activity');
    $query->addExpression('SUM(aw.field_global_goal_activity_worth_value)', 'total');
    $query->having('SUM(aw.field_global_goal_activity_worth_value) > 0');

    $query->orderBy('total', 'DESC');

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

    return floatval($total);
  }
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;
    }
761517
protected function campaignBudgetsAction(Request $request)
    {
        // Get the API payload to test.
        $params['campaignId'] = $this->request->request->get('campaignId');
        $params['dateFrom']   = new \DateTime('now');
        $em                   = $this->container->get('doctrine.orm.entity_manager');
        $statRepo             = $em->getRepository(\MauticPlugin\MauticContactSourceBundle\Entity\Stat::class);
        $data                 = $statRepo->getCampaignBudgetsData($params);
        $headers              = [
            'mautic.contactsource.campaign.budgets.header.source',
            'mautic.contactsource.campaign.budgets.header.cap_name',
            'mautic.contactsource.campaign.budgets.header.today',
            'mautic.contactsource.campaign.budgets.header.daily_cap',
            'mautic.contactsource.campaign.budgets.header.daily_reached',
            'mautic.contactsource.campaign.budgets.header.mtd',
            'mautic.contactsource.campaign.budgets.header.monthly_cap',
            'mautic.contactsource.campaign.budgets.header.monthly_reached',
        ];
        foreach ($headers as $header) {
            $data['columns'][] = [
                'title' => $this->translator->trans($header),
            ];
        }
        $data = UTF8Helper::fixUTF8($data);

        return $this->sendJsonResponse($data);
    }
784511
public function isMemberWinner(NodeInterface $campaign) {
    $isWinner = FALSE;

    $looseString = $campaign->field_campaign_prize_nowin->value;
    $userData = MemberCampaign::getMemberCampaignData($campaign->id());
    $memberCampaignID = MemberCampaign::findMemberCampaign($userData['membership_id'], $campaign->id());

    $memberGameStorage = $this->entityTypeManager->getStorage('openy_campaign_member_game');
    $query = $memberGameStorage->getQuery();
    $gameIds = $query->condition('member', $memberCampaignID)
      ->execute();

    $games = $memberGameStorage->loadMultiple($gameIds);
    foreach ($games as $game) {
      if (!empty($game->result->value) && $game->result->value != $looseString) {
        $isWinner = TRUE;
      }
    }

    return $isWinner;
  }
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;
		}
947287
public function addCampaign(\CampaignChain\CoreBundle\Entity\Campaign $campaigns)
    {
        $this->campaigns[] = $campaigns;

        return $this;
    }