Get contact events for a single campaign

@param        $campaignId
@param        $contactId
@param string $search
@param int    $start
@param int    $limit
@param string $orderBy
@param string $orderByDir

@return array|mixed
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);
    }
1110729
public function getEngagementCount(
        Contact $contact,
        \DateTime $dateFrom = null,
        \DateTime $dateTo = null,
        $unit = 'm',
        ChartQuery $chartQuery = null
    ) {
        $event = new ContactSourceTimelineEvent($contact);
        $event->setCountOnly($dateFrom, $dateTo, $unit, $chartQuery);

        $this->dispatcher->dispatch(ContactSourceEvents::TIMELINE_ON_GENERATE, $event);

        return $event->getEventCounter();
    }
79282
protected function getAllEngagements(
        array $contactClients,
        array $filters = null,
        array $orderBy = null,
        $page = 1,
        $limit = 25
    ) {
        $session = $this->get('session');

        if (null === $filters) {
            $chartfilters = $session->get(
                'mautic.contactclient.plugin.transactions.chartfilter',
                [
                    'date_from' => $this->get('mautic.helper.core_parameters')->getParameter(
                        'default_daterange_filter',
                        '-1 month'
                    ),
                    'date_to'   => null,
                    'type'      => 'All Events',
                ]
            );
            $session->set('mautic.contactclient.plugin.transactions.chartfilter');
            $search = $session->get('mautic.contactclient.plugin.transactions.search', '');
            $session->set('mautic.contactclient.plugin.transactions.search', '');
        }
        $filters = InputHelper::cleanArray(array_merge($chartfilters, ['search' => $search]));

        if (null == $orderBy) {
            if (!$session->has('mautic.contactclient.plugin.transactions.orderby')) {
                $session->set('mautic.contactclient.plugin.transactions.orderby', 'date_added');
                $session->set('mautic.contactclient.plugin.transactions.orderbydir', 'DESC');
            }

            $orderBy = [
                $session->get('mautic.contactclient.plugin.transactions.orderby'),
                $session->get('mautic.contactclient.plugin.transactions.orderbydir'),
            ];
        }

        // prepare result object
        $result = [
            'events'      => [],
            'chartfilter' => $chartfilters,
            'search'      => $search,
            'order'       => $orderBy,
            'types'       => [],
            'total'       => 0,
            'page'        => $page,
            'limit'       => $limit,
            'maxPages'    => 0,
        ];

        // get events for each contact
        foreach ($contactClients as $contactClient) {
            //  if (!$contactClient->getEmail()) continue; // discard contacts without email

            /** @var ContactClientModel $model */
            $model       = $this->getModel('contactClient');
            $engagements = $model->getEngagements($contactClient, $filters, $orderBy, $page, $limit);
            $events      = $engagements['events'];
            $types       = $engagements['types'];

            // inject contactClient into events
            foreach ($events as &$event) {
                $event['contactClientId']    = $contactClient->getId();
                $event['contactClientEmail'] = $contactClient->getEmail();
                $event['contactClientName']  = $contactClient->getName() ? $contactClient->getName(
                ) : $contactClient->getEmail();
            }

            $result['events'] = array_merge($result['events'], $events);
            $result['types']  = array_merge($result['types'], $types);
            $result['total'] += $engagements['total'];
        }

        $result['maxPages'] = ($limit <= 0) ? 1 : round(ceil($result['total'] / $limit));

        usort($result['events'], [$this, 'cmp']); // sort events by

        // now all events are merged, let's limit to   $limit
        array_splice($result['events'], $limit);

        $result['total'] = count($result['events']);

        return $result;
    }
