diff --git a/lib/Horde/ActiveSync/Imap/EasMessageBuilder.php b/lib/Horde/ActiveSync/Imap/EasMessageBuilder.php index fd9b1e39..8c01b3af 100644 --- a/lib/Horde/ActiveSync/Imap/EasMessageBuilder.php +++ b/lib/Horde/ActiveSync/Imap/EasMessageBuilder.php @@ -1,5 +1,9 @@ parsevCalendar($data, 'VCALENDAR', $mime_part->getCharset())) { - $classes = $vCal->getComponentClasses(); - } else { - $classes = []; - } - } catch (Horde_Icalendar_Exception $e) { + $calendar = AbstractComponent::fromString($data); + } catch (IcalendarException $e) { $this->_logger->err($e->getMessage()); return; } // Exit if we can't parse/find any data. - if (empty($classes['horde_icalendar_vevent'])) { + if (!($calendar instanceof VCalendar) || $calendar->getEvents() === []) { return; } - // Many senders omit METHOD on text/calendar parts; treat as REQUEST (Bug #12083). - $method = HordeString::upper($vCal->getAttributeDefault('METHOD', 'REQUEST')); - $this->_easMessage->contentclass = 'urn:content-classes:calendarmessage'; + // A sender that repeats METHOD must not break the sync; the first + // value counts. Many senders omit METHOD on text/calendar parts; + // treat as REQUEST (Bug #12083). + if ($calendar->getProperties()->count('METHOD') > 1) { + $this->_logger->debug('The iTip has more than one METHOD property, using the first.'); + } + $method = $calendar->getMethod() ?? CalendarMethod::from('REQUEST'); - switch ($method) { - case 'REQUEST': - case 'PUBLISH': - $this->_easMessage->messageclass = 'IPM.Schedule.Meeting.Request'; - $mtg = Horde_ActiveSync::messageFactory('MeetingRequest'); - $mtg->fromvEvent($vCal); - $this->_easMessage->meetingrequest = $mtg; - break; - case 'REPLY': - try { - $reply_status = $this->_getiTipStatus($vCal); - switch ($reply_status) { + $messageClass = null; + $hasMeetingData = true; + try { + switch ($method->value) { + case 'REQUEST': + case 'PUBLISH': + $messageClass = 'IPM.Schedule.Meeting.Request'; + break; + case 'REPLY': + switch ($this->_getiTipStatus($calendar)) { case 'ACCEPTED': - $this->_easMessage->messageclass = 'IPM.Schedule.Meeting.Resp.Pos'; + $messageClass = 'IPM.Schedule.Meeting.Resp.Pos'; break; case 'DECLINED': - $this->_easMessage->messageclass = 'IPM.Schedule.Meeting.Resp.Neg'; + $messageClass = 'IPM.Schedule.Meeting.Resp.Neg'; break; case 'TENTATIVE': - $this->_easMessage->messageclass = 'IPM.Schedule.Meeting.Resp.Tent'; + $messageClass = 'IPM.Schedule.Meeting.Resp.Tent'; } - $mtg = Horde_ActiveSync::messageFactory('MeetingRequest'); - $mtg->fromvEvent($vCal); - $this->_easMessage->meetingrequest = $mtg; - } catch (Horde_ActiveSync_Exception $e) { - $this->_logger->err($e->getMessage()); - } - break; - case 'CANCEL': - try { - $mtg = Horde_ActiveSync::messageFactory('MeetingRequest'); - $mtg->fromvEvent($vCal); - $this->_easMessage->meetingrequest = $mtg; - $this->_easMessage->messageclass = Horde_ActiveSync_Message_Mail::CLASS_MEETING_CANCELED; - } catch (Horde_ActiveSync_Exception $e) { - $this->_logger->err($e->getMessage()); - } - break; + break; + case 'CANCEL': + $messageClass = Horde_ActiveSync_Message_Mail::CLASS_MEETING_CANCELED; + break; + default: + $hasMeetingData = false; + } + + if ($hasMeetingData) { + $mtg = Horde_ActiveSync::messageFactory('MeetingRequest'); + $mtg->fromCalendar($calendar, $method); + $this->_easMessage->meetingrequest = $mtg; + } + } catch (Horde_ActiveSync_Exception $e) { + // The mail is still delivered, just without the meeting data. + $this->_logger->err($e->getMessage()); + return; + } + + $this->_easMessage->contentclass = 'urn:content-classes:calendarmessage'; + if ($messageClass !== null) { + $this->_easMessage->messageclass = $messageClass; } } @@ -466,30 +472,25 @@ protected function _getEASImportance($importance) /** * Return the attendee participation status. * - * @param Horde_Icalendar $vCal The vCalendar component. + * @param VCalendar $calendar The iTip. + * + * @return string The upper-cased PARTSTAT of the first attendee, or + * NEEDS-ACTION if it has none (RFC 5545 default). * - * @param Horde_Icalendar * @throws Horde_ActiveSync_Exception */ - protected function _getiTipStatus($vCal) + protected function _getiTipStatus(VCalendar $calendar) { - foreach ($vCal->getComponents() as $component) { - switch ($component->getType()) { - case 'vEvent': - try { - $atparams = $component->getAttribute('ATTENDEE', true); - } catch (Horde_Icalendar_Exception $e) { - throw new Horde_ActiveSync_Exception($e); - } - - if (!is_array($atparams) || !isset($atparams[0])) { - throw new Horde_Icalendar_Exception('Unexpected value'); - } - - // PARTSTAT is optional on ATTENDEE (RFC 5545 default: NEEDS-ACTION). - return $atparams[0]['PARTSTAT'] ?? 'NEEDS-ACTION'; + foreach ($calendar->getEvents() as $event) { + $attendees = $event->getAttendees(); + if ($attendees === []) { + throw new Horde_ActiveSync_Exception('The iTip reply has no ATTENDEE.'); } + + return $attendees[0]->getParticipationStatus()->value; } + + throw new Horde_ActiveSync_Exception('The iTip reply has no event.'); } /** diff --git a/lib/Horde/ActiveSync/Message/MeetingRequest.php b/lib/Horde/ActiveSync/Message/MeetingRequest.php index b462673e..cb710a2f 100755 --- a/lib/Horde/ActiveSync/Message/MeetingRequest.php +++ b/lib/Horde/ActiveSync/Message/MeetingRequest.php @@ -1,5 +1,14 @@ getAttributeDefault('METHOD', 'REQUEST')); - foreach ($vCal->getComponents() as $component) { - switch ($component->getType()) { - case 'vEvent': - $this->_vEvent = $component; - $this->_parsevEvent($component, $method); - break; - - case 'vTimeZone': - // Not sure what to do with Timezone yet/how to get it into - // a TZ structure etc... For now, defaults to default timezone (as the - // specs say it should for iCal without tz specified). - default: - break; - } + $method ??= $calendar->getMethod() ?? CalendarMethod::from('REQUEST'); + $this->_calendar = $calendar; + $this->_resolver = new CalendarTimeResolver($calendar); + + $parsed = false; + foreach ($calendar->getEvents() as $vevent) { + $this->_parsevEvent($vevent, $method); + $parsed = true; } // Ensure we actually have a vEvent to parse. - if (empty($this->_vEvent)) { + if (!$parsed) { return; } - $tz = new Horde_Mapi_Timezone(); - try { + if ($this->starttime instanceof Horde_Date) { + $tz = new Horde_Mapi_Timezone(); $this->timezone = $tz->getSyncTZFromOffsets( - $tz->getOffsetsFromDate(new Horde_Date($this->_vEvent->getAttribute('DTSTART'))) + $tz->getOffsetsFromDate($this->starttime) ); - } catch (Horde_Icalendar_Exception $e) { } $this->alldayevent = (int) $this->_isAllDay(); } /** - * Return the vEvent object the request/response is based on. + * Create a meeting request from a legacy iCalendar object. + * + * @param Horde_Icalendar $vCal The vCalendar. + * + * @deprecated Use fromCalendar(). + * + * @throws Horde_ActiveSync_Exception + */ + public function fromvEvent($vCal) + { + try { + $calendar = AbstractComponent::fromString($vCal->exportvCalendar()); + } catch (IcalendarException $e) { + throw new Horde_ActiveSync_Exception($e->getMessage()); + } + if (!$calendar instanceof VCalendar) { + throw new Horde_ActiveSync_Exception('The iCalendar data is not a VCALENDAR.'); + } + + $this->fromCalendar($calendar); + } + + /** + * Return the vEvent the request/response is based on, as a legacy + * iCalendar component. + * + * Needed by consumers that still take the legacy object, such as the + * calendar/updateAttendee registry API. + * + * @deprecated Consumers should move to the typed calendar model. * - * @return Horde_Icalendar_vEvent + * @return Horde_Icalendar_Vevent|null Null when no event was parsed. */ public function getvEvent() { - return $this->_vEvent; + if ($this->_calendar === null) { + return null; + } + + $legacy = new Horde_Icalendar(); + try { + if (!$legacy->parsevCalendar($this->_calendar->toString())) { + return null; + } + } catch (Horde_Icalendar_Exception $e) { + return null; + } + + $vevent = null; + foreach ($legacy->getComponents() as $component) { + if ($component instanceof Horde_Icalendar_Vevent) { + $vevent = $component; + } + } + + return $vevent; } /** * Parses a vEvent into the message properties. * - * @param Horde_Icalendar_Vevent $vevent The vEvent to parse. - * @param string $method The method (e.g., 'REQUEST'). + * @param Vevent $vevent The vEvent to parse. + * @param CalendarMethod $method The iTip method. * * @throws Horde_ActiveSync_Exception */ - protected function _parsevEvent($vevent, $method = 'REQUEST') + protected function _parsevEvent(Vevent $vevent, CalendarMethod $method) { - if ($method == 'REQUEST') { - $this->responserequested = '1'; - } else { - $this->responserequested = '0'; - } + $method = $method->value; + $this->responserequested = $method === 'REQUEST' ? '1' : '0'; // EAS 14.1+: iOS only offers RSVP when MeetingMessageType is 1 or 2. if ($this->_version > Horde_ActiveSync::VERSION_FOURTEEN) { if ($method === 'REQUEST') { - try { - $sequence = (int) $vevent->getAttributeDefault('SEQUENCE', 0); - } catch (Horde_Icalendar_Exception $e) { - $sequence = 0; - } - $this->meetingmessagetype = $sequence > 0 + $this->meetingmessagetype = $vevent->getSequence() > 0 ? self::MEETING_MESSAGE_UPDATE : self::MEETING_MESSAGE_INITIAL; } elseif ($method === 'PUBLISH') { @@ -228,103 +280,106 @@ protected function _parsevEvent($vevent, $method = 'REQUEST') } } - try { - $organizer = parse_url($vevent->getAttribute('ORGANIZER')); - $this->organizer = $organizer['path']; - } catch (Horde_Icalendar_Exception $e) { + $organizer = $vevent->getOrganizer()?->getEmail(); + if ($organizer !== null && $organizer !== '') { + $this->organizer = $organizer; } - try { - $this->globalobjid = Horde_Mapi::createGoid($vevent->getAttributeDefault('UID', 'nouid')); - $this->starttime = new Horde_Date($vevent->getAttribute('DTSTART')); - } catch (Horde_Exception $e) { - throw new Horde_ActiveSync_Exception($e); + $start = $this->_resolveTime($vevent->getProperties()->get('DTSTART')); + if ($start === null) { + throw new Horde_ActiveSync_Exception('The calendar event has no usable DTSTART.'); } + $this->starttime = $start; + $this->globalobjid = Horde_Mapi::createGoid($vevent->getUid() ?? 'nouid'); - try { - $this->dtstamp = new Horde_Date($vevent->getAttribute('DTSTAMP')); - } catch (Horde_Exception $e) { + $dtstamp = $this->_resolveTime($vevent->getProperties()->get('DTSTAMP')); + if ($dtstamp !== null) { + $this->dtstamp = $dtstamp; } - try { - $this->endtime = new Horde_Date($vevent->getAttribute('DTEND')); - $this->location = HordeString::truncate($vevent->getAttribute('LOCATION'), 255); - } catch (Horde_Icalendar_Exception $e) { + $end = $this->_resolveTime($vevent->getProperties()->get('DTEND')); + if ($end === null && $vevent->getDuration() !== null) { + try { + $end = new Horde_Date( + $start->timestamp() + Duration::fromIcalendar($vevent->getDuration())->toSeconds() + ); + } catch (DateException $e) { + $this->_logger->notice('Ignoring unparseable DURATION: ' . $e->getMessage()); + } + } + if ($end !== null) { + $this->endtime = $end; } - try { - $class = $vevent->getAttribute('CLASS'); - if (!is_array($class)) { - $this->sensitivity = $class == 'PRIVATE' - ? Horde_ActiveSync_Message_Appointment::SENSITIVITY_PRIVATE - : ($class == 'CONFIDENTIAL' ? Horde_ActiveSync_Message_Appointment::SENSITIVITY_CONFIDENTIAL - : ($class == 'PERSONAL' ? Horde_ActiveSync_Message_Appointment::SENSITIVITY_PERSONAL - : Horde_ActiveSync_Message_Appointment::SENSITIVITY_NORMAL)); - } - } catch (Horde_Icalendar_Exception $e) { + $location = $vevent->getProperties()->get('LOCATION'); + if ($location !== null) { + $this->location = HordeString::truncate($this->_textValue($location), 255); } - try { - $status = $vevent->getAttribute('STATUS'); - if (!is_array($status)) { - $status = HordeString::upper($status); - $this->busystatus = $status == 'TENTATIVE' ? Horde_ActiveSync_Message_Appointment::BUSYSTATUS_TENTATIVE - : ($status == 'CONFIRMED' ? Horde_ActiveSync_Message_Appointment::BUSYSTATUS_BUSY - : Horde_ActiveSync_Message_Appointment::BUSYSTATUS_FREE); - } - } catch (Horde_Icalendar_Exception $e) { + if ($vevent->getProperties()->has('CLASS')) { + $class = $vevent->getClassification()->value; + $this->sensitivity = $class === 'PRIVATE' + ? Horde_ActiveSync_Message_Appointment::SENSITIVITY_PRIVATE + : ($class === 'CONFIDENTIAL' ? Horde_ActiveSync_Message_Appointment::SENSITIVITY_CONFIDENTIAL + : ($class === 'PERSONAL' ? Horde_ActiveSync_Message_Appointment::SENSITIVITY_PERSONAL + : Horde_ActiveSync_Message_Appointment::SENSITIVITY_NORMAL)); } - // vCalendar 1.0 alarms - try { - $alarm = $vevent->getAttribute('AALARM'); - if (!is_array($alarm) && intval($alarm)) { - $this->reminder = intval($this->starttime->timestamp() - $alarm); - } - } catch (Horde_Icalendar_Exception $e) { + $status = $vevent->getStatus()?->value; + if ($status !== null) { + $this->busystatus = $status === 'TENTATIVE' ? Horde_ActiveSync_Message_Appointment::BUSYSTATUS_TENTATIVE + : ($status === 'CONFIRMED' ? Horde_ActiveSync_Message_Appointment::BUSYSTATUS_BUSY + : Horde_ActiveSync_Message_Appointment::BUSYSTATUS_FREE); + } + + // vCalendar 1.0 alarms: the first field is the alarm's date-time. + $alarmTime = $this->_resolveTime($vevent->getProperties()->get('AALARM')); + if ($alarmTime !== null && $alarmTime->timestamp() < $start->timestamp()) { + $this->reminder = $start->timestamp() - $alarmTime->timestamp(); } // vCalendar 2.0 alarms - foreach ($vevent->getComponents() as $alarm) { - if (!($alarm instanceof Horde_Icalendar_Valarm)) { + foreach ($vevent->getAlarms() as $alarm) { + $trigger = $alarm->getProperties()->get('TRIGGER'); + if ($trigger === null) { continue; } - try { - $trigger = $alarm->getAttribute('TRIGGER'); - $triggerParams = $alarm->getAttribute('TRIGGER', true); - } catch (Horde_Icalendar_Exception $e) { + + if (strtoupper($trigger->getParameter('VALUE')?->getValue() ?? '') === 'DATE-TIME') { + $triggerTime = $this->_resolveTime($trigger); + if ($triggerTime !== null) { + $this->reminder = $start->timestamp() - $triggerTime->timestamp(); + } continue; } - if (isset($triggerParams['VALUE']) - && $triggerParams['VALUE'] == 'DATE-TIME') { - if (isset($triggerParams['RELATED']) - && $triggerParams['RELATED'] == 'END') { - $this->reminder = intval($this->endtime->timestamp() - $trigger); - } else { - $this->reminder = intval($this->starttime->timestamp() - $trigger); - } - } else { - $this->reminder = -intval($trigger); + + try { + $this->reminder = -Duration::fromIcalendar($trigger->getValue())->toSeconds(); + } catch (DateException $e) { + $this->_logger->notice('Ignoring unparseable alarm TRIGGER: ' . $e->getMessage()); } } $this->_parseDisallowNewTimeProposal($vevent); - $this->_parseInstanceTypeAndRecurrence($vevent); + $this->_parseInstanceTypeAndRecurrence($vevent, $start); } /** * Populate instancetype, recurrenceid, and recurrences from VEVENT data. * + * @param Vevent $vevent The event. + * @param Horde_Date $start The resolved start of the event. + * * @author Torben Dannhauer */ - protected function _parseInstanceTypeAndRecurrence(Horde_Icalendar_Vevent $vevent): void + protected function _parseInstanceTypeAndRecurrence(Vevent $vevent, Horde_Date $start): void { $this->instancetype = Horde_ActiveSync_Utils_Recurrence::detectInstanceType($vevent); if (in_array($this->instancetype, ['2', '3'], true)) { - try { - $this->recurrenceid = new Horde_Date($vevent->getAttribute('RECURRENCE-ID')); - } catch (Horde_Exception $e) { + $recurrenceId = $this->_resolveTime($vevent->getProperties()->get('RECURRENCE-ID')); + if ($recurrenceId !== null) { + $this->recurrenceid = $recurrenceId; } } @@ -332,7 +387,7 @@ protected function _parseInstanceTypeAndRecurrence(Horde_Icalendar_Vevent $veven return; } - $recurrence = Horde_ActiveSync_Utils_Recurrence::recurrenceFromVevent($vevent); + $recurrence = Horde_ActiveSync_Utils_Recurrence::recurrenceFromVevent($vevent, $start); if ($recurrence === null) { return; } @@ -352,22 +407,15 @@ protected function _parseInstanceTypeAndRecurrence(Horde_Icalendar_Vevent $veven /** * Import iCal disallow-counter state for EAS 14+ meeting requests. */ - protected function _parseDisallowNewTimeProposal(Horde_Icalendar_Vevent $vevent): void + protected function _parseDisallowNewTimeProposal(Vevent $vevent): void { if ($this->_version < Horde_ActiveSync::VERSION_FOURTEEN) { return; } foreach (self::DISALLOW_COUNTER_ATTRIBUTES as $name) { - try { - $value = $vevent->getAttribute($name); - } catch (Horde_Icalendar_Exception $e) { - continue; - } - if (is_array($value)) { - $value = reset($value); - } - if (is_string($value) + $value = $vevent->getPropertyValue($name); + if ($value !== null && in_array(strtoupper(trim($value)), ['1', 'TRUE', 'YES'], true)) { $this->disallownewtimeproposal = true; return; @@ -375,6 +423,63 @@ protected function _parseDisallowNewTimeProposal(Horde_Icalendar_Vevent $vevent) } } + /** + * Resolve a date or date-time property to a Horde_Date. + * + * @param Property|null $property The property. + * + * @return Horde_Date|null Null if the property is missing or is not a + * date or date-time. + */ + protected function _resolveTime(?Property $property): ?Horde_Date + { + if ($property === null || $this->_resolver === null) { + return null; + } + + $resolved = $this->_resolver->resolve($property); + if ($resolved === null) { + return null; + } + if ($resolved->unresolvedTzid !== null) { + $this->_logger->notice(sprintf( + 'Unknown time zone "%s" in %s, using the server time zone.', + $resolved->unresolvedTzid, + $property->getName() + )); + } + + return new Horde_Date($resolved->timestamp); + } + + /** + * Return the text of a property: transfer encoding and charset undone, + * iCalendar escapes resolved. + * + * @param Property $property The text property. + * + * @return string The UTF-8 text. + */ + protected function _textValue(Property $property): string + { + $value = $property->getValue(); + + if (strtoupper($property->getParameter('ENCODING')?->getValue() ?? '') === 'QUOTED-PRINTABLE') { + $value = quoted_printable_decode($value); + } + + $charset = $property->getParameter('CHARSET')?->getValue(); + if ($charset !== null && strcasecmp($charset, 'UTF-8') !== 0) { + $value = HordeString::convertCharset($value, $charset, 'UTF-8'); + } + + return preg_replace_callback( + '/\\\\([nN,;\\\\])/', + static fn(array $m): string => strtolower($m[1]) === 'n' ? "\n" : $m[1], + $value + ); + } + /** * Return if this is a request for an all day meeting. * @@ -382,6 +487,10 @@ protected function _parseDisallowNewTimeProposal(Horde_Icalendar_Vevent $vevent) */ protected function _isAllDay() { + if (!($this->starttime instanceof Horde_Date) || !($this->endtime instanceof Horde_Date)) { + return false; + } + return ($this->starttime->hour == 0 && $this->starttime->min == 0 && $this->starttime->sec == 0 && (($this->endtime->hour == 23 && $this->endtime->min == 59) || ($this->endtime->hour == 0 && $this->endtime->min == 0 && $this->endtime->sec == 0 diff --git a/lib/Horde/ActiveSync/Utils/Recurrence.php b/lib/Horde/ActiveSync/Utils/Recurrence.php index 954ad289..9485beec 100755 --- a/lib/Horde/ActiveSync/Utils/Recurrence.php +++ b/lib/Horde/ActiveSync/Utils/Recurrence.php @@ -1,5 +1,7 @@ getAttribute('RECURRENCE-ID'); - $hasRecurrenceId = !is_array($recurrenceId) && strlen((string) $recurrenceId); - } catch (Horde_Icalendar_Exception $e) { - } - - $hasRrule = false; - try { - $rrule = $vevent->getAttribute('RRULE'); - $hasRrule = !is_array($rrule) && strlen((string) $rrule); - } catch (Horde_Icalendar_Exception $e) { - } + $hasRecurrenceId = (string) $vevent->getPropertyValue('RECURRENCE-ID') !== ''; + $hasRrule = (string) $vevent->getRrule() !== ''; if ($hasRecurrenceId) { return $hasRrule ? '2' : '3'; @@ -55,23 +46,18 @@ public static function detectInstanceType(Horde_Icalendar_Vevent $vevent): strin /** * Parse RRULE from a VEVENT into Horde_Date_Recurrence. + * + * @param Vevent $vevent The event carrying the RRULE. + * @param Horde_Date $start The start of the first occurrence, resolved + * by the caller (DTSTART may use a time zone + * only the surrounding calendar can resolve). */ public static function recurrenceFromVevent( - Horde_Icalendar_Vevent $vevent + Vevent $vevent, + Horde_Date $start ): ?Horde_Date_Recurrence { - try { - $rrule = $vevent->getAttribute('RRULE'); - } catch (Horde_Icalendar_Exception $e) { - return null; - } - - if (is_array($rrule) || !strlen((string) $rrule)) { - return null; - } - - try { - $start = new Horde_Date($vevent->getAttribute('DTSTART')); - } catch (Horde_Exception $e) { + $rrule = (string) $vevent->getRrule(); + if ($rrule === '') { return null; } diff --git a/src/Calendar/CalendarTimeResolver.php b/src/Calendar/CalendarTimeResolver.php new file mode 100644 index 00000000..3c1ecd52 --- /dev/null +++ b/src/Calendar/CalendarTimeResolver.php @@ -0,0 +1,152 @@ + + * @category Horde + * @copyright 2026 The Horde Project + * @license http://www.horde.org/licenses/gpl GPLv2 + * @package ActiveSync + */ + +namespace Horde\ActiveSync\Calendar; + +use DateTimeImmutable; +use DateTimeZone; +use Horde\Date\TimezoneMapper; +use Horde\Icalendar\Calendar\VCalendar; +use Horde\Icalendar\Calendar\Vtimezone; +use Horde\Icalendar\Property\Property; + +/** + * Resolves DATE and DATE-TIME properties of a calendar to unix timestamps. + * + * The typed Vevent accessors read a TZID only as an IANA zone name and throw + * on anything else. Mail clients routinely send Windows names or custom + * names whose rules live in the calendar's own VTIMEZONE, so a meeting from + * such a sender could not be read through them. This resolver reads the + * property directly and resolves the zone in this order: + * + * 1. A UTC value ("...Z"). + * 2. The VTIMEZONE in the same calendar that carries the TZID. + * 3. The TZID as an IANA name, or as a Windows name mapped to one. + * 4. Otherwise the wall-clock time is read in the server time zone and the + * unresolved TZID is reported on the result. + * + * Values without a TZID (floating times and DATE values) are read in the + * server time zone. + */ +final class CalendarTimeResolver +{ + /** @var array */ + private array $vtimezones = []; + + /** @var array|null */ + private static ?array $zoneNames = null; + + public function __construct( + VCalendar $calendar, + private readonly VtimezoneOffsets $offsets = new VtimezoneOffsets() + ) { + foreach ($calendar->getTimezones() as $vtimezone) { + $tzid = $vtimezone->getPropertyValue('TZID'); + if ($tzid !== null && $tzid !== '') { + $this->vtimezones[$tzid] ??= $vtimezone; + } + } + } + + /** + * Resolve a DATE or DATE-TIME property. + * + * @return ResolvedTime|null Null when the value is not a date or + * date-time. + */ + public function resolve(Property $property): ?ResolvedTime + { + // vCalendar 1.0 properties such as AALARM append extra fields after + // a semicolon. + $value = trim(explode(';', $property->getValue())[0]); + + if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/i', $value, $m) + || !checkdate((int) $m[2], (int) $m[3], (int) $m[1])) { + return null; + } + + [$year, $month, $day] = [(int) $m[1], (int) $m[2], (int) $m[3]]; + [$hour, $minute, $second] = [(int) ($m[4] ?? 0), (int) ($m[5] ?? 0), (int) ($m[6] ?? 0)]; + + if (!empty($m[7])) { + return new ResolvedTime(gmmktime($hour, $minute, $second, $month, $day, $year)); + } + + $tzid = trim($property->getParameter('TZID')?->getValue() ?? ''); + if ($tzid === '') { + return new ResolvedTime($this->inZone( + date_default_timezone_get(), + $year, + $month, + $day, + $hour, + $minute, + $second + )); + } + + $wallTime = gmmktime($hour, $minute, $second, $month, $day, $year); + + if (isset($this->vtimezones[$tzid])) { + $offset = $this->offsets->offsetAt($this->vtimezones[$tzid], $wallTime); + if ($offset !== null) { + return new ResolvedTime($wallTime - $offset); + } + } + + $zone = TimezoneMapper::toIana($tzid); + if ($this->isKnownZone($zone)) { + return new ResolvedTime($this->inZone($zone, $year, $month, $day, $hour, $minute, $second)); + } + + return new ResolvedTime( + $this->inZone(date_default_timezone_get(), $year, $month, $day, $hour, $minute, $second), + $tzid + ); + } + + /** + * Timestamp of a wall-clock reading in a known time zone. + */ + private function inZone( + string $zone, + int $year, + int $month, + int $day, + int $hour, + int $minute, + int $second + ): int { + return (new DateTimeImmutable('now', new DateTimeZone($zone))) + ->setDate($year, $month, $day) + ->setTime($hour, $minute, $second) + ->getTimestamp(); + } + + /** + * Whether PHP knows the time zone name, so constructing it cannot fail. + */ + private function isKnownZone(string $zone): bool + { + self::$zoneNames ??= array_fill_keys( + DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC), + true + ); + + return isset(self::$zoneNames[$zone]); + } +} diff --git a/src/Calendar/ResolvedTime.php b/src/Calendar/ResolvedTime.php new file mode 100644 index 00000000..e0221789 --- /dev/null +++ b/src/Calendar/ResolvedTime.php @@ -0,0 +1,38 @@ + + * @category Horde + * @copyright 2026 The Horde Project + * @license http://www.horde.org/licenses/gpl GPLv2 + * @package ActiveSync + */ + +namespace Horde\ActiveSync\Calendar; + +/** + * A calendar date or date-time resolved to a point in time. + */ +final class ResolvedTime +{ + /** + * @param int $timestamp Unix timestamp. + * @param string|null $unresolvedTzid Set when the value named a TZID that + * could not be resolved. The timestamp + * then reads the wall-clock time in the + * server time zone, so the caller can + * report it. + */ + public function __construct( + public readonly int $timestamp, + public readonly ?string $unresolvedTzid = null + ) { + } +} diff --git a/src/Calendar/VtimezoneOffsets.php b/src/Calendar/VtimezoneOffsets.php new file mode 100644 index 00000000..fd0cdb07 --- /dev/null +++ b/src/Calendar/VtimezoneOffsets.php @@ -0,0 +1,380 @@ + + * @category Horde + * @copyright 2026 The Horde Project + * @license http://www.horde.org/licenses/gpl GPLv2 + * @package ActiveSync + */ + +namespace Horde\ActiveSync\Calendar; + +use Horde\Icalendar\Calendar\Vtimezone; +use Horde\Icalendar\Component; + +/** + * Evaluates the UTC offset a VTIMEZONE defines for a local wall-clock time. + * + * Mail clients such as Outlook describe a zone with a vendor TZID (for + * example "W. Europe Standard Time") and embed the rules in a VTIMEZONE. + * The TZID alone cannot be resolved, so the embedded STANDARD and DAYLIGHT + * observances are the authority. + * + * Only the rule forms real VTIMEZONE data uses are evaluated: + * + * - an observance without RRULE (a single transition at its DTSTART), + * - RDATE transitions, + * - FREQ=YEARLY with BYMONTH and either BYDAY=nXX (the n-th or last + * weekday of the month) or BYDAY=XX with a BYMONTHDAY list (the first such + * weekday among those days). INTERVAL=1, WKST, UNTIL and a single + * BYHOUR/BYMINUTE/BYSECOND are accepted. + * + * Any other rule makes the whole VTIMEZONE unevaluable. In that case + * offsetAt() returns null instead of an approximation, so the caller can + * fall back deliberately rather than shift a meeting by an hour. + */ +final class VtimezoneOffsets +{ + private const WEEKDAYS = [ + 'SU' => 0, + 'MO' => 1, + 'TU' => 2, + 'WE' => 3, + 'TH' => 4, + 'FR' => 5, + 'SA' => 6, + ]; + + private const SUPPORTED_RULE_PARTS = [ + 'FREQ', + 'INTERVAL', + 'WKST', + 'BYMONTH', + 'BYDAY', + 'BYMONTHDAY', + 'BYHOUR', + 'BYMINUTE', + 'BYSECOND', + 'UNTIL', + ]; + + /** + * Return the UTC offset in effect for a local wall-clock time. + * + * @param Vtimezone $vtimezone The VTIMEZONE to evaluate. + * @param int $wallTime The wall-clock reading expressed as if it + * were UTC (the result of gmmktime()). + * + * @return int|null Seconds east of UTC (3600 for +01:00), or null when + * the VTIMEZONE cannot be evaluated exactly. + */ + public function offsetAt(Vtimezone $vtimezone, int $wallTime): ?int + { + $year = (int) gmdate('Y', $wallTime); + + $transitions = []; + $observances = array_merge( + $vtimezone->getChildrenByType('STANDARD'), + $vtimezone->getChildrenByType('DAYLIGHT') + ); + foreach ($observances as $observance) { + $found = $this->transitions($observance, $year); + if ($found === null) { + return null; + } + array_push($transitions, ...$found); + } + + if ($transitions === []) { + return null; + } + + usort( + $transitions, + static fn(array $a, array $b): int => $a['onset'] <=> $b['onset'] + ); + + // Before the first known transition the zone is in the state the + // first transition leaves. + $offset = $transitions[0]['from']; + foreach ($transitions as $transition) { + if ($transition['onset'] > $wallTime) { + break; + } + $offset = $transition['to']; + } + + return $offset; + } + + /** + * Collect the transitions of one observance that can affect $year. + * + * The onset is the wall-clock time at which the observance begins, + * expressed in the offset in effect before it (TZOFFSETFROM), as + * RFC 5545 defines it. + * + * @return list|null + * Null when the observance uses an unsupported construct. + */ + private function transitions(Component $observance, int $year): ?array + { + $properties = $observance->getProperties(); + + $from = $this->parseOffset($properties->getValue('TZOFFSETFROM')); + $to = $this->parseOffset($properties->getValue('TZOFFSETTO')); + $rawDtstart = $properties->getValue('DTSTART'); + if ($rawDtstart === null) { + // RFC 5545 requires DTSTART; an observance without one does not + // say when it applies, so it cannot contribute a transition. + return []; + } + $dtstart = $this->parseWallTime($rawDtstart); + if ($from === null || $to === null || $dtstart === null) { + return null; + } + + $onsets = []; + + foreach ($properties->getAllValues('RDATE') as $rdates) { + foreach (explode(',', $rdates) as $rdate) { + $onset = $this->parseWallTime(trim($rdate)); + if ($onset === null) { + return null; + } + $onsets[] = $onset; + } + } + + $rrule = $properties->getValue('RRULE'); + if ($rrule === null) { + // Without a rule DTSTART is the (only) transition. + $onsets[] = $dtstart; + } else { + $rule = $this->parseYearlyRule($rrule, $dtstart); + if ($rule === null) { + return null; + } + $startYear = (int) gmdate('Y', $dtstart); + $candidateYears = [$year - 1, $year]; + if ($rule['until'] !== null) { + // A rule that ended before the window still decided the + // offset that applies afterwards (e.g. a zone that gave up + // DST), so include its last occurrences. + $untilYear = (int) gmdate('Y', $rule['until']); + if ($untilYear < $year - 1) { + array_unshift($candidateYears, $untilYear - 1, $untilYear); + } + } + foreach ($candidateYears as $candidateYear) { + if ($candidateYear < $startYear) { + continue; + } + $day = $this->dayOfMonth($candidateYear, $rule); + if ($day === null) { + continue; + } + $onset = gmmktime(0, 0, 0, $rule['month'], $day, $candidateYear) + $rule['timeOfDay']; + if ($onset < $dtstart) { + continue; + } + if ($rule['until'] !== null + && $onset - ($rule['untilIsUtc'] ? $from : 0) > $rule['until']) { + continue; + } + $onsets[] = $onset; + } + } + + return array_map( + static fn(int $onset): array => ['onset' => $onset, 'from' => $from, 'to' => $to], + $onsets + ); + } + + /** + * Parse the supported yearly rule. + * + * @return array{ + * month: int, + * weekday: int, + * ordinal: int|null, + * monthdays: list, + * timeOfDay: int, + * until: int|null, + * untilIsUtc: bool + * }|null + */ + private function parseYearlyRule(string $rrule, int $dtstart): ?array + { + $parts = []; + foreach (explode(';', $rrule) as $part) { + $pair = explode('=', $part, 2); + if (count($pair) !== 2) { + return null; + } + $parts[strtoupper($pair[0])] = $pair[1]; + } + + if (($parts['FREQ'] ?? '') !== 'YEARLY' + || (isset($parts['INTERVAL']) && $parts['INTERVAL'] !== '1') + || array_diff(array_keys($parts), self::SUPPORTED_RULE_PARTS) !== []) { + return null; + } + + if (!isset($parts['BYMONTH'], $parts['BYDAY']) + || !preg_match('/^\d{1,2}$/', $parts['BYMONTH']) + || !preg_match('/^([+-]?\d)?(SU|MO|TU|WE|TH|FR|SA)$/i', $parts['BYDAY'], $day)) { + return null; + } + $month = (int) $parts['BYMONTH']; + if ($month < 1 || $month > 12) { + return null; + } + + $ordinal = $day[1] === '' ? null : (int) $day[1]; + $monthdays = []; + if (isset($parts['BYMONTHDAY'])) { + foreach (explode(',', $parts['BYMONTHDAY']) as $monthday) { + if (!preg_match('/^\d{1,2}$/', $monthday) || (int) $monthday < 1 || (int) $monthday > 31) { + return null; + } + $monthdays[] = (int) $monthday; + } + sort($monthdays); + } elseif ($ordinal === null || $ordinal === 0) { + // A bare weekday would match every such day of the month. + return null; + } + + // Time of day comes from DTSTART unless BYHOUR/BYMINUTE/BYSECOND + // restate it. DTSTART is often in year 1601, a negative timestamp, + // so use a floor modulo. + $seconds = (($dtstart % 86400) + 86400) % 86400; + $time = [ + 'BYHOUR' => intdiv($seconds, 3600), + 'BYMINUTE' => intdiv($seconds % 3600, 60), + 'BYSECOND' => $seconds % 60, + ]; + foreach ($time as $name => $default) { + if (isset($parts[$name])) { + if (!preg_match('/^\d{1,2}$/', $parts[$name])) { + return null; + } + $time[$name] = (int) $parts[$name]; + } + } + + $until = null; + $untilIsUtc = false; + if (isset($parts['UNTIL'])) { + $until = $this->parseUntil($parts['UNTIL']); + if ($until === null) { + return null; + } + $untilIsUtc = str_ends_with(strtoupper($parts['UNTIL']), 'Z'); + } + + return [ + 'month' => $month, + 'weekday' => self::WEEKDAYS[strtoupper($day[2])], + 'ordinal' => $ordinal, + 'monthdays' => $monthdays, + 'timeOfDay' => $time['BYHOUR'] * 3600 + $time['BYMINUTE'] * 60 + $time['BYSECOND'], + 'until' => $until, + 'untilIsUtc' => $untilIsUtc, + ]; + } + + /** + * Day of the month the rule selects in a year, or null if none. + * + * @param array{month: int, weekday: int, ordinal: int|null, monthdays: list} $rule + */ + private function dayOfMonth(int $year, array $rule): ?int + { + $firstOfMonth = gmmktime(0, 0, 0, $rule['month'], 1, $year); + $daysInMonth = (int) gmdate('t', $firstOfMonth); + $firstWeekday = (int) gmdate('w', $firstOfMonth); + + if ($rule['monthdays'] !== []) { + foreach ($rule['monthdays'] as $monthday) { + if ($monthday <= $daysInMonth + && (($firstWeekday + $monthday - 1) % 7) === $rule['weekday']) { + return $monthday; + } + } + + return null; + } + + if ($rule['ordinal'] > 0) { + $day = 1 + (($rule['weekday'] - $firstWeekday + 7) % 7) + ($rule['ordinal'] - 1) * 7; + } else { + $lastWeekday = ($firstWeekday + $daysInMonth - 1) % 7; + $day = $daysInMonth - (($lastWeekday - $rule['weekday'] + 7) % 7) + ($rule['ordinal'] + 1) * 7; + } + + return ($day >= 1 && $day <= $daysInMonth) ? $day : null; + } + + /** + * Parse an UNTIL value. + * + * Older Horde exports wrote malformed values such as "19440325T16000Z". + * Only the end of a historic rule depends on the time part, so when the + * time part is malformed the date alone is used. + */ + private function parseUntil(string $value): ?int + { + $value = trim($value); + + $until = $this->parseWallTime($value); + if ($until !== null) { + return $until; + } + + if (preg_match('/^(\d{4})(\d{2})(\d{2})(?:T\d*)?Z?$/i', $value, $m) + && checkdate((int) $m[2], (int) $m[3], (int) $m[1])) { + return gmmktime(0, 0, 0, (int) $m[2], (int) $m[3], (int) $m[1]); + } + + return null; + } + + /** + * Parse a UTC offset such as "+0100" or "-053000" into seconds. + */ + private function parseOffset(?string $value): ?int + { + if ($value === null || !preg_match('/^([+-])(\d{2})(\d{2})(\d{2})?$/', trim($value), $m)) { + return null; + } + + $seconds = (int) $m[2] * 3600 + (int) $m[3] * 60 + (int) ($m[4] ?? 0); + + return $m[1] === '-' ? -$seconds : $seconds; + } + + /** + * Parse "YYYYMMDDTHHMMSS[Z]" into a wall-clock reading (as if UTC). + */ + private function parseWallTime(?string $value): ?int + { + if ($value === null + || !preg_match('/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?$/i', trim($value), $m) + || !checkdate((int) $m[2], (int) $m[3], (int) $m[1])) { + return null; + } + + return gmmktime((int) $m[4], (int) $m[5], (int) $m[6], (int) $m[2], (int) $m[3], (int) $m[1]); + } +} diff --git a/test/unit/Horde/ActiveSync/Calendar/CalendarTimeResolverTest.php b/test/unit/Horde/ActiveSync/Calendar/CalendarTimeResolverTest.php new file mode 100644 index 00000000..d5f95661 --- /dev/null +++ b/test/unit/Horde/ActiveSync/Calendar/CalendarTimeResolverTest.php @@ -0,0 +1,274 @@ + + * @license http://www.horde.org/licenses/gpl GPLv2 + * @copyright 2026 The Horde Project (http://www.horde.org) + * @package ActiveSync + */ + +namespace Horde\ActiveSync\Calendar; + +use Horde\Icalendar\Calendar\VCalendar; +use Horde\Icalendar\Component\AbstractComponent; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\TestCase; + +#[CoversClass(CalendarTimeResolver::class)] +#[CoversClass(VtimezoneOffsets::class)] +#[CoversClass(ResolvedTime::class)] +class CalendarTimeResolverTest extends TestCase +{ + private string $oldTz; + + protected function setUp(): void + { + $this->oldTz = date_default_timezone_get(); + date_default_timezone_set('Europe/Berlin'); + } + + protected function tearDown(): void + { + date_default_timezone_set($this->oldTz); + } + + /** + * Resolve the DTSTART of the only event in a calendar. + */ + private function resolve(string $dtstartLine, string $timezones = ''): ?ResolvedTime + { + $calendar = AbstractComponent::fromString( + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Example//EN\r\nMETHOD:REQUEST\r\n" + . $timezones + . "BEGIN:VEVENT\r\nUID:alice-1@example.com\r\n" + . "DTSTAMP:20260101T000000Z\r\n" + . $dtstartLine . "\r\n" + . "SUMMARY:Planning\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n" + ); + $this->assertInstanceOf(VCalendar::class, $calendar); + $event = $calendar->getEvents()[0]; + + return (new CalendarTimeResolver($calendar))->resolve($event->getProperties()->get('DTSTART')); + } + + /** + * A US style zone under a vendor TZID: second Sunday in March and first + * Sunday in November, DTSTART in 1601 as Outlook writes it. + */ + private function usZone(string $tzid): string + { + return "BEGIN:VTIMEZONE\r\nTZID:$tzid\r\n" + . "BEGIN:STANDARD\r\nDTSTART:16011104T020000\r\n" + . "RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=11\r\n" + . "TZOFFSETFROM:-0400\r\nTZOFFSETTO:-0500\r\nEND:STANDARD\r\n" + . "BEGIN:DAYLIGHT\r\nDTSTART:16010311T020000\r\n" + . "RRULE:FREQ=YEARLY;BYDAY=2SU;BYMONTH=3\r\n" + . "TZOFFSETFROM:-0500\r\nTZOFFSETTO:-0400\r\nEND:DAYLIGHT\r\n" + . "END:VTIMEZONE\r\n"; + } + + public function testUtcValue(): void + { + $result = $this->resolve('DTSTART:20260701T100000Z'); + + $this->assertSame(gmmktime(10, 0, 0, 7, 1, 2026), $result->timestamp); + $this->assertNull($result->unresolvedTzid); + } + + public function testFloatingValueUsesServerTimeZone(): void + { + $result = $this->resolve('DTSTART:20260701T100000'); + + // Berlin is UTC+2 in July. + $this->assertSame(gmmktime(8, 0, 0, 7, 1, 2026), $result->timestamp); + $this->assertNull($result->unresolvedTzid); + } + + public function testDateValueUsesServerTimeZone(): void + { + $result = $this->resolve('DTSTART;VALUE=DATE:20260701'); + + $this->assertSame(gmmktime(22, 0, 0, 6, 30, 2026), $result->timestamp); + } + + public function testIanaTzidWithoutVtimezone(): void + { + $result = $this->resolve('DTSTART;TZID=America/New_York:20260115T100000'); + + $this->assertSame(gmmktime(15, 0, 0, 1, 15, 2026), $result->timestamp); + $this->assertNull($result->unresolvedTzid); + } + + public function testWindowsTzidWithoutVtimezoneIsMapped(): void + { + $result = $this->resolve('DTSTART;TZID=W. Europe Standard Time:20260115T100000'); + + $this->assertSame(gmmktime(9, 0, 0, 1, 15, 2026), $result->timestamp); + $this->assertNull($result->unresolvedTzid); + } + + /** + * @dataProvider customZoneProvider + */ + public function testCustomTzidIsResolvedFromVtimezone(string $local, int $expectedUtc): void + { + $result = $this->resolve( + 'DTSTART;TZID=Custom Eastern:' . $local, + $this->usZone('Custom Eastern') + ); + + $this->assertSame($expectedUtc, $result->timestamp); + $this->assertNull($result->unresolvedTzid); + } + + public static function customZoneProvider(): array + { + return [ + 'winter' => ['20260115T100000', gmmktime(15, 0, 0, 1, 15, 2026)], + 'summer' => ['20260715T100000', gmmktime(14, 0, 0, 7, 15, 2026)], + 'day before DST starts' => ['20260307T120000', gmmktime(17, 0, 0, 3, 7, 2026)], + 'day DST starts' => ['20260308T120000', gmmktime(16, 0, 0, 3, 8, 2026)], + 'day DST ends' => ['20261101T120000', gmmktime(17, 0, 0, 11, 1, 2026)], + 'leap day' => ['20280229T120000', gmmktime(17, 0, 0, 2, 29, 2028)], + ]; + } + + public function testVtimezoneWinsOverTzidName(): void + { + // The calendar redefines an IANA name with a fixed -0300 offset. + $zone = "BEGIN:VTIMEZONE\r\nTZID:Europe/Berlin\r\n" + . "BEGIN:STANDARD\r\nDTSTART:20000101T000000\r\n" + . "TZOFFSETFROM:-0300\r\nTZOFFSETTO:-0300\r\nEND:STANDARD\r\n" + . "END:VTIMEZONE\r\n"; + + $result = $this->resolve('DTSTART;TZID=Europe/Berlin:20260115T100000', $zone); + + $this->assertSame(gmmktime(13, 0, 0, 1, 15, 2026), $result->timestamp); + } + + public function testUnknownTzidWithoutVtimezoneIsReported(): void + { + $result = $this->resolve('DTSTART;TZID=Mystery Standard Time:20260701T100000'); + + $this->assertSame('Mystery Standard Time', $result->unresolvedTzid); + // Falls back to the server time zone (Berlin, UTC+2). + $this->assertSame(gmmktime(8, 0, 0, 7, 1, 2026), $result->timestamp); + } + + public function testUnsupportedVtimezoneFallsBackToIanaName(): void + { + $zone = "BEGIN:VTIMEZONE\r\nTZID:Europe/Berlin\r\n" + . "BEGIN:STANDARD\r\nDTSTART:20000101T000000\r\n" + . "RRULE:FREQ=DAILY;COUNT=3\r\n" + . "TZOFFSETFROM:+0100\r\nTZOFFSETTO:+0100\r\nEND:STANDARD\r\n" + . "END:VTIMEZONE\r\n"; + + $result = $this->resolve('DTSTART;TZID=Europe/Berlin:20260701T100000', $zone); + + $this->assertSame(gmmktime(8, 0, 0, 7, 1, 2026), $result->timestamp); + $this->assertNull($result->unresolvedTzid); + } + + /** + * @dataProvider invalidValueProvider + */ + public function testInvalidValueResolvesToNull(string $line): void + { + $this->assertNull($this->resolve($line)); + } + + public static function invalidValueProvider(): array + { + return [ + 'text' => ['DTSTART:tomorrow'], + 'impossible date' => ['DTSTART:20260231T100000Z'], + 'truncated' => ['DTSTART:2026070'], + ]; + } + + public function testVcalendar10ValueWithTrailingFields(): void + { + $result = $this->resolve('DTSTART:20260701T100000Z;PT10M;3;Beep'); + + $this->assertSame(gmmktime(10, 0, 0, 7, 1, 2026), $result->timestamp); + } + + /** + * Zone whose DST rules ended long ago and that has stayed on standard + * time since (Brisbane style). + */ + public function testExpiredRulesLeaveTheLastOffsetInForce(): void + { + $zone = "BEGIN:VTIMEZONE\r\nTZID:Expired\r\n" + . "BEGIN:DAYLIGHT\r\nDTSTART:19891029T020000\r\n" + . "RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10;UNTIL=19911026T160000Z\r\n" + . "TZOFFSETFROM:+1000\r\nTZOFFSETTO:+1100\r\nEND:DAYLIGHT\r\n" + . "BEGIN:STANDARD\r\nDTSTART:19900304T020000\r\n" + . "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=1SU;UNTIL=19920229T160000Z\r\n" + . "TZOFFSETFROM:+1100\r\nTZOFFSETTO:+1000\r\nEND:STANDARD\r\n" + . "END:VTIMEZONE\r\n"; + + $result = $this->resolve('DTSTART;TZID=Expired:20260115T120000', $zone); + + $this->assertSame(gmmktime(2, 0, 0, 1, 15, 2026), $result->timestamp); + } + + public function testObservanceWithoutDtstartIsIgnored(): void + { + $zone = "BEGIN:VTIMEZONE\r\nTZID:Partial\r\n" + . "BEGIN:STANDARD\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0000\r\nEND:STANDARD\r\n" + . "BEGIN:STANDARD\r\nDTSTART:19710101T000000\r\n" + . "TZOFFSETFROM:+0000\r\nTZOFFSETTO:+0200\r\nEND:STANDARD\r\n" + . "END:VTIMEZONE\r\n"; + + $result = $this->resolve('DTSTART;TZID=Partial:20260115T120000', $zone); + + $this->assertSame(gmmktime(10, 0, 0, 1, 15, 2026), $result->timestamp); + } + + /** + * Rules restated with BYMONTHDAY, BYHOUR and WKST, as some exporters + * write the "second Sunday" of a month. + */ + public function testRuleWithByMonthDayAndTimeParts(): void + { + $zone = "BEGIN:VTIMEZONE\r\nTZID:Exporter\r\n" + . "BEGIN:STANDARD\r\nDTSTART:16011104T000000\r\n" + . "RRULE:FREQ=YEARLY;WKST=MO;INTERVAL=1;BYMONTH=11;BYDAY=SU;BYMONTHDAY=1,2,3,4,5,6,7;BYHOUR=2\r\n" + . "TZOFFSETFROM:-0400\r\nTZOFFSETTO:-0500\r\nEND:STANDARD\r\n" + . "BEGIN:DAYLIGHT\r\nDTSTART:16010311T000000\r\n" + . "RRULE:FREQ=YEARLY;WKST=MO;INTERVAL=1;BYMONTH=3;BYDAY=SU;BYMONTHDAY=8,9,10,11,12,13,14;BYHOUR=2\r\n" + . "TZOFFSETFROM:-0500\r\nTZOFFSETTO:-0400\r\nEND:DAYLIGHT\r\n" + . "END:VTIMEZONE\r\n"; + + $summer = $this->resolve('DTSTART;TZID=Exporter:20260715T100000', $zone); + $winter = $this->resolve('DTSTART;TZID=Exporter:20260115T100000', $zone); + $afterSwitch = $this->resolve('DTSTART;TZID=Exporter:20260308T120000', $zone); + $beforeSwitch = $this->resolve('DTSTART;TZID=Exporter:20260307T120000', $zone); + + $this->assertSame(gmmktime(14, 0, 0, 7, 15, 2026), $summer->timestamp); + $this->assertSame(gmmktime(15, 0, 0, 1, 15, 2026), $winter->timestamp); + $this->assertSame(gmmktime(16, 0, 0, 3, 8, 2026), $afterSwitch->timestamp); + $this->assertSame(gmmktime(17, 0, 0, 3, 7, 2026), $beforeSwitch->timestamp); + } + + public function testOffsetsReturnNullForUnsupportedRule(): void + { + $calendar = AbstractComponent::fromString( + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Example//EN\r\n" + . "BEGIN:VTIMEZONE\r\nTZID:Odd\r\n" + . "BEGIN:STANDARD\r\nDTSTART:20000101T000000\r\nRRULE:FREQ=MONTHLY\r\n" + . "TZOFFSETFROM:+0100\r\nTZOFFSETTO:+0100\r\nEND:STANDARD\r\n" + . "END:VTIMEZONE\r\n" + . "END:VCALENDAR\r\n" + ); + + $this->assertNull( + (new VtimezoneOffsets())->offsetAt($calendar->getTimezones()[0], gmmktime(12, 0, 0, 7, 1, 2026)) + ); + } +} diff --git a/test/unit/Horde/ActiveSync/Imap/EasMessageBuilderMeetingRequestTest.php b/test/unit/Horde/ActiveSync/Imap/EasMessageBuilderMeetingRequestTest.php new file mode 100644 index 00000000..baaee2ef --- /dev/null +++ b/test/unit/Horde/ActiveSync/Imap/EasMessageBuilderMeetingRequestTest.php @@ -0,0 +1,198 @@ + + * @license http://www.horde.org/licenses/gpl GPLv2 + * @copyright 2026 The Horde Project (http://www.horde.org) + * @package ActiveSync + */ + +namespace Horde\ActiveSync\Imap; + +use Horde_ActiveSync; +use Horde_ActiveSync_Imap_EasMessageBuilder; +use Horde_ActiveSync_Log_Logger; +use Horde_ActiveSync_Message_Mail; +use Horde_ActiveSync_Message_MeetingRequest; +use Horde_Log_Handler_Null; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\TestCase; +use ReflectionClass; + +#[CoversClass(Horde_ActiveSync_Imap_EasMessageBuilder::class)] +class EasMessageBuilderMeetingRequestTest extends TestCase +{ + /** + * Run the builder's iTip handling on a calendar and return the message. + */ + private function build(string $ics): Horde_ActiveSync_Message_Mail + { + $logger = new Horde_ActiveSync_Log_Logger(new Horde_Log_Handler_Null()); + $message = new Horde_ActiveSync_Message_Mail([ + 'logger' => $logger, + 'protocolversion' => Horde_ActiveSync::VERSION_SIXTEENONE, + ]); + + $part = new class ($ics) { + public function __construct(private string $ics) + { + } + + public function getContents(): string + { + return $this->ics; + } + + public function getCharset(): string + { + return 'UTF-8'; + } + }; + $imapMessage = new class ($part) { + public function __construct(private object $part) + { + } + + public function hasiCalendar(): object + { + return $this->part; + } + }; + + // The constructor needs a full IMAP message; only the iTip handling + // is under test. + $reflection = new ReflectionClass(Horde_ActiveSync_Imap_EasMessageBuilder::class); + $builder = $reflection->newInstanceWithoutConstructor(); + foreach ([ + '_version' => Horde_ActiveSync::VERSION_SIXTEENONE, + '_logger' => $logger, + '_easMessage' => $message, + '_imapMessage' => $imapMessage, + ] as $name => $value) { + $property = $reflection->getProperty($name); + $property->setValue($builder, $value); + } + $reflection->getMethod('_meetingRequest')->invoke($builder); + + return $message; + } + + private function calendar(array $calendarLines, array $eventLines = []): string + { + return implode("\r\n", array_merge( + ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Example//Test//EN'], + $calendarLines, + [ + 'BEGIN:VEVENT', + 'UID:test-event-uid@example.test', + 'DTSTART:20260618T220000Z', + 'DTEND:20260618T230000Z', + 'DTSTAMP:20260619T195852Z', + 'ORGANIZER:mailto:organizer@example.test', + ], + $eventLines, + ['END:VEVENT', 'END:VCALENDAR', ''] + )); + } + + public function testRequestBecomesMeetingRequest(): void + { + $message = $this->build($this->calendar(['METHOD:REQUEST'])); + + $this->assertSame('IPM.Schedule.Meeting.Request', $message->messageclass); + $this->assertSame('urn:content-classes:calendarmessage', $message->contentclass); + $this->assertInstanceOf(Horde_ActiveSync_Message_MeetingRequest::class, $message->meetingrequest); + } + + /** + * A repeated METHOD made the legacy reader return an array, which + * crashed the whole sync with a TypeError. + */ + public function testRepeatedMethodDoesNotBreakTheSync(): void + { + $message = $this->build($this->calendar(['METHOD:REQUEST', 'METHOD:REQUEST'])); + + $this->assertSame('IPM.Schedule.Meeting.Request', $message->messageclass); + $this->assertInstanceOf(Horde_ActiveSync_Message_MeetingRequest::class, $message->meetingrequest); + } + + public function testMissingMethodIsTreatedAsRequest(): void + { + $message = $this->build($this->calendar([])); + + $this->assertSame('IPM.Schedule.Meeting.Request', $message->messageclass); + } + + public function testCancelBecomesCanceledMeeting(): void + { + $message = $this->build($this->calendar(['METHOD:CANCEL'])); + + $this->assertSame(Horde_ActiveSync_Message_Mail::CLASS_MEETING_CANCELED, $message->messageclass); + } + + /** + * @dataProvider replyProvider + */ + public function testReplyMapsParticipationStatus(string $partstat, string $expectedClass): void + { + $message = $this->build($this->calendar( + ['METHOD:REPLY'], + ['ATTENDEE;PARTSTAT=' . $partstat . ':mailto:attendee@example.test'] + )); + + $this->assertSame($expectedClass, $message->messageclass); + $this->assertInstanceOf(Horde_ActiveSync_Message_MeetingRequest::class, $message->meetingrequest); + } + + public static function replyProvider(): array + { + return [ + 'accepted' => ['ACCEPTED', 'IPM.Schedule.Meeting.Resp.Pos'], + 'declined' => ['DECLINED', 'IPM.Schedule.Meeting.Resp.Neg'], + 'tentative' => ['TENTATIVE', 'IPM.Schedule.Meeting.Resp.Tent'], + 'lower case' => ['accepted', 'IPM.Schedule.Meeting.Resp.Pos'], + ]; + } + + public function testReplyWithoutAttendeeDegradesToPlainMail(): void + { + $message = $this->build($this->calendar(['METHOD:REPLY'])); + + $this->assertEmpty($message->messageclass); + $this->assertEmpty($message->meetingrequest); + } + + public function testEventWithoutStartDegradesToPlainMail(): void + { + $ics = str_replace("DTSTART:20260618T220000Z\r\n", '', $this->calendar(['METHOD:REQUEST'])); + + $message = $this->build($ics); + + $this->assertEmpty($message->messageclass); + $this->assertEmpty($message->contentclass); + } + + /** + * @dataProvider unusableCalendarProvider + */ + public function testUnusableCalendarLeavesTheMailUntouched(string $ics): void + { + $message = $this->build($ics); + + $this->assertEmpty($message->messageclass); + $this->assertEmpty($message->contentclass); + } + + public static function unusableCalendarProvider(): array + { + return [ + 'not a calendar' => ["just some text\r\n"], + 'unterminated' => ["BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:x\r\n"], + 'no event' => ["BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//E//T//EN\r\nMETHOD:REQUEST\r\nEND:VCALENDAR\r\n"], + ]; + } +} diff --git a/test/unit/Horde/ActiveSync/Message/MeetingRequestTest.php b/test/unit/Horde/ActiveSync/Message/MeetingRequestTest.php index 8eda79b6..dc0117d3 100755 --- a/test/unit/Horde/ActiveSync/Message/MeetingRequestTest.php +++ b/test/unit/Horde/ActiveSync/Message/MeetingRequestTest.php @@ -11,10 +11,15 @@ namespace Horde\ActiveSync; +use Horde\Icalendar\Calendar\VCalendar; +use Horde\Icalendar\Component\AbstractComponent; use Horde_ActiveSync; +use Horde_ActiveSync_Exception; use Horde_ActiveSync_Log_Logger; use Horde_ActiveSync_Message_MeetingRequest; +use Horde_Date; use Horde_Icalendar; +use Horde_Icalendar_Vevent; use Horde_Log_Handler_Null; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; @@ -136,27 +141,309 @@ public function testFromVeventSetsInstanceTypeForRecurrenceId(): void ); } + public function testRepeatedMethodUsesTheFirstValue(): void + { + $ics = str_replace( + "METHOD:REQUEST\r\n", + "METHOD:REQUEST\r\nMETHOD:REQUEST\r\nMETHOD:CANCEL\r\n", + $this->_buildVcalendar() + ); + + $message = $this->_parse($ics); + + $this->assertSame('1', $message->getProperty('responserequested')); + $this->assertSame( + Horde_ActiveSync_Message_MeetingRequest::MEETING_MESSAGE_INITIAL, + $message->getProperty('meetingmessagetype') + ); + } + + public function testMissingMethodIsTreatedAsRequest(): void + { + $ics = str_replace("METHOD:REQUEST\r\n", '', $this->_buildVcalendar()); + + $message = $this->_parse($ics); + + $this->assertSame('1', $message->getProperty('responserequested')); + } + + public function testMethodIsCaseInsensitive(): void + { + $message = $this->_createMeetingRequest(Horde_ActiveSync::VERSION_SIXTEENONE, [], 'cancel'); + + $this->assertSame('0', $message->getProperty('responserequested')); + } + + public function testSequenceMakesRequestAnUpdate(): void + { + $message = $this->_createMeetingRequest( + Horde_ActiveSync::VERSION_SIXTEENONE, + ['SEQUENCE:2'] + ); + + $this->assertSame( + Horde_ActiveSync_Message_MeetingRequest::MEETING_MESSAGE_UPDATE, + $message->getProperty('meetingmessagetype') + ); + } + + public function testTimesAndOrganizerAreExported(): void + { + $message = $this->_createMeetingRequest(Horde_ActiveSync::VERSION_SIXTEENONE); + + $this->assertSame(gmmktime(22, 0, 0, 6, 18, 2026), $message->getProperty('starttime')->timestamp()); + $this->assertSame(gmmktime(23, 0, 0, 6, 18, 2026), $message->getProperty('endtime')->timestamp()); + $this->assertSame(gmmktime(19, 58, 52, 6, 19, 2026), $message->getProperty('dtstamp')->timestamp()); + $this->assertSame('organizer@example.test', $message->getProperty('organizer')); + $this->assertSame('0', (string) $message->getProperty('alldayevent')); + } + + public function testWindowsTimeZoneWithEmbeddedVtimezone(): void + { + $zone = [ + 'BEGIN:VTIMEZONE', + 'TZID:W. Europe Standard Time', + 'BEGIN:STANDARD', + 'DTSTART:16011028T030000', + 'RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10', + 'TZOFFSETFROM:+0200', + 'TZOFFSETTO:+0100', + 'END:STANDARD', + 'BEGIN:DAYLIGHT', + 'DTSTART:16010325T020000', + 'RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3', + 'TZOFFSETFROM:+0100', + 'TZOFFSETTO:+0200', + 'END:DAYLIGHT', + 'END:VTIMEZONE', + ]; + $ics = $this->_replaceEventTimes( + $this->_buildVcalendar([], 'REQUEST', $zone), + 'DTSTART;TZID=W. Europe Standard Time:20260715T100000', + 'DTEND;TZID=W. Europe Standard Time:20260715T110000' + ); + + $message = $this->_parse($ics); + + // Summer time in Central Europe is UTC+2. + $this->assertSame(gmmktime(8, 0, 0, 7, 15, 2026), $message->getProperty('starttime')->timestamp()); + $this->assertSame(gmmktime(9, 0, 0, 7, 15, 2026), $message->getProperty('endtime')->timestamp()); + } + + public function testUnknownTimeZoneFallsBackToServerTimeZone(): void + { + $ics = $this->_replaceEventTimes( + $this->_buildVcalendar(), + 'DTSTART;TZID=Mystery Standard Time:20260715T100000', + 'DTEND;TZID=Mystery Standard Time:20260715T110000' + ); + + $message = $this->_parse($ics); + + // The test runs with UTC as the server time zone. + $this->assertSame(gmmktime(10, 0, 0, 7, 15, 2026), $message->getProperty('starttime')->timestamp()); + } + + public function testAllDayEventIsDetected(): void + { + $ics = $this->_replaceEventTimes( + $this->_buildVcalendar(), + 'DTSTART;VALUE=DATE:20260715', + 'DTEND;VALUE=DATE:20260716' + ); + + $message = $this->_parse($ics); + + $this->assertSame(1, $message->getProperty('alldayevent')); + } + + public function testEndIsDerivedFromDuration(): void + { + $ics = $this->_replaceEventTimes($this->_buildVcalendar(), 'DTSTART:20260715T100000Z', 'DURATION:PT90M'); + + $message = $this->_parse($ics); + + $this->assertSame(gmmktime(11, 30, 0, 7, 15, 2026), $message->getProperty('endtime')->timestamp()); + } + + public function testEventWithoutUsableStartIsRejected(): void + { + $ics = $this->_replaceEventTimes($this->_buildVcalendar(), 'X-NOTHING:1', 'X-NOTHING:2'); + + $this->expectException(Horde_ActiveSync_Exception::class); + $this->_parse($ics); + } + + public function testLocationIsUnescaped(): void + { + $message = $this->_createMeetingRequest( + Horde_ActiveSync::VERSION_SIXTEENONE, + ['LOCATION:Room 1\, Building 2\; Floor 3'] + ); + + $this->assertSame('Room 1, Building 2; Floor 3', $message->getProperty('location')); + } + + public function testLocationQuotedPrintableAndCharsetAreDecoded(): void + { + $message = $this->_createMeetingRequest( + Horde_ActiveSync::VERSION_SIXTEENONE, + ['LOCATION;ENCODING=QUOTED-PRINTABLE;CHARSET=ISO-8859-1:Caf=E9 M=FCnchen'] + ); + + $this->assertSame("Caf\u{e9} M\u{fc}nchen", $message->getProperty('location')); + } + + public function testLocationIsIndependentOfEndTime(): void + { + $ics = $this->_replaceEventTimes( + $this->_buildVcalendar(['LOCATION:Room 1']), + 'DTSTART:20260715T100000Z', + 'X-NOTHING:1' + ); + + $message = $this->_parse($ics); + + $this->assertSame('Room 1', $message->getProperty('location')); + } + + public function testClassAndStatusAreMapped(): void + { + $message = $this->_createMeetingRequest( + Horde_ActiveSync::VERSION_SIXTEENONE, + ['CLASS:private', 'STATUS:tentative'] + ); + + $this->assertSame( + \Horde_ActiveSync_Message_Appointment::SENSITIVITY_PRIVATE, + $message->getProperty('sensitivity') + ); + $this->assertSame( + \Horde_ActiveSync_Message_Appointment::BUSYSTATUS_TENTATIVE, + $message->getProperty('busystatus') + ); + } + + public function testRepeatedClassDoesNotBreakParsing(): void + { + $message = $this->_createMeetingRequest( + Horde_ActiveSync::VERSION_SIXTEENONE, + ['CLASS:CONFIDENTIAL', 'CLASS:PUBLIC'] + ); + + $this->assertSame( + \Horde_ActiveSync_Message_Appointment::SENSITIVITY_CONFIDENTIAL, + $message->getProperty('sensitivity') + ); + } + + public function testRelativeAlarmSetsReminder(): void + { + $message = $this->_createMeetingRequest( + Horde_ActiveSync::VERSION_SIXTEENONE, + ['BEGIN:VALARM', 'ACTION:DISPLAY', 'TRIGGER:-PT15M', 'END:VALARM'] + ); + + $this->assertSame(900, $message->getProperty('reminder')); + } + + public function testAbsoluteAlarmSetsReminder(): void + { + $message = $this->_createMeetingRequest( + Horde_ActiveSync::VERSION_SIXTEENONE, + ['BEGIN:VALARM', 'ACTION:DISPLAY', 'TRIGGER;VALUE=DATE-TIME:20260618T214500Z', 'END:VALARM'] + ); + + $this->assertSame(900, $message->getProperty('reminder')); + } + + public function testUnparseableAlarmIsIgnored(): void + { + $message = $this->_createMeetingRequest( + Horde_ActiveSync::VERSION_SIXTEENONE, + ['BEGIN:VALARM', 'ACTION:DISPLAY', 'TRIGGER:soon', 'END:VALARM'] + ); + + $this->assertFalse($message->getProperty('reminder')); + } + + public function testLegacyEntryPointStillWorks(): void + { + $logger = new Horde_ActiveSync_Log_Logger(new Horde_Log_Handler_Null()); + $message = new Horde_ActiveSync_Message_MeetingRequest([ + 'logger' => $logger, + 'protocolversion' => Horde_ActiveSync::VERSION_SIXTEENONE, + ]); + $vcal = new Horde_Icalendar(); + $vcal->parseVcalendar($this->_buildVcalendar()); + + $message->fromvEvent($vcal); + + $this->assertSame(gmmktime(22, 0, 0, 6, 18, 2026), $message->getProperty('starttime')->timestamp()); + } + + public function testGetvEventReturnsLegacyEvent(): void + { + $message = $this->_createMeetingRequest(Horde_ActiveSync::VERSION_SIXTEENONE); + + $vevent = $message->getvEvent(); + + $this->assertInstanceOf(Horde_Icalendar_Vevent::class, $vevent); + $this->assertSame('test-event-uid@example.test', $vevent->getAttribute('UID')); + } + + public function testGetvEventIsNullBeforeParsing(): void + { + $message = new Horde_ActiveSync_Message_MeetingRequest([ + 'logger' => new Horde_ActiveSync_Log_Logger(new Horde_Log_Handler_Null()), + 'protocolversion' => Horde_ActiveSync::VERSION_SIXTEENONE, + ]); + + $this->assertNull($message->getvEvent()); + } + + /** + * Replace the DTSTART and DTEND lines of the default event. + */ + protected function _replaceEventTimes(string $ics, string $start, string $end): string + { + return str_replace( + ["DTSTART:20260618T220000Z", "DTEND:20260618T230000Z"], + [$start, $end], + $ics + ); + } + protected function _createMeetingRequest( string $version, array $extraEventLines = [], string $method = 'REQUEST' ): Horde_ActiveSync_Message_MeetingRequest + { + return $this->_parse($this->_buildVcalendar($extraEventLines, $method), $version); + } + + protected function _parse( + string $ics, + string $version = Horde_ActiveSync::VERSION_SIXTEENONE + ): Horde_ActiveSync_Message_MeetingRequest { $logger = new Horde_ActiveSync_Log_Logger(new Horde_Log_Handler_Null()); $message = new Horde_ActiveSync_Message_MeetingRequest([ 'logger' => $logger, 'protocolversion' => $version, ]); - $vcal = new Horde_Icalendar(); - $vcal->parseVcalendar($this->_buildVcalendar($extraEventLines, $method)); - $message->fromvEvent($vcal); + $calendar = AbstractComponent::fromString($ics); + $this->assertInstanceOf(VCalendar::class, $calendar); + $message->fromCalendar($calendar); return $message; } protected function _buildVcalendar( array $extraEventLines = [], - string $method = 'REQUEST' + string $method = 'REQUEST', + array $timezoneLines = [] ): string { return implode("\r\n", array_merge([ @@ -164,6 +451,7 @@ protected function _buildVcalendar( 'VERSION:2.0', 'PRODID:-//Horde//ActiveSync Test//EN', 'METHOD:' . $method, + ], $timezoneLines, [ 'BEGIN:VEVENT', 'UID:test-event-uid@example.test', 'DTSTART:20260618T220000Z',