Returns an iCal feed for this calendar

@param int    $starttime Range start timestamp
@param int    $endtime   Range end timestamp
@param string $filename  Filename used for output file
@return string
434881
public function toIcal($starttime = null, $endtime = null, $filename = 'calendar.ics') {

		if (is_null($starttime)) {
			$starttime = time();
		}
		if (is_null($endtime)) {
			$endtime = strtotime('+1 year', $starttime);
		}

		$instances = $this->getAllEventInstances($starttime, $endtime, true, 'ical');

		$config = array(
			'unique_id' => $this->guid,
			// setting these explicitly until icalcreator bug #14 is solved
			'allowEmpty' => true,
			'nl' => "\r\n",
			'format' => 'iCal',
			'delimiter' => DIRECTORY_SEPARATOR,
			'filename' => $filename, // this is last until #14 is solved
		);

		$v = new vcalendar($config);
		$v->setProperty('method', 'PUBLISH');
		$v->setProperty("X-WR-CALNAME", implode(' - ', array(elgg_get_config('sitename'), $this->getDisplayName())));
		$v->setProperty("X-WR-CALDESC", strip_tags($this->description));
		$v->setProperty("X-WR-TIMEZONE", Util::UTC);
		foreach ($instances as $instance) {

			$e = & $v->newComponent('vevent');

			$organizer = elgg_extract('organizer', $instance, array());
			unset($instance['organizer']);

			$reminders = elgg_extract('reminders', $instance, array());
			unset($instance['reminders']);

			foreach ($instance as $property => $value) {
				$e->setProperty($property, $value);
			}

			if (!empty($organizer)) {
				if (is_email_address($organizer)) {
					$e->setProperty('organizer', $organizer);
				} else {
					$e->setProperty('organizer', elgg_get_site_entity()->email, array(
						'CN' => $organizer,
					));
				}
			}

			if (!empty($reminders)) {
				foreach ($reminders as $reminder) {
					$a = & $e->newComponent('valarm');
					$a->setProperty('action', 'DISPLAY');
					$a->setProperty('trigger', "-PT{$reminder}S");
				}
			}
		}

		$v->returnCalendar();
	}
574583
public function getLeads($startDate, $endDate, array $params = array())
    {
        $isValidStartDate = $this->utils->isSystemDatetime($startDate);
        $isValidEndDate = $this->utils->isSystemDatetime($endDate);
        if (!$isValidEndDate || !$isValidStartDate) {
            throw new InvalidArgumentException('Invalid params: Only system date has available YYYY-MM-DDD HH:II:SS');
        }

        if ($startDate > $endDate) {
            throw new InvalidArgumentException('Invalid params: start_date > end_date');
        }

        $isOutOfLimit = $this->utils->isOutOfLimit($startDate, $endDate, LeadAcademic::LIMIT_PERIOD);
        if ($isOutOfLimit) {
            throw new InvalidArgumentException('Invalid params: Period is too large. Available only ' . LeadAcademic::LIMIT_PERIOD);
        }

        $params['date_lbound'] = $startDate;
        $params['date_ubound'] = $endDate;

        $this->normalizeParams($params);
        $response = $this->execute('/', $params);
        $data = $this->normalize($response);
        return $data['leads'];
    }
204158
public function getVisitorsAndPageViewsForPeriod($startDate, $endDate, $groupBy = 'date')
    {
        $visitorData = [];
        $answer = $this->performQuery($startDate, $endDate, 'ga:visits,ga:pageviews', ['dimensions' => 'ga:'.$groupBy]);

        foreach ($answer->rows as $dateRow) {
            $visitorData[] = [$groupBy => Carbon::createFromFormat(($groupBy == 'yearMonth' ? 'Ym' : 'Ymd'), $dateRow[0]), 'visitors' => $dateRow[1], 'pageViews' => $dateRow[2]];
        }

        return new Collection($visitorData);
    }