1011636
protected function getFiles(
        ContactClient $contactClient,
        array $filters = null,
        array $orderBy = null,
        $page = 1,
        $limit = 25
    ) {
        $session  = $this->get('session');
        $criteria = [];
        if (null === $filters) {
            $storedFilters = $session->get(
                'mautic.contactclient.'.$contactClient->getId().'.chartfilter',
                [
                    'date_from' => $this->get('mautic.helper.core_parameters')->getParameter(
                        'default_daterange_filter',
                        '-1 month midnight'
                    ),
                    'date_to'   => null,
                    'type'      => '',
                ]
            );
            $session->set('mautic.contactclient.'.$contactClient->getId().'.chartfilter', $storedFilters);
            // $filters['fromDate'] = new \DateTime($storedFilters['date_from']);
            // $filters['toDate']   = new \DateTime($storedFilters['date_to']);
            $filters['type'] = $storedFilters['type'];
        }

        $filters['contactClient'] = $contactClient->getId();

        foreach ($filters as $name => $value) {
            switch ($name) {
                // case 'fromDate':
                //     $criteria[] = ['col' => 'dateAdded', 'expr' => 'gte', 'val' => $value];
                //     break;
                // case 'toDate':
                //     $criteria[] = ['col' => 'dateAdded', 'expr' => 'lt', 'val' => $value];
                //     break;
                default:
                    if (!empty($value)) {
                        $criteria[] = ['col' => $name, 'expr' => 'eq', 'val' => $value];
                    }
            }
        }

        $start = ($page - 1) * $limit;

        if (null === $orderBy || null === $orderBy[0]) { //empty array or no fieldname in first index
            if (!$session->has('mautic.contactclient.'.$contactClient->getId().'.files.orderby')) {
                $session->set('mautic.contactclient.'.$contactClient->getId().'.files.orderby', 'date_added');
                $session->set('mautic.contactclient.'.$contactClient->getId().'.files.orderbydir', 'DESC');
            }

            $orderBy = [
                $session->get('mautic.contactclient.'.$contactClient->getId().'.files.orderby'),
                $session->get('mautic.contactclient.'.$contactClient->getId().'.files.orderbydir'),
            ];
        }

        /** @var FileRepository $fileRepository */
        $fileRepository = $this->getDoctrine()->getManager()->getRepository('MauticContactClientBundle:File');
        $files          = $fileRepository->getEntities(
            [
                'filter'     => ['where' => $criteria],
                'start'      => $start,
                'limit'      => $limit,
                'orderBy'    => 'f.'.lcfirst(str_replace('_', '', ucwords($orderBy[0], '_'))),
                'orderByDir' => $orderBy[1],
            ]
        );

        $fileCount = count($files);

        return [
            'files'    => $files,
            'filters'  => $filters,
            'order'    => $orderBy,
            'total'    => $fileCount,
            'page'     => $page,
            'limit'    => $limit,
            'maxPages' => ceil($fileCount / $limit),
        ];
    }
