Example #1
0
 /**
  * Returns true or false depending on if the event falls in the specified
  * time-range. This is used for filtering purposes.
  *
  * The rules used to determine if an event falls within the specified
  * time-range is based on the CalDAV specification.
  *
  * @param DateTime $start
  * @param DateTime $end
  * @return bool
  */
 public function isInTimeRange(DateTime $start, DateTime $end)
 {
     if ($this->RRULE) {
         $it = new Sabre_VObject_RecurrenceIterator($this);
         $it->fastForward($start);
         // We fast-forwarded to a spot where the end-time of the
         // recurrence instance exceeded the start of the requested
         // time-range.
         //
         // If the starttime of the recurrence did not exceed the
         // end of the time range as well, we have a match.
         return $it->getDTStart() < $end && $it->getDTEnd() > $start;
     }
     $effectiveStart = $this->DTSTART->getDateTime();
     if (isset($this->DTEND)) {
         // The DTEND property is considered non inclusive. So for a 3 day
         // event in july, dtstart and dtend would have to be July 1st and
         // July 4th respectively.
         //
         // See:
         // http://tools.ietf.org/html/rfc5545#page-54
         $effectiveEnd = $this->DTEND->getDateTime();
     } elseif (isset($this->DURATION)) {
         $effectiveEnd = clone $effectiveStart;
         $effectiveEnd->add(Sabre_VObject_DateTimeParser::parseDuration($this->DURATION));
     } elseif ($this->DTSTART->getDateType() == Sabre_VObject_Element_DateTime::DATE) {
         $effectiveEnd = clone $effectiveStart;
         $effectiveEnd->modify('+1 day');
     } else {
         $effectiveEnd = clone $effectiveStart;
     }
     return $start <= $effectiveEnd && $end > $effectiveStart;
 }
    function testGetDTEnd()
    {
        $ics = <<<ICS
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//iCal 4.0.4//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
TRANSP:OPAQUE
DTEND;TZID=America/New_York:20070925T170000
UID:uuid
DTSTAMP:19700101T000000Z
LOCATION:
DESCRIPTION:
STATUS:CONFIRMED
SEQUENCE:18
SUMMARY:Stuff
DTSTART;TZID=America/New_York:20070925T160000
CREATED:20071004T144642Z
RRULE:FREQ=MONTHLY;INTERVAL=1;UNTIL=20071030T035959Z;BYDAY=5TU
END:VEVENT
END:VCALENDAR
ICS;
        $vObject = Sabre_VObject_Reader::read($ics);
        $it = new Sabre_VObject_RecurrenceIterator($vObject, (string) $vObject->VEVENT->UID);
        while ($it->valid()) {
            $it->next();
        }
        // If we got here, it means we were successful. The bug that was in teh
        // system before would fail on the 5th tuesday of the month, if the 5th
        // tuesday did not exist.
    }