195902
private function getInvoices(DateTime $startDate, DateTime $endDate)
    {
        $offset = Mirakl::MIRAKL_API_MAX_PAGINATE;

        $invoicesData = $this->mirakl->getInvoices(
            $startDate,
            $endDate
        );

        $invoices = array_merge(array(), $invoicesData['invoices']);

        $total = $invoicesData['total_count'];

        while ($total % $offset !== $total) {

            $invoicesData = $this->mirakl->getInvoices(
                $startDate,
                $endDate,
                Mirakl::MIRAKL_API_MAX_PAGINATE,
                $offset
            );

            $invoices = array_merge($invoices, $invoicesData['invoices']);

            $offset += Mirakl::MIRAKL_API_MAX_PAGINATE;
        }

        return $invoices;
    }
712094
public function getEntityPayments($startDate, $endDate)
    {
        $requestInterval = new Structure\RequestInterval($startDate, $endDate);

        $this->response = parent::getEntityPayments($this->entity, $requestInterval);

        /**
         * Checks the state of the platform integration.
         */
        if (Exception\IntegrationState::check($this->response->integrationState)) {
            throw new Exception\IntegrationState($this->response->integrationState);
        }

        return $this->response;
    }
342652
public function getTimeEntries($startdate = null, $enddate = null)
    {
        if (empty($startdate)) {
            $startdate = date('Y-m-d', time() - 86400);
        }
        if (empty($enddate)) {
            $enddate = $startdate;
        }
        $this->uri = 'https://toggl.com/reports/api/v2/details?user_agent=' . $this->user_agent . '&since=' . $startdate . '&until=' . $enddate . '&workspace_id=' . $this->workspace_id;

        $data = null;
        
        $response = $this->processRequest($data, self::GET);
        $this->_handleError($data, $response);
        $toggl_entries = $this->processTogglResponse($response);
        $timeEntries = [];
        foreach ($toggl_entries as $entry) {
            $te = new TimeEntry(
                $this,
                $entry->id,
                $entry->client,
                $entry->project,
                $entry->description
            );
            $te->setEntryDate(date('Y-m-d', strtotime($entry->start)));
            $te->setDurationTime($entry->dur);
            $te->setTask($entry->task);
            $te->setDescription($entry->description);
            $te->processTags($entry->tags);
            $te->setBillable($entry->is_billable);
            $timeEntries[] = $te;
        }
        return $timeEntries;
    }
1244310
public function getParticipationsByDayByRangeDate($startDate = '', $endDate = '')
    {
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
        $emConfig = $em->getConfiguration();
        $emConfig->addCustomDatetimeFunction('DATE', '\DoctrineExtensions\Query\Mysql\Date');

        $startDateTime = \DateTime::createFromFormat('d/m/Y', $startDate);
        $endDateTime = \DateTime::createFromFormat('d/m/Y', $endDate);

        if ($startDate != '' && $endDate != '') {
            $dateRange = "(e.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0' AND e.created_at <= '" . $endDateTime->format('Y-m-d') . " 23:59:59')";
        } elseif ($startDate == '' && $endDate != '') {
            $dateRange = "e.created_at <= '" . $endDateTime->format('Y-m-d') . " 23:59:59'";
        } elseif ($startDate != '' && $endDate == '') {
            $dateRange = "e.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0'";
        } else {
            $dateRange = "e.created_at IS NOT NULL";
        }

        $query = $em->createQuery('
            SELECT DATE(e.created_at) as date, COUNT(e.id) as qty FROM PlaygroundGame\Entity\Entry e
			WHERE ' . $dateRange . '
            AND e.active=0
            GROUP BY date
        ');
        $result = $query->getResult();
        return $result;
    }
1330306
public function findCalendarDatas(Blog $blog, $startDate, $endDate, $executeQuery = true)
    {
        $startDateTime = new \DateTime($startDate);
        $currentTimestamp = time();
        $endDateTime = new \DateTime($endDate);

        if ($currentTimestamp < $endDate) {
            $endDateTime->setTimestamp($currentTimestamp);
        }

        $query = $this->createQueryBuilder('post')
            ->select(['post'])
            ->andWhere('post.blog = :blogId')
            ->andWhere('post.status = :postStatus')
            ->andWhere('post.publicationDate IS NOT NULL')
            ->andWhere('post.publicationDate BETWEEN :startDate AND :endDate')
            ->setParameter('blogId', $blog->getId())
            ->setParameter('postStatus', Statusable::STATUS_PUBLISHED)
            ->setParameter('startDate', $startDateTime)
            ->setParameter('endDate', $endDateTime)
            ->getQuery()
        ;

        return $executeQuery ? $query->getResult() : $query;
    }
1313423
public static function initDatetimesInRange($start_datetime, $end_datetime, $hoursDifference = 1){
        $dates_in_range = [];
        $begin = new DateTime($start_datetime);
        $end = new DateTime($end_datetime);
        $endModify = $end->modify( '+'.$hoursDifference.' hour' ); 

        $interval = new DateInterval('PT'.$hoursDifference.'H');
        $daterange = new DatePeriod($begin, $interval ,$endModify);

        foreach($daterange as $date){
            $dates_in_range[$date->getTimestamp()] = $date->format("Y-m-d H:i:s");
        }
        return $dates_in_range;
    }
938986
public function getByRangeUserId( $startDate, $endDate, $userId ) {

		$modelClass	= static::$modelClass;
		$modelTable	= $this->getModelTable();

		$conditions = [ "$modelTable.scheduledAt BETWEEN '$startDate' AND '$endDate'", 'userId' => $userId ];

		$query = $modelClass::queryWithUser( [ 'conditions' => $conditions ] );

		return $query->all();
	}
1181475
public static function dateRange($field, $title, $startDate = '', $endDate = '')
    {
        return self::datePicker($field, $title, [(string)$startDate, (string)$endDate], DatePicker::TYPE_DATE_RANGE);
    }
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;
    }