553233
public function getEventsForTimelineExport($contactSourceId, array $options = [], $count)
    {
        $query = $this->getEntityManager()->getConnection()->createQueryBuilder()
            ->from(MAUTIC_TABLE_PREFIX.'contactsource_events', 'c');
        if ($count) {
            $query->select('COUNT(c.id) as count');
        } else {
            $query->select('c.id, c.type, c.date_added, c.message, c.contact_id, c.logs');
        }

        $query->where(
            $query->expr()->eq('c.contactsource_id', ':contactSourceId')
        )
            ->setParameter('contactSourceId', (int) $contactSourceId);

        if (!empty($options['dateFrom']) && !empty($options['dateTo'])) {
            $options['dateTo']->modify('+1 day - 1 second');
            $query->andWhere('c.date_added BETWEEN FROM_UNIXTIME(:dateFrom) AND FROM_UNIXTIME(:dateTo)')
                ->setParameter('dateFrom', $options['dateFrom']->setTime(00, 00, 00)->getTimestamp())
                ->setParameter('dateTo', $options['dateTo']->setTime(23, 59, 59)->getTimestamp());
        } elseif (!empty($options['dateFrom'])) {
            $query->andWhere($query->expr()->gte('c.date_added', 'FROM_UNIXTIME(:dateFrom)'))
                ->setParameter('dateFrom', $options['dateFrom']->setTime(00, 00, 00)->getTimestamp());
        } elseif (!empty($options['dateTo'])) {
            $options['dateTo']->modify('+1 day - 1 second');
            $query->andWhere($query->expr()->lte('c.date_added', 'FROM_UNIXTIME(:dateTo)'))
                ->setParameter('dateTo', $options['dateTo']->setTime(23, 59, 59)->getTimestamp());
        }

        if (isset($options['message']) && !empty($options['message'])) {
            $query->andWhere('c.message LIKE :message')
                ->setParameter('message', '%'.trim($options['message']).'%');
        }

        if (isset($options['contact_id']) && !empty($options['contact_id'])) {
            $query->andWhere('c.contact_id = :contact')
                ->setParameter('contact', trim($options['contact_id']));
        }

        if (isset($options['type']) && !empty($options['type'])) {
            $query->andWhere('c.type = :type')
                ->setParameter('type', trim($options['type']));
        }

        if (isset($options['campaignId']) && !empty($options['campaignId'])) {
            $query->join(
                'c',
                'contactsource_stats', 's',
                'c.contactsource_id = s.contactsource_id AND c.contact_id = s.contact_id'
            )
                ->andWhere($query->expr()->eq('s.campaign_id', ':campaignId'))
                ->setParameter('campaignId', $options['campaignId']);
        }

        $query->orderBy('c.date_added', 'DESC');

        if (!empty($options['limit'])) {
            $query->setMaxResults($options['limit']);
            if (!empty($options['start'])) {
                $query->andWhere('c.id > :offset')
                    ->setParameter('offset', $options['start']);
            }
        }

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

        return $results;
    }