Example #3
0
 /**
  * Returns true or false depending on if the event falls in the specified
  * time-range. This is used for filtering purposes.
  *
  * The rules used to determine if an event falls within the specified
  * time-range is based on the CalDAV specification.
  *
  * @param DateTime $start
  * @param DateTime $end
  * @return bool
  */
 public function isInTimeRange(DateTime $start, DateTime $end)
 {
     if ($this->RRULE) {
         $it = new Sabre_VObject_RecurrenceIterator($this);
         $it->fastForward($start);
         // We fast-forwarded to a spot where the end-time of the
         // recurrence instance exceeded the start of the requested
         // time-range.
         //
         // If the starttime of the recurrence did not exceed the
         // end of the time range as well, we have a match.
         return $it->getDTStart() < $end && $it->getDTEnd() > $start;
     }
     $effectiveStart = $this->DTSTART->getDateTime();
     if (isset($this->DTEND)) {
         $effectiveEnd = $this->DTEND->getDateTime();
         // If this was an all-day event, we should just increase the
         // end-date by 1. Otherwise the event will last until the second
         // the date changed, by increasing this by 1 day the event lasts
         // all of the last day as well.
         if ($this->DTSTART->getDateType() == Sabre_VObject_Element_DateTime::DATE) {
             $effectiveEnd->modify('+1 day');
         }
     } elseif (isset($this->DURATION)) {
         $effectiveEnd = clone $effectiveStart;
         $effectiveEnd->add(Sabre_VObject_DateTimeParser::parseDuration($this->DURATION));
     } elseif ($this->DTSTART->getDateType() == Sabre_VObject_Element_DateTime::DATE) {
         $effectiveEnd = clone $effectiveStart;
         $effectiveEnd->modify('+1 day');
     } else {
         $effectiveEnd = clone $effectiveStart;
     }
     return $start <= $effectiveEnd && $end > $effectiveStart;
 }
 /**
  * Different bug, also likely an infinite loop.
  */
 function testYearlyByMonthLoop()
 {
     $ev = Sabre_VObject_Component::create('VEVENT');
     $ev->UID = 'uuid';
     $ev->DTSTART = '20120101T154500';
     $ev->DTSTART['TZID'] = 'Europe/Berlin';
     $ev->RRULE = 'FREQ=YEARLY;INTERVAL=1;UNTIL=20120203T225959Z;BYMONTH=2;BYSETPOS=1;BYDAY=SU,MO,TU,WE,TH,FR,SA';
     $ev->DTEND = '20120101T164500';
     $ev->DTEND['TZID'] = 'Europe/Berlin';
     // This recurrence rule by itself is a yearly rule that should happen
     // every february.
     //
     // The BYDAY part expands this to every day of the month, but the
     // BYSETPOS limits this to only the 1st day of the month. Very crazy
     // way to specify this, and could have certainly been a lot easier.
     $cal = Sabre_VObject_Component::create('VCALENDAR');
     $cal->add($ev);
     $it = new Sabre_VObject_RecurrenceIterator($cal, 'uuid');
     $it->fastForward(new DateTime('2012-01-29 23:00:00', new DateTimeZone('UTC')));
     $collect = array();
     while ($it->valid()) {
         $collect[] = $it->getDTSTART();
         if ($it->getDTSTART() > new DateTime('2013-02-05 22:59:59', new DateTimeZone('UTC'))) {
             break;
         }
         $it->next();
     }
     $this->assertEquals(array(new DateTime('2012-02-01 15:45:00', new DateTimeZone('Europe/Berlin'))), $collect);
 }
Example #5
0
 /**
  * If this calendar object, has events with recurrence rules, this method 
  * can be used to expand the event into multiple sub-events.
  *
  * Each event will be stripped from it's recurrence information, and only 
  * the instances of the event in the specified timerange will be left 
  * alone.
  *
  * In addition, this method will cause timezone information to be stripped, 
  * and normalized to UTC.
  *
  * This method will alter the VCalendar. This cannot be reversed.
  *
  * This functionality is specifically used by the CalDAV standard. It is 
  * possible for clients to request expand events, if they are rather simple 
  * clients and do not have the possibility to calculate recurrences.
  *
  * @param DateTime $start
  * @param DateTime $end 
  * @return void
  */
 public function expand(DateTime $start, DateTime $end)
 {
     $newEvents = array();
     foreach ($this->select('VEVENT') as $key => $vevent) {
         if (isset($vevent->{'RECURRENCE-ID'})) {
             unset($this->children[$key]);
             continue;
         }
         if (!$vevent->rrule) {
             unset($this->children[$key]);
             if ($vevent->isInTimeRange($start, $end)) {
                 $newEvents[] = $vevent;
             }
             continue;
         }
         $uid = (string) $vevent->uid;
         if (!$uid) {
             throw new LogicException('Event did not have a UID!');
         }
         $it = new Sabre_VObject_RecurrenceIterator($this, $vevent->uid);
         $it->fastForward($start);
         while ($it->valid() && $it->getDTStart() < $end) {
             if ($it->getDTEnd() > $start) {
                 $newEvents[] = $it->getEventObject();
             }
             $it->next();
         }
         unset($this->children[$key]);
     }
     foreach ($newEvents as $newEvent) {
         foreach ($newEvent->children as $child) {
             if ($child instanceof Sabre_VObject_Property_DateTime && $child->getDateType() == Sabre_VObject_Property_DateTime::LOCALTZ) {
                 $child->setDateTime($child->getDateTime(), Sabre_VObject_Property_DateTime::UTC);
             }
         }
         $this->add($newEvent);
     }
     // Removing all VTIMEZONE components
     unset($this->VTIMEZONE);
 }
