Get campaign ids, membership id and full name from SESSION.

@param int $campaignId
Campaign node ID.

@return array MemberCampaign data from SESSION.
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] : '',
    ];
  }
631505
public function GetCccCampaignStats($CampaignId, Request\GetCccCampaignStats $GetCccCampaignStats = null)
    {
        $uri = $this->getUri('/ccc/%s/stats', array($CampaignId));

        return $this->get($uri, $GetCccCampaignStats);
    }
1067063
public function getCredentialsByApplicationId($applicationId)
    {
        return $this->createCommand()
            ->setRequest(
                $this->client->get(Url::factory('application')->setQuery(array('applicationId' => $applicationId)))
            )
            ->setResponseClass('Maba\OAuthCommerceInternalClient\Entity\ApplicationPassword[]')
        ;
    }
577401
public static function findMemberCampaign($membershipID, $campaignID) {
    $connection = \Drupal::service('database');
    /** @var \Drupal\Core\Database\Query\Select $query */
    $query = $connection->select('openy_campaign_member', 'm');
    $query->condition('m.membership_id', $membershipID);
    $query->join('openy_campaign_member_campaign', 'mc', 'm.id = mc.member');
    $query->condition('mc.campaign', $campaignID);
    $query->fields('mc', ['id']);
    $memberCampaignRes = $query->execute()->fetchField();

    return (!empty($memberCampaignRes)) ? $memberCampaignRes : FALSE;
  }
42009
private function getAllMembersDataForQueue() {
    /** @var \Drupal\Core\Database\Query\Select $query */
    $query = $this->connection->select('node_field_data', 'n');
    $query->condition('n.status', 1);
    $query->condition('n.type', 'campaign');

    $query->join('openy_campaign_member_campaign', 'mc', 'n.nid = mc.campaign');
    $query->addField('mc', 'member', 'member_id');

    $query->join('openy_campaign_member', 'm', 'mc.member = m.id');
    $query->addField('m', 'personify_id', 'personify_id');

    $query->join('node__field_campaign_start_date', 'ds', 'n.nid = ds.entity_id');
    $query->addField('ds', 'field_campaign_start_date_value', 'start_date');

    $query->join('node__field_campaign_end_date', 'de', 'n.nid = de.entity_id');
    $query->addField('de', 'field_campaign_end_date_value', 'end_date');

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

    $membersData = [];
    foreach ($resArray as $item) {
      // UTC dates from Drupal database.
      $startDate = \DateTime::createFromFormat('Y-m-d\TH:i:s', $item->start_date);
      $endDate = \DateTime::createFromFormat('Y-m-d\TH:i:s', $item->end_date);

      // Expand Member dates to fit all active campaigns.
      if (in_array($item->member_id, array_keys($membersData))) {
        $startDate = $membersData[$item->member_id]['start_date'] > $startDate ? $startDate : $membersData[$item->member_id]['start_date'];
        $endDate = $membersData[$item->member_id]['end_date'] < $endDate ? $endDate : $membersData[$item->member_id]['end_date'];
      }

      $startDate->setTime(0, 0, 0);

      $membersData[$item->member_id] = [
        'member_id' => $item->member_id,
        'master_customer_id' => $item->personify_id,
        'start_date' => $startDate,
        'end_date' => $endDate,
      ];
    }

    return $membersData;
  }
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;
    }
228190
private function getBranches($campaignId = NULL) {
    $locations = [
      'default' => $this->t('Location'),
    ];

    $query = $this->entityTypeManager->getStorage('node')->getQuery();
    $nids = $query->condition('type', 'branch')
      ->condition('status', '1')
      ->sort('title', 'ASC')
      ->execute();
    $branches = $this->entityTypeManager->getStorage('node')->loadMultiple($nids);

    // Get list of branches related to the Campaign.
    $campaign = NULL;
    $campaignBranches = [];
    if (!empty($campaignId)) {
      /** @var \Drupal\node\Entity\Node $campaign Campaign node. */
      $campaign = $this->entityTypeManager->getStorage('node')->load($campaignId);
      $branchesField = $campaign->get('field_campaign_branch_target')->getValue();
      foreach ($branchesField as $branchItem) {
        $campaignBranches[] = $branchItem['target_id'];
      }
    }
    /** @var \Drupal\node\Entity\Node $branch */
    foreach ($branches as $branch) {
      if (!empty($campaignBranches) && !in_array($branch->id(), $campaignBranches)) {
        continue;
      }
      $locations[$branch->id()] = $branch->getTitle();
    }

    return $locations;
  }