1326314
public function getStatsByCampaign(
        ContactSource $contactSource,
        $unit,
        $type,
        \DateTime $dateFrom = null,
        \DateTime $dateTo = null,
        $campaignId = null,
        $dateFormat = null,
        $canViewOthers = true
    ) {
        $unit           = (null === $unit) ? $this->getTimeUnitFromDateRange($dateFrom, $dateTo) : $unit;
        $dateToAdjusted = clone $dateTo;

        $userTZ     = new \DateTime('now');
        $userTzName = $userTZ->getTimezone()->getName();

        if (in_array($unit, ['H', 'i', 's'])) {
            // draw the chart with the correct intervals for intra-day
            $dateToAdjusted->setTime(23, 59, 59);
        }
        $chart = new LineChart($unit, $dateFrom, $dateToAdjusted, $dateFormat);
        $query = new ChartQuery($this->em->getConnection(), $dateFrom, $dateToAdjusted, $unit);

        if (isset($campaignId) && !empty($campaignId)) {
            $campaign                      = $this->em->getRepository('MauticCampaignBundle:Campaign')->getEntity($campaignId);
            $campaigns[$campaign->getId()] = $campaign->getName();
        } else {
            $campaigns = $this->getCampaignList($contactSource);
        }

        if ('cost' != $type) {
            foreach ($campaigns as $campaignId => $campaignName) {
                $q = $query->prepareTimeDataQuery(
                    'contactsource_stats',
                    'date_added',
                    [
                        'contactsource_id' => $contactSource->getId(),
                        'type'             => $type,
                        'campaign_id'      => $campaignId,
                    ]
                );

                if (!in_array($unit, ['H', 'i', 's'])) {
                    // For some reason, Mautic only sets UTC in Query Date builder
                    // if its an intra-day date range ¯\_(ツ)_/¯
                    // so we have to do it here.
                    $paramDateTo   = $q->getParameter('dateTo');
                    $paramDateFrom = $q->getParameter('dateFrom');
                    $paramDateTo   = new \DateTime($paramDateTo);
                    $paramDateTo->setTimeZone(new \DateTimeZone('UTC'));
                    $q->setParameter('dateTo', $paramDateTo->format('Y-m-d H:i:s'));
                    $paramDateFrom = new \DateTime($paramDateFrom);
                    $paramDateFrom->setTimeZone(new \DateTimeZone('UTC'));
                    $q->setParameter('dateFrom', $paramDateFrom->format('Y-m-d H:i:s'));
                    $select    = $q->getQueryPart('select')[0];
                    $newSelect = str_replace(
                        't.date_added,',
                        "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),",
                        $select
                    );
                    $q->resetQueryPart('select');
                    $q->select($newSelect);

                    // AND adjust the group By, since its using db timezone Date values
                    $groupBy    = $q->getQueryPart('groupBy')[0];
                    $newGroupBy = str_replace(
                        't.date_added,',
                        "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),",
                        $groupBy
                    );
                    $q->resetQueryPart('groupBy');
                    $q->groupBy($newGroupBy);
                }

                if (!$canViewOthers) {
                    $this->limitQueryToCreator($q);
                }
                $data = $query->loadAndBuildTimeData($q);
                foreach ($data as $val) {
                    if (0 !== $val) {
                        if (empty($campaignName)) {
                            $campaignName = 'No Campaign';
                        }
                        $chart->setDataset($campaignName, $data);
                        break;
                    }
                }
            }
        } else {
            // Revenue has a different scale and data source so do it as a one off

            $dbUnit        = $query->getTimeUnitFromDateRange($dateFrom, $dateTo);
            $dbUnit        = $query->translateTimeUnit($dbUnit);
            $dateConstruct = "DATE_FORMAT(CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'), '$dbUnit.')";
            foreach ($campaigns as $campaignId => $campaignName) {
                $q = $query->prepareTimeDataQuery(
                    'contactsource_stats',
                    'date_added',
                    [
                        'contactsource_id' => (int) $contactSource->getId(),
                        'type'             => Stat::TYPE_ACCEPTED,
                    ]
                );
                if (!$canViewOthers) {
                    $this->limitQueryToCreator($q);
                }
                $q->select($dateConstruct.' AS date, ROUND(SUM(t.attribution) * -1, 2) AS count')
                    ->andWhere('campaign_id = :campaign_id'.$campaignId)
                    ->setParameter('campaign_id'.$campaignId, $campaignId)
                    ->groupBy($dateConstruct);
                $data = $query->loadAndBuildTimeData($q);
                foreach ($data as $val) {
                    if (0 !== $val) {
                        if (empty($campaignName)) {
                            $campaignName = 'No Campaign';
                        }
                        $chart->setDataset($campaignName, $data);
                        break;
                    }
                }
            }
        }

        return $chart->render();
    }
301480
public function listCampaigns($limit = null, $offset = null)
    {
        $data = array();
        if (!empty($limit)) {
            $data['limit'] = $limit;
        }
        if (!empty($offset)) {
            $data['offset'] = $offset;
        }
        $requestResult = $this->sendRequest('campaigns', 'GET', $data);

        return $this->handleResult($requestResult);
    }
362059
public function listCampaignSourcesAction($campaignId)
    {
        $campaignId     = intval($campaignId);
        $table_alias    = $this->model->getRepository()->getTableAlias();
        $campaignFilter = [
            'column' => $table_alias.'.campaign_settings',
            'expr'   => 'like', //like
            'value'  => '%"campaignId": "'.$campaignId.'"%',
        ];

        $this->extraGetEntitiesArguments = [
            'filter' => [
                'where' => [
                    $campaignFilter,
                ],
            ],
        ];

        return $this->getEntitiesAction();
    }
473578
private function createCustomerFirstAbandonedCart($quoteCollection, $storeId, $campaignId)
    {
        $result = 0;
        foreach ($quoteCollection as $quote) {
            $websiteId = $this->helper->storeManager->getStore($storeId)->getWebsiteId();
            if (! $this->updateDataFieldAndCreateAc($quote, $websiteId, $storeId)) {
                continue;
            }

            //send campaign; check if valid to be sent
            if ($this->isLostBasketCustomerEnabled(self::CUSTOMER_LOST_BASKET_ONE, $storeId)) {
                $this->sendEmailCampaign(
                    $quote->getCustomerEmail(),
                    $quote,
                    $campaignId,
                    self::CUSTOMER_LOST_BASKET_ONE,
                    $websiteId
                );
            }

            $this->totalCustomers++;
            $result = $this->totalCustomers;
        }

        return $result;
    }
