@param $campaign_id
@param $bounce_type
@param $start_date
@param $end_date

@return array
@throws Exception

API documentation: https://whatcounts.zendesk.com/hc/en-us/articles/204670105
429950
public function reportBounceStatistics($campaign_id, $bounce_type, $start_date, $end_date)
		{
			$form_data = array(
				'campaign_id' => $campaign_id,
				'bounce_type' => $bounce_type,
				'from_date' => $start_date,
				'to_date' => $end_date,
				'headers' => 1
			);
			$data = $this->call('rpt_bounce_stats', $form_data, 'csv');
			$data .= PHP_EOL;
			$csv = new \parseCSV($data);

			return $csv->data;
		}
681660
public function getTopReferrersForPeriod($startDate, $endDate, $maxResults)
    {
        $referrerData = [];

        $answer = $this->performQuery($startDate, $endDate, 'ga:pageviews', ['dimensions' => 'ga:fullReferrer', 'sort' => '-ga:pageviews', 'max-results' => $maxResults]);

        if (is_null($answer->rows)) {
            return new Collection([]);
        }

        foreach ($answer->rows as $pageRow) {
            $referrerData[] = ['url' => $pageRow[0], 'pageViews' => $pageRow[1]];
        }

        return new Collection($referrerData);
    }
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;
  }
689672
public function getAdverts($start, $end, $section=null)
    {
    
        if($count == 0){
            $count2 = 0;

            $qb2 = $this->getQueryBuilder() 
            ->join('a.located', 'l')
            ->where('l.name = :section')
            ->andWhere('a.from <= :start')
            ->andWhere('a.to >= :end')
            ->andWhere('a.active = :active')
            ->setParameters(array(
                'section' => $section, 
                'start' => $start, 
                'end' => $end,
                'active' => true,
                ));

            $query = $qb2->getQuery();
        }
        
        //->orderBy('s.day', 'ASC')
        $adverts = array();
        if(is_object($query)){
            $adverts = $query->getResult();
        }
        
        $arr = new \Doctrine\Common\Collections\ArrayCollection();
        foreach ($adverts as $ad) {
            $arr->add($ad);
        }
        
        return $arr;
    }
941138
public static function activityDay(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id)
    {
        $databox = $app->findDataboxById($sbas_id);
        $conn = $databox->get_connection();
        $result = array();
        $res = array();
        $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);

        $params = [':site_id' => $app['conf']->get(['main', 'key'])];
        $params = array_merge($params, $datefilter['params']);
/*
        $sql = "
            SELECT tt.ddate, COUNT( DATE_FORMAT( tt.ddate, '%d' ) ) AS activity
            FROM (
                SELECT DISTINCT(log_date.id), DATE_FORMAT( log_date.date, '%Y-%m-%d' ) AS ddate
                FROM log AS log_date FORCE INDEX (date_site) INNER JOIN log_colls FORCE INDEX (couple) ON (log_date.id = log_colls.log_id)
                WHERE " . $datefilter['sql'] . "
                AND log_date.site = :site_id" .
            (('' !== $collfilter['sql']) ?  (" AND (" . $collfilter['sql'] . ")") : '')
            . ") AS tt
            GROUP by  tt.ddate
            ORDER BY  tt.ddate ASC";
*/
        $sql = "SELECT tt.ddate, COUNT( DATE_FORMAT( tt.ddate, '%d' ) ) AS activity\n"
            . " FROM (\n"
            . "     SELECT DISTINCT(log_date.id), DATE_FORMAT( log_date.date, '%Y-%m-%d' ) AS ddate\n"
            . "     FROM log AS log_date FORCE INDEX (date_site)\n"
            . "     WHERE " . $datefilter['sql'] . "\n"
            . "     AND log_date.site = :site_id AND !ISNULL(usrid)"
            . ") AS tt\n"
            . " GROUP by  tt.ddate\n"
            . " ORDER BY  tt.ddate ASC";

// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);

        $stmt = $conn->prepare($sql);
        $stmt->execute($params);
        $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $stmt->closeCursor();

        foreach ($rs as $row) {
            $date = new DateTime($row['ddate']);
            $result[$date->format(DATE_ATOM)] = $row['activity'];
        }

        foreach ($result as $key => $act) {
            $res[$key] = number_format($act, 2, '.', '');
        }

        return $res;
    }
1295177
def reports(from_id, start_date = nil, end_date = nil)
      params = []

      if from_id
        params << "from_id=#{from_id}"
      end

      if start_date and not end_date
        raise 'must include both start_date and end_date'
      end
      if end_date and not start_date
        raise 'must include both start_date and end_date'
      end

      if start_date and end_date
        params << "start_date=#{start_date.strftime('%FT%T.%L%z')}"
        params << "end_date=#{end_date.strftime('%FT%T.%L%z')}"
      end

      query = "#{@endpoint}?"

      if params.size > 0
        query << params.join('&')
      end

      get query
    end
728225
public function getRouteCalendars($externalCoverageId, $externalRouteId, \DateTime $startDate, \DateTime $endDate)
    {
        $query = array(
            'api' => 'coverage',
            'parameters' => array(
                'region' => $externalCoverageId,
                'action' => 'calendars',
                'path_filter' => 'routes/'.$externalRouteId,
                'parameters' => '?start_date='.$startDate->format($this->dateFormat).'&end_date='.$endDate->format($this->dateFormat),
            ),
        );

        return $this->navitia_component->call($query);
    }
894252
public function during($startDate, $endDate)
    {
        $validationResult = QueryValidator::validateCustomDateRange(
            $startDate,
            $endDate
        );
        if ($validationResult->isFailed()) {
            throw new InvalidArgumentException('The start or end date is' .
                ' invalid. Validation fail reasons: ' .
                $validationResult->getFailReason());
        }

        $this->duringStartDate = $startDate;
        $this->duringEndDate = $endDate;
    }