Example #6
0
/**
 * Parses some information from calendar objects, used for optimized
 * calendar-queries.
 *
 * Blantently copied from Sabre_CalDAV_Backend_PDO
 *
 * Returns an array with the following keys:
 *   * etag
 *   * size
 *   * componentType
 *   * firstOccurence
 *   * lastOccurence
 *
 * @param string $calendarData
 * @return array
 */
function getDenormalizedData($calendarData)
{
    $vObject = Sabre_VObject_Reader::read($calendarData);
    $componentType = null;
    $component = null;
    $firstOccurence = null;
    $lastOccurence = null;
    foreach ($vObject->getComponents() as $component) {
        if ($component->name !== 'VTIMEZONE') {
            $componentType = $component->name;
            break;
        }
    }
    if (!$componentType) {
        throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
    }
    if ($componentType === 'VEVENT') {
        $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp();
        // Finding the last occurence is a bit harder
        if (!isset($component->RRULE)) {
            if (isset($component->DTEND)) {
                $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
            } elseif (isset($component->DURATION)) {
                $endDate = clone $component->DTSTART->getDateTime();
                $endDate->add(Sabre_VObject_DateTimeParser::parse($component->DURATION->value));
                $lastOccurence = $endDate->getTimeStamp();
            } elseif ($component->DTSTART->getDateType() === Sabre_VObject_Property_DateTime::DATE) {
                $endDate = clone $component->DTSTART->getDateTime();
                $endDate->modify('+1 day');
                $lastOccurence = $endDate->getTimeStamp();
            } else {
                $lastOccurence = $firstOccurence;
            }
        } else {
            $it = new Sabre_VObject_RecurrenceIterator($vObject, (string) $component->UID);
            $maxDate = new DateTime(self::MAX_DATE);
            if ($it->isInfinite()) {
                $lastOccurence = $maxDate->getTimeStamp();
            } else {
                $end = $it->getDtEnd();
                while ($it->valid() && $end < $maxDate) {
                    $end = $it->getDtEnd();
                    $it->next();
                }
                $lastOccurence = $end->getTimeStamp();
            }
        }
    }
    return array('etag' => md5($calendarData), 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => $firstOccurence, 'lastOccurence' => $lastOccurence);
}
 /**
  * Parses the input data and returns a correct VFREEBUSY object, wrapped in
  * a VCALENDAR.
  *
  * @return Sabre_VObject_Component
  */
 public function getResult()
 {
     $busyTimes = array();
     foreach ($this->objects as $object) {
         foreach ($object->getBaseComponents() as $component) {
             switch ($component->name) {
                 case 'VEVENT':
                     $FBTYPE = 'BUSY';
                     if (isset($component->TRANSP) && strtoupper($component->TRANSP) === 'TRANSPARENT') {
                         break;
                     }
                     if (isset($component->STATUS)) {
                         $status = strtoupper($component->STATUS);
                         if ($status === 'CANCELLED') {
                             break;
                         }
                         if ($status === 'TENTATIVE') {
                             $FBTYPE = 'BUSY-TENTATIVE';
                         }
                     }
                     $times = array();
                     if ($component->RRULE) {
                         $iterator = new Sabre_VObject_RecurrenceIterator($object, (string) $component->uid);
                         if ($this->start) {
                             $iterator->fastForward($this->start);
                         }
                         $maxRecurrences = 200;
                         while ($iterator->valid() && --$maxRecurrences) {
                             $startTime = $iterator->getDTStart();
                             if ($this->end && $startTime > $this->end) {
                                 break;
                             }
                             $times[] = array($iterator->getDTStart(), $iterator->getDTEnd());
                             $iterator->next();
                         }
                     } else {
                         $startTime = $component->DTSTART->getDateTime();
                         if ($this->end && $startTime > $this->end) {
                             break;
                         }
                         $endTime = null;
                         if (isset($component->DTEND)) {
                             $endTime = $component->DTEND->getDateTime();
                         } elseif (isset($component->DURATION)) {
                             $duration = Sabre_VObject_DateTimeParser::parseDuration((string) $component->DURATION);
                             $endTime = clone $startTime;
                             $endTime->add($duration);
                         } elseif ($component->DTSTART->getDateType() === Sabre_VObject_Property_DateTime::DATE) {
                             $endTime = clone $startTime;
                             $endTime->modify('+1 day');
                         } else {
                             // The event had no duration (0 seconds)
                             break;
                         }
                         $times[] = array($startTime, $endTime);
                     }
                     foreach ($times as $time) {
                         if ($this->end && $time[0] > $this->end) {
                             break;
                         }
                         if ($this->start && $time[1] < $this->start) {
                             break;
                         }
                         $busyTimes[] = array($time[0], $time[1], $FBTYPE);
                     }
                     break;
                 case 'VFREEBUSY':
                     foreach ($component->FREEBUSY as $freebusy) {
                         $fbType = isset($freebusy['FBTYPE']) ? strtoupper($freebusy['FBTYPE']) : 'BUSY';
                         // Skipping intervals marked as 'free'
                         if ($fbType === 'FREE') {
                             continue;
                         }
                         $values = explode(',', $freebusy);
                         foreach ($values as $value) {
                             list($startTime, $endTime) = explode('/', $value);
                             $startTime = Sabre_VObject_DateTimeParser::parseDateTime($startTime);
                             if (substr($endTime, 0, 1) === 'P' || substr($endTime, 0, 2) === '-P') {
                                 $duration = Sabre_VObject_DateTimeParser::parseDuration($endTime);
                                 $endTime = clone $startTime;
                                 $endTime->add($duration);
                             } else {
                                 $endTime = Sabre_VObject_DateTimeParser::parseDateTime($endTime);
                             }
                             if ($this->start && $this->start > $endTime) {
                                 continue;
                             }
                             if ($this->end && $this->end < $startTime) {
                                 continue;
                             }
                             $busyTimes[] = array($startTime, $endTime, $fbType);
                         }
                     }
                     break;
             }
         }
     }
     if ($this->baseObject) {
         $calendar = $this->baseObject;
     } else {
         $calendar = new Sabre_VObject_Component('VCALENDAR');
         $calendar->version = '2.0';
         $calendar->prodid = '-//SabreDAV//Sabre VObject ' . Sabre_VObject_Version::VERSION . '//EN';
         $calendar->calscale = 'GREGORIAN';
     }
     $vfreebusy = new Sabre_VObject_Component('VFREEBUSY');
     $calendar->add($vfreebusy);
     if ($this->start) {
         $dtstart = new Sabre_VObject_Property_DateTime('DTSTART');
         $dtstart->setDateTime($this->start, Sabre_VObject_Property_DateTime::UTC);
         $vfreebusy->add($dtstart);
     }
     if ($this->end) {
         $dtend = new Sabre_VObject_Property_DateTime('DTEND');
         $dtend->setDateTime($this->start, Sabre_VObject_Property_DateTime::UTC);
         $vfreebusy->add($dtend);
     }
     $dtstamp = new Sabre_VObject_Property_DateTime('DTSTAMP');
     $dtstamp->setDateTime(new DateTime('now'), Sabre_VObject_Property_DateTime::UTC);
     $vfreebusy->add($dtstamp);
     foreach ($busyTimes as $busyTime) {
         $busyTime[0]->setTimeZone(new DateTimeZone('UTC'));
         $busyTime[1]->setTimeZone(new DateTimeZone('UTC'));
         $prop = new Sabre_VObject_Property('FREEBUSY', $busyTime[0]->format('Ymd\\THis\\Z') . '/' . $busyTime[1]->format('Ymd\\THis\\Z'));
         $prop['FBTYPE'] = $busyTime[2];
         $vfreebusy->add($prop);
     }
     return $calendar;
 }
 /**
  * Validates if a component matches the given time range.
  *
  * This is all based on the rules specified in rfc4791, which are quite
  * complex.
  *
  * @param Sabre_VObject_Node $component
  * @param DateTime $start
  * @param DateTime $end
  * @return bool
  */
 protected function validateTimeRange(Sabre_VObject_Node $component, $start, $end)
 {
     if (is_null($start)) {
         $start = new DateTime('1900-01-01');
     }
     if (is_null($end)) {
         $end = new DateTime('3000-01-01');
     }
     switch ($component->name) {
         case 'VEVENT':
         case 'VTODO':
         case 'VJOURNAL':
             return $component->isInTimeRange($start, $end);
         case 'VALARM':
             // If the valarm is wrapped in a recurring event, we need to
             // expand the recursions, and validate each.
             //
             // Our datamodel doesn't easily allow us to do this straight
             // in the VALARM component code, so this is a hack, and an
             // expensive one too.
             if ($component->parent->name === 'VEVENT' && $component->parent->RRULE) {
                 // Fire up the iterator!
                 $it = new Sabre_VObject_RecurrenceIterator($component->parent->parent, (string) $component->parent->UID);
                 while ($it->valid()) {
                     $expandedEvent = $it->getEventObject();
                     // We need to check from these expanded alarms, which
                     // one is the first to trigger. Based on this, we can
                     // determine if we can 'give up' expanding events.
                     $firstAlarm = null;
                     foreach ($expandedEvent->VALARM as $expandedAlarm) {
                         $effectiveTrigger = $expandedAlarm->getEffectiveTriggerTime();
                         if ($expandedAlarm->isInTimeRange($start, $end)) {
                             return true;
                         }
                         if ((string) $expandedAlarm->TRIGGER['VALUE'] === 'DATE-TIME') {
                             // This is an alarm with a non-relative trigger
                             // time, likely created by a buggy client. The
                             // implication is that every alarm in this
                             // recurring event trigger at the exact same
                             // time. It doesn't make sense to traverse
                             // further.
                         } else {
                             // We store the first alarm as a means to
                             // figure out when we can stop traversing.
                             if (!$firstAlarm || $effectiveTrigger < $firstAlarm) {
                                 $firstAlarm = $effectiveTrigger;
                             }
                         }
                     }
                     if (is_null($firstAlarm)) {
                         // No alarm was found.
                         //
                         // Or technically: No alarm that will change for
                         // every instance of the recurrence was found,
                         // which means we can assume there was no match.
                         return false;
                     }
                     if ($firstAlarm > $end) {
                         return false;
                     }
                     $it->next();
                 }
                 return false;
             } else {
                 return $component->isInTimeRange($start, $end);
             }
         case 'VFREEBUSY':
             throw new Sabre_DAV_Exception_NotImplemented('time-range filters are currently not supported on ' . $component->name . ' components');
         case 'COMPLETED':
         case 'CREATED':
         case 'DTEND':
         case 'DTSTAMP':
         case 'DTSTART':
         case 'DUE':
         case 'LAST-MODIFIED':
             return $start <= $component->getDateTime() && $end >= $component->getDateTime();
         default:
             throw new Sabre_DAV_Exception_BadRequest('You cannot create a time-range filter on a ' . $component->name . ' component');
     }
 }
 /**
  * Validates if a component matches the given time range.
  *
  * This is all based on the rules specified in rfc4791, which are quite
  * complex.
  *
  * @param Sabre_VObject_Node $component
  * @param DateTime $start
  * @param DateTime $end
  * @return bool
  */
 protected function validateTimeRange(Sabre_VObject_Node $component, $start, $end)
 {
     if (is_null($start)) {
         $start = new DateTime('1900-01-01');
     }
     if (is_null($end)) {
         $end = new DateTime('3000-01-01');
     }
     switch ($component->name) {
         case 'VEVENT':
         case 'VTODO':
         case 'VJOURNAL':
             return $component->isInTimeRange($start, $end);
         case 'VALARM':
             // If the valarm is wrapped in a recurring event, we need to
             // expand the recursions, and validate each.
             //
             // Our datamodel doesn't easily allow us to do this straight
             // in the VALARM component code, so this is a hack, and an
             // expensive one too.
             if ($component->parent->name === 'VEVENT' && $component->parent->RRULE) {
                 // Fire up the iterator!
                 $it = new Sabre_VObject_RecurrenceIterator($component->parent->parent, (string) $component->parent->UID);
                 while ($it->valid()) {
                     $expandedEvent = $it->getEventObject();
                     // We need to check from these expanded alarms, which
                     // one is the first to trigger. Based on this, we can
                     // determine if we can 'give up' expanding events.
                     $firstAlarm = null;
                     foreach ($expandedEvent->VALARM as $expandedAlarm) {
                         $effectiveTrigger = $expandedAlarm->getEffectiveTriggerTime();
                         if (!$firstAlarm || $effectiveTrigger < $firstAlarm) {
                             $firstAlarm = $effectiveTrigger;
                         }
                         if ($expandedAlarm->isInTimeRange($start, $end)) {
                             return true;
                         }
                     }
                     if ($firstAlarm > $end) {
                         return false;
                     }
                     $it->next();
                 }
                 return false;
             } else {
                 return $component->isInTimeRange($start, $end);
             }
         case 'VFREEBUSY':
             throw new Sabre_DAV_Exception_NotImplemented('time-range filters are currently not supported on ' . $component->name . ' components');
         case 'COMPLETED':
         case 'CREATED':
         case 'DTEND':
         case 'DTSTAMP':
         case 'DTSTART':
         case 'DUE':
         case 'LAST-MODIFIED':
             return $start <= $component->getDateTime() && $end >= $component->getDateTime();
         default:
             throw new Sabre_DAV_Exception_BadRequest('You cannot create a time-range filter on a ' . $component->name . ' component');
     }
 }
 /**
  * @depends testValues
  */
 function testOverridenEventNoValuesExpected()
 {
     $vcal = Sabre_VObject_Component::create('VCALENDAR');
     $ev1 = Sabre_VObject_Component::create('VEVENT');
     $ev1->UID = 'overridden';
     $ev1->RRULE = 'FREQ=WEEKLY;COUNT=3';
     $ev1->DTSTART = '20120124T120000Z';
     $ev1->SUMMARY = 'baseEvent';
     $vcal->add($ev1);
     // ev2 overrides an event, and puts it 6 days earlier instead.
     $ev2 = Sabre_VObject_Component::create('VEVENT');
     $ev2->UID = 'overridden';
     $ev2->{'RECURRENCE-ID'} = '20120131T120000Z';
     $ev2->DTSTART = '20120125T120000Z';
     $ev2->SUMMARY = 'Override!';
     $vcal->add($ev2);
     $it = new Sabre_VObject_RecurrenceIterator($vcal, 'overridden');
     $dates = array();
     $summaries = array();
     // The reported problem was specifically related to the VCALENDAR
     // expansion. In this parcitular case, we had to forward to the 28th of
     // january.
     $it->fastForward(new DateTime('2012-01-28 23:00:00'));
     // We stop the loop when it hits the 6th of februari. Normally this
     // iterator would hit 24, 25 (overriden from 31) and 7 feb but because
     // we 'filter' from the 28th till the 6th, we should get 0 results.
     while ($it->valid() && $it->getDTSTart() < new DateTime('2012-02-06 23:00:00')) {
         $dates[] = $it->getDTStart();
         $summaries[] = (string) $it->getEventObject()->SUMMARY;
         $it->next();
     }
     $this->assertEquals(array(), $dates);
     $this->assertEquals(array(), $summaries);
 }