144622
public function getFilteredTasksList($search = null, $order_by = null, $start = 0, $limit = null){
        $res = array();
            
        $sql = 'SELECT majat_name, majat_status, majat_last_run, majat_last_result, majat_frequency, majat_nb_occur, majat_running' .
            ' FROM `##maj_admintasks`';
        
        $args = array();
                
        if ($order_by) {
            $sql .= ' ORDER BY ';
            $i = 0;
            foreach ($order_by as $key => $value) {
                if ($i > 0) {
                    $sql .= ',';
                }
                
                switch ($value['dir']) {
                    case 'asc':
                        $sql .= $value['column'] . ' ASC ';
                        break;
                    case 'desc':
                        $sql .= $value['column'] . ' DESC ';
                        break;
                }
                $i++;
            }
        } else {
            $sql .= ' ORDER BY majat_name ASC';
        }
        
        if ($limit) {
            $sql .= ' LIMIT :limit OFFSET :offset';
            $args['limit']  = $limit;
            $args['offset'] = $start;
        }
            
        $data = Database::prepare($sql)->execute($args)->fetchAll(\PDO::FETCH_ASSOC);

        foreach($data as $ga) {
            $task = $this->loadTaskFromRow($ga);
			if($task && (empty($search) || ($search && strpos($task->getTitle(), $search) !== false)))
			{
				$res[] = $task;
			}
        }
		
        return $res;
    }