343764
public function getListUserCountByRangeDate($types, $startDate = '', $endDate = '')
    {
        if (empty($types)) {
            return array();
        }
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');

        $now = new \DateTime("now");
        // $now->format('Y-m-d') . ' 23:59:59';
        $startDateTime = \DateTime::createFromFormat('d/m/Y', $startDate);
        $endDateTime = \DateTime::createFromFormat('d/m/Y', $endDate);

        $rsm = new \Doctrine\ORM\Query\ResultSetMapping;

        $select = array();
        $i = 0;

        foreach ($types as $type) {
            switch ($type) {
                case 'validatedMembers':
                    $filter = "u.state IS NOT NULL";
                    break;
                case 'activeMembers':
                    $filter = "u.state=1";
                    break;
                case 'optin':
                    $filter = "u.optin=1";
                    break;
                case 'optinPartners':
                    $filter = "u.optin_partner=1";
                    break;
                case 'unregistered':
                    $filter = "u.state IS NULL";
                    break;
                case 'suspended':
                    $filter = "u.state=2";
                    break;
                default:
                case 'members':
                    $filter = "u.user_id";
                    break;
            }

            $rsm->addScalarResult('c'.$i, 'c'.$i);
            $select[] = 'SUM(CASE WHEN '.$filter.' THEN 1 ELSE 0 END) AS c'.$i;
            $rsm->addScalarResult('c'.$i.'_male', 'c'.$i.'_male');
            $select[] = 'SUM(CASE WHEN '.$filter.' AND (u.title=\'M\' OR u.title IS NULL) THEN 1 ELSE 0 END) AS c'.$i.'_male';
            $rsm->addScalarResult('c'.$i.'_female', 'c'.$i.'_female');
            $select[] = 'SUM(CASE WHEN '.$filter.' AND u.title=\'Me\' THEN 1 ELSE 0 END) AS c'.$i++.'_female';
        }

        if ($startDate != '' && $endDate != '') {
            $dateRange = "(u.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0' AND u.created_at <= '" . $endDateTime->format('Y-m-d') . " 0:0:0')";
        } elseif ($startDate == '' && $endDate != '') {
            $dateRange = "u.created_at <= '" . $endDateTime->format('Y-m-d') . " 0:0:0'";
        } elseif ($startDate != '' && $endDate == '') {
            $dateRange = "u.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0'";
        } else {
            $dateRange = "u.created_at IS NOT NULL";
        }
        $query = $em->createNativeQuery('
			SELECT '.implode(',', $select).' FROM user AS u
			WHERE ' . $dateRange, $rsm);
        return array_values($query->getSingleResult());
    }
1143339
public function getCampaignRevenueChartData(Campaign $campaign, \DateTime $dateFrom, \DateTime $dateTo)
    {
        $container = $this->dispatcher->getContainer();
        $chartData = ['labels' => [], 'datasets' => []];
        $labels    = $costs = $revenues = $profits = [];
        $cache_dir = $container->getParameter('kernel.cache_dir');

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

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

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

        // Prepare data for chart rendering

        // fix when only 1 result
        if (!empty($data)) {
            foreach ($data as $item) {
                $labels[] = $item['label'];

                $costs[]    = self::formatDollar(-$item['cost']);
                $revenues[] = self::formatDollar($item['revenue']);
                $profits[]  = self::formatDollar($item['profit']);
            }

            $chartData = [
                'labels'   => $labels,
                'datasets' => [
                    [
                        'label'                     => 'Cost',
                        'data'                      => $costs,
                        'backgroundColor'           => 'rgba(204,51,51,0.1)',
                        'borderColor'               => 'rgba(204,51,51,0.8)',
                        'pointHoverBackgroundColor' => 'rgba(204,51,51,0.75)',
                        'pointHoverBorderColor'     => 'rgba(204,51,51,1)',
                    ],
                    [
                        'label'                     => 'Revenue',
                        'data'                      => $revenues,
                        'backgroundColor'           => 'rgba(51,51,51,0.1)',
                        'borderColor'               => 'rgba(51,51,51,0.8)',
                        'pointHoverBackgroundColor' => 'rgba(51,51,51,0.75)',
                        'pointHoverBorderColor'     => 'rgba(51,51,51,1)',
                    ],
                    [
                        'label'                     => 'Profit',
                        'data'                      => $profits,
                        'backgroundColor'           => 'rgba(51,170,51,0.1)',
                        'borderColor'               => 'rgba(51,170,51,0.8)',
                        'pointHoverBackgroundColor' => 'rgba(51,170,51,0.75)',
                        'pointHoverBorderColor'     => 'rgba(51,170,51,1)',
                    ],
                ],
            ];
        }

        return $chartData;
    }
976369
protected function get_student_activities($sampleid, $tablename, $starttime, $endtime) {

        // May not be available.
        $user = $this->retrieve('user', $sampleid);

        if ($this->course === null) {
            // The indicator scope is a range, so all activities belong to the same course.
            $this->course = \core_analytics\course::instance($this->retrieve('course', $sampleid));
        }

        if ($this->activitylogs === null) {
            // Fetch all activity logs in each activity in the course, not restricted to a specific sample so we can cache it.

            $courseactivities = $this->course->get_all_activities($this->get_activity_type());

            // Null if no activities of this type in this course.
            if (empty($courseactivities)) {
                $this->activitylogs = false;
                return null;
            }
            $this->activitylogs = $this->fetch_activity_logs($courseactivities, $starttime, $endtime);
        }

        if ($this->grades === null) {
            // Even if this is probably already filled during fill_per_analysable_caches.
            $this->fetch_student_grades($this->course);
        }

        if ($cm = $this->retrieve('cm', $sampleid)) {
            // Samples are at cm level or below.
            $useractivities = array(\context_module::instance($cm->id)->id => $cm);
        } else {
            // Activities that should be completed during this time period.
            $useractivities = $this->get_activities($starttime, $endtime, $user);
        }

        return $useractivities;
    }
39344
public function addRescheduleItemToSession($startDay = 1, $endDay = 7, \DateTime $startTime = null, $reason = null)
    {
        $result = false;
        if (isset($this->getEvent()['leadEventLog'])) {
            // To randomly disperse API requests we must get all openings within the date range first.
            $all = 'api' === $this->contactClient->getType();

            // Get all openings if API, otherwise just get the first available.
            $openings = $this->payloadModel->getScheduleModel()->findOpening($startDay, $endDay, 1, $all, $startTime);
            if ($openings) {
                // Select an opening.
                if ($all) {
                    $opening = $openings[rand(0, count($openings) - 1)];
                } else {
                    $opening = reset($openings);
                }
                /**
                 * @var \DateTime
                 * @var $end      \DateTime
                 */
                list($start, $end) = $opening;

                // Randomly disperse within this range of time if needed.
                if ($all) {
                    // How many seconds are there in this range, minus a minute for margin of error at the end of day?
                    $rangeSeconds = max(0, ($end->format('U') - $start->format('U') - 60));
                    $randSeconds  = rand(0, $rangeSeconds);
                    $start->modify('+'.$randSeconds.' seconds');
                }

                // Add leadEventLog id instance to global session array for later processing in reschedule() dispatch.
                $eventLogId          = $this->getEvent()['leadEventLog']->getId();
                $events              = $this->getSession()->get('contact.client.reschedule.event', []);
                $events[$eventLogId] = [
                    'triggerDate' => $start,
                    'reason'      => $reason,
                ];
                $this->getSession()->set('contact.client.reschedule.event', $events);
                $result = true;
            }
        }

        return $result;
    }
263279
public function isExecutableByCampaignByInterval($content, \DateTime $startDate, $interval, $errMsg)
    {
        /** @var Campaign $campaign */
        $campaign = $content->getOperation()->getActivity()->getCampaign();

        if($campaign->getInterval()){
            $campaignIntervalDate = new \DateTime();
            $campaignIntervalDate->modify($campaign->getInterval());
            $maxDuplicateIntervalDate = new \DateTime();
            $maxDuplicateIntervalDate->modify($interval);

            if($maxDuplicateIntervalDate > $campaignIntervalDate){
                return array(
                    'status' => false,
                    'message' => $errMsg,
                );
            }
        }

        return $this->isExecutableByCampaign(
            $content, $content->getOperation()->getActivity()->getStartDate()
        );
    }
878513
public function listEvents(Carbon $startDateTime = null, Carbon $endDateTime = null, array $queryParameters = []): array
    {
        $parameters = [
            'singleEvents' => true,
            'orderBy' => 'startTime',
        ];

        if (is_null($startDateTime)) {
            $startDateTime = Carbon::now()->startOfDay();
        }

        $parameters['timeMin'] = $startDateTime->format(DateTime::RFC3339);

        if (is_null($endDateTime)) {
            $endDateTime = Carbon::now()->addYear()->endOfDay();
        }
        $parameters['timeMax'] = $endDateTime->format(DateTime::RFC3339);

        $parameters = array_merge($parameters, $queryParameters);

        return $this
            ->calendarService
            ->events
            ->listEvents($this->calendarId, $parameters)
            ->getItems();
    }
247645
public function remove_from_drip_campaign($recipient_address, $drip_campaign_id){
        $endpoint = "drip_campaigns/" . $drip_campaign_id . "/deactivate";

        $payload = array(
            "recipient_address" => $recipient_address
        );

        return $this->api_request($endpoint, self::HTTP_POST, $payload);
    }
145727
protected function getEventOptions(CsvTable $table, EntityInterface $entity, string $startField) : array
    {
        // Event start and end times
        $eventTimes = $this->getEventTime($entity, $startField);

        $mailer = new IcEmail($table, $entity);

        $result = [
            'id' => $entity->get('id'),
            'sequence' => $entity->isNew() ? 0 : time(),
            'summary' => $mailer->getEventSubject(),
            'description' => $mailer->getEventContent(),
            'location' => (string)$entity->get('location'),
            'startTime' => $eventTimes['start'],
            'endTime' => $eventTimes['end'],
        ];

        return $result;
    }
1278579
public function reportTrackedEvents($event_type, $start_datetime, $end_datetime, $offset=0)
		{
			$form_data = array(
				'event_type' => $event_type,
				'start_datetime' => $start_datetime,
				'end_datetime' => $end_datetime,
				'offset' => $offset
			);
			$xml = $this->call('rpt_tracked_events', $form_data);

			return json_decode(json_encode($xml), TRUE);
		}