815774
public function whereBetweenTime($field, $startTime, $endTime = null)
    {
        if (is_null($endTime)) {
            $time    = is_string($startTime) ? strtotime($startTime) : $startTime;
            $endTime = strtotime('+1 day', $time);
        }

        $this->where($field, 'between time', [$startTime, $endTime]);

        return $this;
    }
948734
public function getSellerWindowAtThisTime(\DateTime $startTime, $delivery_type)
    {
        $windows = $this->getSellerWindowsIndexedByStartTimeAndDeliveryType();

        if (!empty($windows[$startTime->format(\DateTime::ATOM)][$delivery_type]))
        {
            return $windows[$startTime->format(\DateTime::ATOM)][$delivery_type];
        }

        return false;
    }
120534
public static function getMonthsRange($startData, $endDate) {
        $time1 = strtotime($startData); //absolute date comparison needs to be done here, because PHP doesn't do date comparisons
        $time2 = strtotime($endDate);
        //$my1 = date('mY', $time1); //need these to compare dates at 'month' granularity
        //$my2 = date('mY', $time2);
        $year1 = date('Y', $time1);
        $year2 = date('Y', $time2);
        $years = range($year1, $year2);
        $months = Array();
        foreach ($years as $year) {
            $months[$year] = array();
            while ($time1 < $time2) {
                if (date('Y', $time1) == $year) {
                    $months[$year][] = date('m', $time1);
                    $time1 = strtotime(date('Y-m-d', $time1) . ' +1 month');
                } else {
                    break;
                }
            }
            continue;
        }

        return $months;
    }
113139
protected function get_time_range_weeks_number($starttime, $endtime) {
        if ($endtime <= $starttime) {
            throw new \coding_exception('End time timestamp should be greater than start time.');
        }

        $starttimedt = new \DateTime();
        $starttimedt->setTimestamp($starttime);
        $starttimedt->setTimezone(new \DateTimeZone('UTC'));
        $endtimedt = new \DateTime();
        $endtimedt->setTimestamp($endtime);
        $endtimedt->setTimezone(new \DateTimeZone('UTC'));

        $diff = $endtimedt->getTimestamp() - $starttimedt->getTimestamp();
        return $diff / WEEKSECS;
    }
1271928
public function getEndTimeFromStartTime(\DateTime $startTime)
    {
        $endTime  = clone $startTime;
        $endTime->add(\DateInterval::createFromDateString('+2 hour'));

        return $endTime;
    }