1010467
public function getTasks($bundleName = null, $moduleIdentifier = null, $campaignId = null){
        $qb = $this->em->createQueryBuilder();
        $qb->select('c')
            ->from('CampaignChain\CoreBundle\Entity\Campaign', 'c');

        if(isset($bundleName) && isset($moduleIdentifier)){
            $qb->from('CampaignChain\CoreBundle\Entity\Module', 'm')
                ->from('CampaignChain\CoreBundle\Entity\Bundle', 'b')
                ->where('b.name = :bundleName')
                ->andWhere('m.identifier = :moduleIdentifier')
                ->andWhere('m.id = c.campaignModule')
                ->setParameter('bundleName', $bundleName)
                ->setParameter('moduleIdentifier', $moduleIdentifier);
        }

        if(isset($campaignId)){
            $qb->andWhere('c.id = :campaignId')
                ->setParameter('campaignId', $campaignId);
        }

        $qb->andWhere('c.parent IS NULL');

        $qb->orderBy('c.startDate', 'DESC');

        $query = $qb->getQuery();
        $campaigns = $query->getResult();

        //$ganttTask = $campaigns;

        // Create GANTT data
        $ganttDataId = 1;
        $ganttLinkId = 1;

        foreach($campaigns as $campaign){
            $campaign_data['text'] = $campaign->getName();
            // Define the trigger hook's identifier.
            if($campaign->getTriggerHook()){
                //$campaign_data['trigger_identifier'] = str_replace('-', '_', $campaign->getTriggerHook()->getIdentifier());
                // Retrieve the start and end date from the trigger hook.
                $hookService = $this->container->get($campaign->getTriggerHook()->getServices()['entity']);
                $hook = $hookService->getHook($campaign);
                $campaign_data['start_date'] = $hook->getStartDate()->format(self::FORMAT_TIMELINE_DATE);
                if($hook->getEndDate()){
                    $campaign_data['end_date'] = $hook->getEndDate()->format(self::FORMAT_TIMELINE_DATE);
                } else {
                    $campaign_data['end_date'] = $campaign_data['start_date'];
                }
                // Provide the hook's start and end date form field names.
                //$campaign_data['start_date_identifier'] = $hookService->getStartDateIdentifier();
                //$campaign_data['end_date_identifier'] = $hookService->getEndDateIdentifier();
            }
            $campaignId = $campaign->getId();
//            $campaign_data['id'] = (string) $ganttDataId;
            $campaign_data['id'] = (string) $campaign->getId().'_campaign';
            $campaign_data['campaignchain_id'] = (string) $campaign->getId();
            $campaign_data['type'] = 'campaign';
            $campaign_data['route_edit_api'] = $campaign->getCampaignModule()->getRoutes()['edit_api'];
            $campaign_data['route_plan_detail'] = $campaign->getCampaignModule()->getRoutes()['plan_detail'];
            $campaignService = $this->container->get('campaignchain.core.campaign');
            $campaign_data['tpl_teaser'] = $campaignService->tplTeaser(
                $campaign->getCampaignModule(),
                array(
                    'only_icon' => true,
                    'size' => 24,
                )
            );
            $ganttDataId++;
//            $campaign['entity'] = array(
//                'id' => $campaignId,
//                'name' => 'Campaign',
//            );
            $ganttCampaignData[] = $campaign_data;

            // Get activities of campaign
            $qb = $this->em->createQueryBuilder();
            $qb->select('a')
                ->from('CampaignChain\CoreBundle\Entity\Activity', 'a')
                ->where('a.campaign = :campaignId')
                ->andWhere('a.parent IS NULL')
                ->setParameter('campaignId', $campaignId)
                ->orderBy('a.startDate', 'ASC');
            $query = $qb->getQuery();
            $activities = $query->getResult();

            if(is_array($activities) && count($activities)){
                foreach($activities as $activity){
                    $activity_data['text'] = $activity->getName();

                    // Define the trigger hook's identifier.
                    //$activity_data['trigger_identifier'] = str_replace('-', '_', $activity->getTriggerHook()->getIdentifier());
                    // Retrieve the start and end date from the trigger hook.
                    $hookService = $this->container->get($activity->getTriggerHook()->getServices()['entity']);
                    $hook = $hookService->getHook($activity);
                    $activity_data['start_date'] = $hook->getStartDate()->format(self::FORMAT_TIMELINE_DATE);
                    if($hook->getEndDate()){
                        $activity_data['end_date'] = $hook->getEndDate()->format(self::FORMAT_TIMELINE_DATE);
                    } else {
                        $activity_data['end_date'] = $activity_data['start_date'];
                    }
                    // Provide the hook's start and end date form field names.
                    //$activity_data['start_date_identifier'] = $hookService->getStartDateIdentifier();
                    //$activity_data['end_date_identifier'] = $hookService->getEndDateIdentifier();

//                    $activity_data['start_date'] = $activity_data['end_date'] = $activity->getDue()->format(self::FORMAT_TIMELINE_DATE);
//                    $activity_data['id'] = $ganttDataId;
                    $activity_data['id'] = (string) $activity->getId().'_activity';
                    $ganttDataId++;
                    $activity_data['campaignchain_id'] = (string) $activity->getId();
                    $activity_data['parent'] = $campaign_data['id'];
                    $activity_data['type'] = 'activity';
//                    $activity_data['form_root_name'] = $activity->getActivityModule()->getFormRootName();
                    $activity_data['route_edit_api'] = $activity->getActivityModule()->getRoutes()['edit_api'];
                    $activity_data['route_read_modal'] = $activity->getActivityModule()->getRoutes()['read_modal'];
                    // Get activity icons path
                    $activityService = $this->container->get('campaignchain.core.activity');
                    $activity_data['tpl_teaser'] = $activityService->tplTeaser($activity, array('only_icon' => true));

                    $ganttActivityData[] = $activity_data;
                    $ganttActivityLinks[] = array(
                        'id' => $ganttLinkId,
                        'source' => $campaign_data['id'],
                        'target' => $activity_data['id'],
                        'type' => '1',
                    );
                    $ganttLinkId++;

                    // TODO: Retrieve GANTT data for operations of an activity if the activity does not equal the operation.
                }
            }

            // Get milestones of campaign
            $qb = $this->em->createQueryBuilder();
            $qb->select('m')
                ->from('CampaignChain\CoreBundle\Entity\Milestone', 'm')
                ->where('m.campaign = :campaignId')
                ->setParameter('campaignId', $campaignId)
                ->orderBy('m.startDate', 'ASC');
            $query = $qb->getQuery();
            $milestones = $query->getResult();

            if(is_array($milestones) && count($milestones)){
                foreach($milestones as $milestone){
                    $milestone_data['text'] = $milestone->getName();
                    // Define the trigger hook's identifier.
                    //$milestone_data['trigger_identifier'] = str_replace('-', '_', $milestone->getTriggerHook()->getIdentifier());
                    // Retrieve the start and end date from the trigger hook.
                    $hookService = $this->container->get($milestone->getTriggerHook()->getServices()['entity']);
                    $hook = $hookService->getHook($milestone);
                    $milestone_data['start_date'] = $hook->getStartDate()->format(self::FORMAT_TIMELINE_DATE);
                    if($hook->getEndDate()){
                        $milestone_data['end_date'] = $hook->getEndDate()->format(self::FORMAT_TIMELINE_DATE);
                    } else {
                        $milestone_data['end_date'] = $milestone_data['start_date'];
                    }
                    // Provide the hook's start and end date form field names.
                    //$milestone_data['start_date_identifier'] = $hookService->getStartDateIdentifier();
                    //$milestone_data['end_date_identifier'] = $hookService->getEndDateIdentifier();
//                    $milestone_data['id'] = $ganttDataId;
                    $milestone_data['id'] = (string) $milestone->getId().'_milestone';
                    $ganttDataId++;
                    $milestone_data['campaignchain_id'] = (string) $milestone->getId();
                    $milestone_data['parent'] = $campaign_data['id'];
                    $milestone_data['type'] = 'milestone';
                    $milestone_data['route_edit_api'] = $milestone->getMilestoneModule()->getRoutes()['edit_api'];
                    $milestone_data['route_read_modal'] = $milestone->getMilestoneModule()->getRoutes()['edit_api'];
                    // Get icons path
                    $milestoneService = $this->container->get('campaignchain.core.milestone');
                    $icons = $milestoneService->getIcons($milestone);
                    $milestone_data['icon_path_16px'] = $icons['16px'];
                    $milestone_data['icon_path_24px'] = $icons['24px'];

                    $ganttMilestoneData[] = $milestone_data;
                    $ganttMilestoneLinks[] = array(
                        'id' => $ganttLinkId,
                        'source' => $campaign_data['id'],
                        'target' => $milestone_data['id'],
                        'type' => '1',
                    );
                    $ganttLinkId++;
                }
            }
        }

        $ganttTasks = array();

        if(isset($ganttCampaignData) && is_array($ganttCampaignData)){
            $hasMilestones = false;
            $hasActivities = false;

            $ganttTasks['data'] = $ganttCampaignData;
            if(isset($ganttMilestoneData) && is_array($ganttMilestoneData)){
                $ganttTasks['data'] = array_merge($ganttTasks['data'], $ganttMilestoneData);
                $hasMilestones = true;
            }
            if(isset($ganttActivityData) && is_array($ganttActivityData)){
                $ganttTasks['data'] = array_merge($ganttTasks['data'], $ganttActivityData);
                $hasActivities = true;
            }
            if($hasMilestones && $hasActivities){
                $ganttTasks['links'] = array_merge($ganttActivityLinks, $ganttMilestoneLinks);
            } elseif($hasMilestones){
                $ganttTasks['links'] = $ganttMilestoneLinks;
            } elseif($hasActivities){
                $ganttTasks['links'] = $ganttActivityLinks;
            }
        } else {
            $this->container->get('session')->getFlashBag()->add(
                'warning',
                'No campaigns available yet. Please create one.'
            );

            header('Location: '.
                $this->container->get('router')->generate('campaignchain_core_campaign_new')
            );
            exit;
        }

        return $this->serializer->serialize($ganttTasks, 'json');
    }