274357
public function lists($partyId = null)
    {
        $params = [
            'id' => $partyId,
        ];

        return $this->parseJSON('get', [self::API_GET, $params]);
    }
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,
    ];
  }
659799
public function getAllCampaigns(array $filters = null) {
        $response = $this->mailjet->get(Resources::$Campaign, ['filters' => $filters]);
        if (!$response->success()) {
            $this->throwError("CampaignDraftManager:getAllCampaigns() failed", $response);
        }

        return $response->getData();
    }
1088954
public function toChannels($channels, $campaignId, $meta = [])
	{
		$data = ['channel_uids' => $channels, 'meta' => $meta];

		return $this->request->send('POST', "channels/campaigns/$campaignId", $data);
	}
987766
private function getWinnersOfType($type, $node_id) {
    $result = [];
    $streamText = '';
    $config = $this->configFactory->get('openy_campaign.general_settings');
    switch ($type) {
      case 'instant':
        /** @var \Drupal\Core\Database\Query\Select $query */
        $query = $this->connection->select('openy_campaign_member_game', 'g');
        $query->join('openy_campaign_member', 'm', 'g.member = m.id');
        $query->join('openy_campaign_member_campaign', 'mc', 'mc.member = m.id');
        $query->condition('mc.campaign', $node_id);
        $query->condition('g.result', '%SORRY%', 'NOT LIKE');
        $query->condition('g.result', '%Did not win%', 'NOT LIKE');
        $query->fields('g', ['created']);
        $query->fields('m', ['first_name', 'last_name']);
        $query->orderBy('g.created', 'ASC');
        $query->range(0, 50);
        $result = $query->execute()->fetchAll();
        $streamText = $config->get('stream_text_game');
        break;

      case 'visit':
        $campaign = $this->entityTypeManager->getStorage('node')->load($node_id);
        // Calculate visit goal winners.
        $achievedMemberCampaignIds = $this->getVisitsGoalWinners($campaign);
        // Load needed information.
        if (!empty($achievedMemberCampaignIds)) {
          /** @var \Drupal\Core\Database\Query\Select $query */
          $query = $this->connection->select('openy_campaign_member_campaign', 'mc');
          $query->condition('mc.id', $achievedMemberCampaignIds, 'IN');
          $query->join('openy_campaign_member', 'm', 'mc.member = m.id');
          $query->fields('m', ['first_name', 'last_name']);
          $query->range(0, 50);
          $result = $query->execute()->fetchAll();
          $streamText = $config->get('stream_text_visits');
        }
        break;
    }
    if (count($result)) {
      foreach ($result as &$row) {
        if (isset($row->last_name)) {
          $row->last_name = substr($row->last_name, 0, 1);
        }
        if (isset($row->created)) {
          $row->created = $this->timeAgo($row->created);
        }
        $row->stream_text = $streamText;
      }
    }
    return $result;
  }
578968
private function _getSession($sessionId)
    {
        if (is_null($this->_session)) {
            $this->_session = $this->_repository->find(array('sessionId' => $sessionId));
        }

        return $this->_session;
    }
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;
  }
215231
public function getUserGroups(string $userId = ''): array
    {
        // if not specified, get current user's id
        if (empty($userId)) {
            $userId = $this->Auth->user('id');
        }

        $groups = TableRegistry::get('Groups.Groups');

        $query = $groups->find('list', [
            'keyField' => 'id',
            'valueField' => 'name'
        ]);
        $query->matching('Users', function ($q) use ($userId) {
            return $q->where(['Users.id' => $userId]);
        });

        return $query->toArray();
    }
193775
public function getContactCampaignEvents($campaignId, $contactId, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
    {
        $parameters = array(
            'search'        => $search,
            'start'         => $start,
            'limit'         => $limit,
            'orderBy'       => $orderBy,
            'orderByDir'    => $orderByDir,
        );

        $parameters = array_filter($parameters);

        return $this->makeRequest('campaigns/'.$campaignId.'/events/contact/'.$contactId, $parameters);
    }
26906
public function updateCampaign($CampaignId, Campaign $campaign) {
        $response = $this->mailjet->put(Resources::$Campaign, ['id' => $CampaignId, 'body' => $campaign->format()]);
        if (!$response->success()) {
            $this->throwError("CampaignManager:updateCampaign() failed", $response);
        }

        return $response->getData();
    }