452429
private function getCampaignsToSend($emailsToSend, $website)
    {
        $campaignsToSend = [];
        foreach ($emailsToSend as $campaign) {
            $email = $campaign->getEmail();
            $campaignId = $campaign->getCampaignId();
            $websiteId = $website->getId();
            $client = false;
            if ($this->helper->isEnabled($websiteId)) {
                $client = $this->helper->getWebsiteApiClient($websiteId);
            }
            //Only if valid client is returned
            if ($client && $this->isCampaignValid($campaign)) {
                $campaignsToSend[$campaignId]['client'] = $client;
                $contact = $this->helper->getContact(
                    $campaign->getEmail(),
                    $websiteId
                );
                if ($contact && isset($contact->id)) {
                    //update data fields
                    if ($campaign->getEventName() == 'Order Review') {
                        $this->updateDataFieldsForORderReviewCampaigns($campaign, $websiteId, $client, $email);
                    } elseif ($campaign->getEventName() ==
                        \Dotdigitalgroup\Email\Model\Campaign::CAMPAIGN_EVENT_LOST_BASKET
                    ) {
                        $campaignCollection = $this->campaignCollection->create();
                        // If AC campaigns found with status processing for given email then skip for current cron run
                        if ($campaignCollection->getNumberOfAcCampaignsWithStatusProcessingExistForContact($email)) {
                            continue;
                        }
                        $this->helper->updateLastQuoteId($campaign->getQuoteId(), $email, $websiteId);
                    }

                    $campaignsToSend[$campaignId]['contacts'][] = $contact->id;
                    $campaignsToSend[$campaignId]['ids'][] = $campaign->getId();
                } else {
                    //update the failed to send email message error message
                    $campaign->setSendStatus(\Dotdigitalgroup\Email\Model\Campaign::FAILED)
                        ->setMessage('Send not permitted. Contact is suppressed.');
                    $this->campaignResourceModel->saveItem($campaign);
                }
            }
        }

        return $campaignsToSend;
    }
206996
public function getStats($contactClientId, $type, $fromDate = null, $toDate = null)
    {
        $q = $this->createQueryBuilder('s');

        $expr = $q->expr()->andX(
            $q->expr()->eq('IDENTITY(s.contactclient)', (int) $contactClientId),
            $q->expr()->eq('s.type', ':type')
        );

        if ($fromDate) {
            $expr->add(
                $q->expr()->gte('s.dateAdded', ':fromDate')
            );
            $q->setParameter('fromDate', $fromDate);
        }
        if ($toDate) {
            $expr->add(
                $q->expr()->lte('s.dateAdded', ':toDate')
            );
            $q->setParameter('toDate', $toDate);
        }

        $q->where($expr)
            ->setParameter('type', $type);

        return $q->getQuery()->getArrayResult();
    }
517766
public static function get_user_contacts(int $userid, int $limitfrom = 0, int $limitnum = 0) {
        global $DB;

        $sql = "SELECT *
                  FROM {message_contacts} mc
                 WHERE mc.userid = ? OR mc.contactid = ?
              ORDER BY timecreated DESC, id ASC";
        if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
            $userids = [];
            foreach ($contacts as $contact) {
                if ($contact->userid == $userid) {
                    $userids[] = $contact->contactid;
                } else {
                    $userids[] = $contact->userid;
                }
            }
            return helper::get_member_info($userid, $userids);
        }

        return [];
    }
925513
public function updateCampaignSchedule($CampaignId, $date)
    {
        $response = $this->mailjet->put(Resources::$CampaigndraftSchedule,
            ['id' => $CampaignId, 'body' => $date]);
        if (!$response->success()) {
            $this->throwError("CampaignDraftService:updateCampaignSchedule 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;
    }
123065
public function getContactUrlsFromContactId( $ContactEntryId){
        $service = sprintf( self::API_CONTACT_URLS, $ContactEntryId);
        $rest = $this->getService( $service);
        $rest->GET();

        return $rest->getResultAsArray( models\Call\ContactUrl::class);
    }