Apps, Admin, Setting Translation (Defaults)
[tine20] / tine20 / Calendar / Convert / Event / VCalendar / Abstract.php
1 <?php
2 /**
3  * Tine 2.0
4  *
5  * @package     Calendar
6  * @subpackage  Frontend
7  * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
8  * @author      Lars Kneschke <l.kneschke@metaways.de>
9  * @copyright   Copyright (c) 2011-2014 Metaways Infosystems GmbH (http://www.metaways.de)
10  *
11  */
12
13 /**
14  * abstract class to convert a single event (repeating with exceptions) to/from VCalendar
15  *
16  * @package     Calendar
17  * @subpackage  Convert
18  */
19 class Calendar_Convert_Event_VCalendar_Abstract extends Tinebase_Convert_VCalendar_Abstract implements Tinebase_Convert_Interface
20 {
21     public static $cutypeMap = array(
22         Calendar_Model_Attender::USERTYPE_USER          => 'INDIVIDUAL',
23         Calendar_Model_Attender::USERTYPE_GROUPMEMBER   => 'INDIVIDUAL',
24         Calendar_Model_Attender::USERTYPE_GROUP         => 'GROUP',
25         Calendar_Model_Attender::USERTYPE_RESOURCE      => 'RESOURCE',
26     );
27     
28     protected $_modelName = 'Calendar_Model_Event';
29
30     /**
31      * value of METHOD property
32      * @var string
33      */
34     protected $_method;
35     
36     /**
37      * options array
38      * @var array
39      * 
40      * TODO allow more options
41      * 
42      * current options:
43      *  - onlyBasicData (only use basic event data when converting from VCALENDAR to Tine 2.0)
44      */
45     protected $_options = array();
46     
47     /**
48      * set options
49      * @param array $options
50      */
51     public function setOptions($options)
52     {
53         $this->_options = $options;
54     }
55     
56     /**
57      * convert Tinebase_Record_RecordSet to Sabre\VObject\Component
58      *
59      * @param  Tinebase_Record_RecordSet  $_records
60      * @return Sabre\VObject\Component
61      */
62     public function fromTine20RecordSet(Tinebase_Record_RecordSet $_records)
63     {
64         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) 
65             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Events: ' . print_r($_records->toArray(), true));
66         
67         // required vcalendar fields
68         $version = Tinebase_Application::getInstance()->getApplicationByName('Calendar')->version;
69         
70         $vcalendar = new \Sabre\VObject\Component\VCalendar(array(
71             'PRODID'   => "-//tine20.com//Tine 2.0 Calendar V$version//EN",
72             'VERSION'  => '2.0',
73             'CALSCALE' => 'GREGORIAN'
74         ));
75         
76         if (isset($this->_method)) {
77             $vcalendar->add('METHOD', $this->_method);
78         }
79         
80         $originatorTz = $_records->getFirstRecord() ? $_records->getFirstRecord()->originator_tz : NULL;
81         if (empty($originatorTz)) {
82             throw new Tinebase_Exception_Record_Validation('originator_tz needed for conversion to Sabre\VObject\Component');
83         }
84         
85         $vcalendar->add(new Sabre_VObject_Component_VTimezone($originatorTz));
86         
87         foreach ($_records as $_record) {
88             $this->_convertCalendarModelEvent($vcalendar, $_record);
89             
90             if ($_record->exdate instanceof Tinebase_Record_RecordSet) {
91                 $_record->exdate->addIndices(array('is_deleted'));
92                 $eventExceptions = $_record->exdate->filter('is_deleted', false);
93                 
94                 foreach ($eventExceptions as $eventException) {
95                     $this->_convertCalendarModelEvent($vcalendar, $eventException, $_record);
96                 }
97                 
98             }
99         }
100         
101         $this->_afterFromTine20Model($vcalendar);
102         
103         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) 
104             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' card ' . $vcalendar->serialize());
105         
106         return $vcalendar;
107     }
108
109     /**
110      * convert Calendar_Model_Event to Sabre\VObject\Component
111      *
112      * @param  Calendar_Model_Event  $_record
113      * @return Sabre\VObject\Component
114      */
115     public function fromTine20Model(Tinebase_Record_Abstract $_record)
116     {
117         $_records = new Tinebase_Record_RecordSet(get_class($_record), array($_record), true, false);
118         
119         return $this->fromTine20RecordSet($_records);
120     }
121     
122     /**
123      * convert calendar event to Sabre\VObject\Component
124      * 
125      * @param  \Sabre\VObject\Component\VCalendar $vcalendar
126      * @param  Calendar_Model_Event               $_event
127      * @param  Calendar_Model_Event               $_mainEvent
128      */
129     protected function _convertCalendarModelEvent(\Sabre\VObject\Component\VCalendar $vcalendar, Calendar_Model_Event $_event, Calendar_Model_Event $_mainEvent = null)
130     {
131         // clone the event and change the timezone
132         $event = clone $_event;
133         $event->setTimezone($event->originator_tz);
134         
135         $lastModifiedDateTime = $_event->last_modified_time ? $_event->last_modified_time : $_event->creation_time;
136         if (! $event->creation_time instanceof Tinebase_DateTime) {
137             throw new Tinebase_Exception_Record_Validation('creation_time needed for conversion to Sabre\VObject\Component');
138         }
139         
140         $vevent = $vcalendar->create('VEVENT', array(
141             'CREATED'       => $_event->creation_time->getClone()->setTimezone('UTC'),
142             'LAST-MODIFIED' => $lastModifiedDateTime->getClone()->setTimezone('UTC'),
143             'DTSTAMP'       => Tinebase_DateTime::now(),
144             'UID'           => $event->uid,
145         ));
146         
147         $vevent->add('SEQUENCE', $event->hasExternalOrganizer() ? $event->external_seq : $event->seq);
148         
149         if ($event->isRecurException()) {
150             $originalDtStart = $_event->getOriginalDtStart()->setTimezone($_event->originator_tz);
151             
152             $recurrenceId = $vevent->add('RECURRENCE-ID', $originalDtStart);
153             
154             if ($_mainEvent && $_mainEvent->is_all_day_event == true) {
155                 $recurrenceId['VALUE'] = 'DATE';
156             }
157         }
158         
159         // dtstart and dtend
160         $dtstart = $vevent->add('DTSTART', $_event->dtstart->getClone()->setTimezone($event->originator_tz));
161         
162         if ($event->is_all_day_event == true) {
163             $dtstart['VALUE'] = 'DATE';
164             
165             // whole day events ends at 23:59:(00|59) in Tine 2.0 but 00:00 the next day in vcalendar
166             $event->dtend->addSecond($event->dtend->get('s') == 59 ? 1 : 0);
167             $event->dtend->addMinute($event->dtend->get('i') == 59 ? 1 : 0);
168             
169             $dtend = $vevent->add('DTEND', $event->dtend);
170             $dtend['VALUE'] = 'DATE';
171         } else {
172             $dtend = $vevent->add('DTEND', $event->dtend);
173         }
174         
175         // auto status for deleted events
176         if ($event->is_deleted) {
177             $event->status = Calendar_Model_Event::STATUS_CANCELED;
178         }
179         
180         // event organizer
181         if (!empty($event->organizer)) {
182             $organizerContact = $event->resolveOrganizer();
183
184             if ($organizerContact instanceof Addressbook_Model_Contact && !empty($organizerContact->email)) {
185                 $organizer = $vevent->add(
186                     'ORGANIZER',
187                     'mailto:' . $organizerContact->email,
188                     array('CN' => $organizerContact->n_fileas, 'EMAIL' => $organizerContact->email)
189                 );
190             }
191         }
192
193         $this->_addEventAttendee($vevent, $event);
194         
195         $optionalProperties = array(
196             'class',
197             'status',
198             'description',
199             'geo',
200             'location',
201             'priority',
202             'summary',
203             'transp',
204             'url'
205         );
206         
207         foreach ($optionalProperties as $property) {
208             if (!empty($event->$property)) {
209                 $vevent->add(strtoupper($property), $event->$property);
210             }
211         }
212
213         $class = $event->class == Calendar_Model_Event::CLASS_PUBLIC ? 'PUBLIC' : 'CONFIDENTIAL';
214         $vcalendar->add('X-CALENDARSERVER-ACCESS', $class);
215         $vevent->add('X-CALENDARSERVER-ACCESS', $class);
216
217         // categories
218         if (!isset($event->tags)) {
219             $event->tags = Tinebase_Tags::getInstance()->getTagsOfRecord($event);
220         }
221         if(isset($event->tags) && count($event->tags) > 0) {
222             $vevent->add('CATEGORIES', (array) $event->tags->name);
223         }
224         
225         // repeating event properties
226         if ($event->rrule) {
227             if ($event->is_all_day_event == true) {
228                 $vevent->add('RRULE', preg_replace_callback('/UNTIL=([\d :-]{19})(?=;?)/', function($matches) {
229                     $dtUntil = new Tinebase_DateTime($matches[1]);
230                     $dtUntil->setTimezone((string) Tinebase_Core::getUserTimezone());
231                     
232                     return 'UNTIL=' . $dtUntil->format('Ymd');
233                 }, $event->rrule));
234             } else {
235                 $vevent->add('RRULE', preg_replace('/(UNTIL=)(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/', '$1$2$3$4T$5$6$7Z', $event->rrule));
236             }
237             
238             if ($event->exdate instanceof Tinebase_Record_RecordSet) {
239                 $event->exdate->addIndices(array('is_deleted'));
240                 $deletedEvents = $event->exdate->filter('is_deleted', true);
241                 
242                 foreach ($deletedEvents as $deletedEvent) {
243                     $dateTime = $deletedEvent->getOriginalDtStart();
244
245                     $exdate = $vevent->add('EXDATE');
246                     
247                     if ($event->is_all_day_event == true) {
248                         $dateTime->setTimezone($event->originator_tz);
249                         $exdate['VALUE'] = 'DATE';
250                     }
251                     
252                     $exdate->setValue($dateTime);
253                 }
254             }
255         }
256         
257         $ownAttendee = Calendar_Model_Attender::getOwnAttender($event->attendee);
258         
259         if ($event->alarms instanceof Tinebase_Record_RecordSet) {
260             $mozLastAck = NULL;
261             $mozSnooze = NULL;
262             
263             foreach ($event->alarms as $alarm) {
264                 $valarm = $vcalendar->create('VALARM');
265                 $valarm->add('ACTION', 'DISPLAY');
266                 $valarm->add('DESCRIPTION', $event->summary);
267                 
268                 if ($dtack = Calendar_Controller_Alarm::getAcknowledgeTime($alarm)) {
269                     $valarm->add('ACKNOWLEDGED', $dtack->getClone()->setTimezone('UTC')->format('Ymd\\THis\\Z'));
270                     $mozLastAck = $dtack > $mozLastAck ? $dtack : $mozLastAck;
271                 }
272                 
273                 if ($dtsnooze = Calendar_Controller_Alarm::getSnoozeTime($alarm)) {
274                     $mozSnooze = $dtsnooze > $mozSnooze ? $dtsnooze : $mozSnooze;
275                 }
276                 if (is_numeric($alarm->minutes_before)) {
277                     if ($event->dtstart == $alarm->alarm_time) {
278                         $periodString = 'PT0S';
279                     } else {
280                         $interval = $event->dtstart->diff($alarm->alarm_time);
281                         $periodString = sprintf('%sP%s%s%s%s',
282                             $interval->format('%r'),
283                             $interval->format('%d') > 0 ? $interval->format('%dD') : null,
284                             ($interval->format('%h') > 0 || $interval->format('%i') > 0) ? 'T' : null,
285                             $interval->format('%h') > 0 ? $interval->format('%hH') : null,
286                             $interval->format('%i') > 0 ? $interval->format('%iM') : null
287                         );
288                     }
289                     # TRIGGER;VALUE=DURATION:-PT1H15M
290                     $trigger = $valarm->add('TRIGGER', $periodString);
291                     $trigger['VALUE'] = "DURATION";
292                 } else {
293                     # TRIGGER;VALUE=DATE-TIME:...
294                     $trigger = $valarm->add('TRIGGER', $alarm->alarm_time->getClone()->setTimezone('UTC')->format('Ymd\\THis\\Z'));
295                     $trigger['VALUE'] = "DATE-TIME";
296                 }
297                 
298                 $vevent->add($valarm);
299             }
300             
301             if ($mozLastAck instanceof DateTime) {
302                 $vevent->add('X-MOZ-LASTACK', $mozLastAck->getClone()->setTimezone('UTC'), array('VALUE' => 'DATE-TIME'));
303             }
304             
305             if ($mozSnooze instanceof DateTime) {
306                 $vevent->add('X-MOZ-SNOOZE-TIME', $mozSnooze->getClone()->setTimezone('UTC'), array('VALUE' => 'DATE-TIME'));
307             }
308         }
309         
310         $baseUrl = Tinebase_Core::getHostname() . "/webdav/Calendar/records/Calendar_Model_Event/{$event->getId()}/";
311         
312         if ($event->attachments instanceof Tinebase_Record_RecordSet) {
313             foreach ($event->attachments as $attachment) {
314                 $filename = rawurlencode($attachment->name);
315                 $attach = $vcalendar->createProperty('ATTACH', "{$baseUrl}{$filename}", array(
316                     'MANAGED-ID' => $attachment->hash,
317                     'FMTTYPE'    => $attachment->contenttype,
318                     'SIZE'       => $attachment->size,
319                     'FILENAME'   => $filename
320                 ), 'TEXT');
321                 
322                 $vevent->add($attach);
323             }
324             
325         }
326         
327         $vcalendar->add($vevent);
328     }
329     
330     /**
331      * add event attendee to VEVENT object 
332      * 
333      * @param \Sabre\VObject\Component\VEvent $vevent
334      * @param Calendar_Model_Event            $event
335      */
336     protected function _addEventAttendee(\Sabre\VObject\Component\VEvent $vevent, Calendar_Model_Event $event)
337     {
338         if (empty($event->attendee)) {
339             return;
340         }
341         
342         Calendar_Model_Attender::resolveAttendee($event->attendee, FALSE, $event);
343         
344         foreach($event->attendee as $eventAttendee) {
345             $attendeeEmail = $eventAttendee->getEmail();
346             
347             $parameters = array(
348                 'CN'       => $eventAttendee->getName(),
349                 'CUTYPE'   => Calendar_Convert_Event_VCalendar_Abstract::$cutypeMap[$eventAttendee->user_type],
350                 'PARTSTAT' => $eventAttendee->status,
351                 'ROLE'     => "{$eventAttendee->role}-PARTICIPANT",
352                 'RSVP'     => 'FALSE'
353             );
354             if (strpos($attendeeEmail, '@') !== false) {
355                 $parameters['EMAIL'] = $attendeeEmail;
356             }
357             $vevent->add('ATTENDEE', (strpos($attendeeEmail, '@') !== false ? 'mailto:' : 'urn:uuid:') . $attendeeEmail, $parameters);
358         }
359     }
360
361     /**
362      * set the METHOD for the generated VCALENDAR
363      *
364      * @param  string  $_method  the method
365      */
366     public function setMethod($method)
367     {
368         $this->_method = $method;
369     }
370     
371     /**
372      * converts vcalendar to Calendar_Model_Event
373      * 
374      * @param  mixed                 $_blob    the VCALENDAR to parse
375      * @param  Calendar_Model_Event  $_record  update existing event
376      * @param  array                 $options  array of options
377      * @return Calendar_Model_Event
378      */
379     public function toTine20Model($blob, Tinebase_Record_Abstract $_record = null, $options = array())
380     {
381         $vcalendar = self::getVObject($blob);
382         
383         // contains the VCALENDAR any VEVENTS
384         if (! isset($vcalendar->VEVENT)) {
385             throw new Tinebase_Exception_UnexpectedValue('no vevents found');
386         }
387         
388         // update a provided record or create a new one
389         if ($_record instanceof Calendar_Model_Event) {
390             $event = $_record;
391         } else {
392             $event = new Calendar_Model_Event(null, false);
393         }
394         
395         if (isset($vcalendar->METHOD)) {
396             $this->setMethod($vcalendar->METHOD);
397         }
398         
399         $baseVevent = $this->_findMainEvent($vcalendar);
400         
401         if (! $baseVevent) {
402             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
403                 . ' No main VEVENT found');
404             
405             if (! $_record && count($vcalendar->VEVENT) > 0) {
406                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
407                     . ' Convert recur exception without existing event using first VEVENT');
408                 $this->_convertVevent($vcalendar->VEVENT[0], $event, $options);
409             }
410         } else {
411             $this->_convertVevent($baseVevent, $event, $options);
412         }
413         
414         // TODO only do this for events with rrule?
415         // if (! empty($event->rrule)) {
416         $this->_parseEventExceptions($event, $vcalendar, $baseVevent, $options);
417         
418         $event->isValid(true);
419         
420         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ 
421             . ' Event: ' . print_r($event->toArray(), true));
422         
423         return $event;
424     }
425     
426     /**
427      * find the main event - the main event has no RECURRENCE-ID
428      * 
429      * @param \Sabre\VObject\Component\VCalendar $vcalendar
430      * @return \Sabre\VObject\Component\VCalendar | null
431      */
432     protected function _findMainEvent(\Sabre\VObject\Component\VCalendar $vcalendar)
433     {
434         foreach ($vcalendar->VEVENT as $vevent) {
435             if (! isset($vevent->{'RECURRENCE-ID'})) {
436                 return $vevent;
437             }
438         }
439         
440         return null;
441     }
442     
443     /**
444      * parse event exceptions and add them to Tine 2.0 event record
445      * 
446      * @param  Calendar_Model_Event                $event
447      * @param  \Sabre\VObject\Component\VCalendar  $vcalendar
448      * @param  \Sabre\VObject\Component\VCalendar  $baseVevent
449      * @param  array                               $options
450      */
451     protected function _parseEventExceptions(Calendar_Model_Event $event, \Sabre\VObject\Component\VCalendar $vcalendar, $baseVevent = null, $options = array())
452     {
453         if (! $event->exdate instanceof Tinebase_Record_RecordSet) {
454             $event->exdate = new Tinebase_Record_RecordSet('Calendar_Model_Event');
455         }
456         $recurExceptions =  $event->exdate->filter('is_deleted', false);
457         
458         foreach ($vcalendar->VEVENT as $vevent) {
459             if (isset($vevent->{'RECURRENCE-ID'}) && $event->uid == $vevent->UID) {
460                 $recurException = $this->_getRecurException($recurExceptions, $vevent);
461                 
462                 // initialize attendee with attendee from base events for new exceptions
463                 // this way we can keep attendee extra values like groupmember type
464                 // attendees which do not attend to the new exception will be removed in _convertVevent
465                 if (! $recurException->attendee instanceof Tinebase_Record_RecordSet) {
466                     $recurException->attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender');
467                     foreach ($event->attendee as $attendee) {
468                         $recurException->attendee->addRecord(new Calendar_Model_Attender(array(
469                             'user_id'   => $attendee->user_id,
470                             'user_type' => $attendee->user_type,
471                             'role'      => $attendee->role,
472                             'status'    => $attendee->status
473                         )));
474                     }
475                 }
476                 
477                 // initialize attachments from base event as clients may skip parameters like
478                 // name and contentytpe and we can't backward relove them from managedId
479                 if ($event->attachments instanceof Tinebase_Record_RecordSet && 
480                         ! $recurException->attachments instanceof Tinebase_Record_RecordSet) {
481                     $recurException->attachments = new Tinebase_Record_RecordSet('Tinebase_Model_Tree_Node');
482                     foreach ($event->attachments as $attachment) {
483                         $recurException->attachments->addRecord(new Tinebase_Model_Tree_Node(array(
484                             'name'         => $attachment->name,
485                             'type'         => Tinebase_Model_Tree_Node::TYPE_FILE,
486                             'contenttype'  => $attachment->contenttype,
487                             'hash'         => $attachment->hash,
488                         ), true));
489                     }
490                 }
491                 
492                 if ($baseVevent) {
493                     $this->_adaptBaseEventProperties($vevent, $baseVevent);
494                 }
495                 
496                 $this->_convertVevent($vevent, $recurException, $options);
497                 
498                 if (! $recurException->getId()) {
499                     $event->exdate->addRecord($recurException);
500                 }
501             }
502         }
503     }
504     
505     /**
506      * adapt X-MOZ-LASTACK / X-MOZ-SNOOZE-TIME from base vevent
507      * 
508      * @see 0009396: alarm_ack_time and alarm_snooze_time are not updated
509      */
510     protected function _adaptBaseEventProperties($vevent, $baseVevent)
511     {
512         $propertiesToAdapt = array('X-MOZ-LASTACK', 'X-MOZ-SNOOZE-TIME');
513         
514         foreach ($propertiesToAdapt as $property) {
515             if (isset($baseVevent->{$property})) {
516                 $vevent->{$property} = $baseVevent->{$property};
517             }
518         }
519     }
520     
521     /**
522      * template method
523      * 
524      * implement if client has support for sending attachments
525      * 
526      * @param Calendar_Model_Event          $event
527      * @param Tinebase_Record_RecordSet     $attachments
528      */
529     protected function _manageAttachmentsFromClient($event, $attachments) {}
530     
531     /**
532      * convert VCALENDAR to Tinebase_Record_RecordSet of Calendar_Model_Event
533      * 
534      * @param  mixed  $blob  the vcalendar to parse
535      * @param  array  $options
536      * @return Tinebase_Record_RecordSet
537      */
538     public function toTine20RecordSet($blob, $options = array())
539     {
540         $vcalendar = self::getVObject($blob);
541         
542         $result = new Tinebase_Record_RecordSet('Calendar_Model_Event');
543         
544         foreach ($vcalendar->VEVENT as $vevent) {
545             if (! isset($vevent->{'RECURRENCE-ID'})) {
546                 $event = new Calendar_Model_Event();
547                 $this->_convertVevent($vevent, $event, $options);
548                 if (! empty($event->rrule)) {
549                     $this->_parseEventExceptions($event, $vcalendar, $options);
550                 }
551                 $result->addRecord($event);
552             }
553         }
554         
555         return $result;
556     }
557     
558     /**
559      * get METHOD of current VCALENDAR or supplied blob
560      * 
561      * @param  string  $blob
562      * @return string|NULL
563      */
564     public function getMethod($blob = NULL)
565     {
566         if ($this->_method) {
567             return $this->_method;
568         }
569         
570         if ($blob !== NULL) {
571             $vcalendar = self::getVObject($blob);
572             return $vcalendar->METHOD;
573         }
574         
575         return null;
576     }
577
578     /**
579      * find a matching exdate or return an empty event record
580      * 
581      * @param  Tinebase_Record_RecordSet        $oldExdates
582      * @param  \Sabre\VObject\Component\VEvent  $vevent
583      * @return Calendar_Model_Event
584      */
585     protected function _getRecurException(Tinebase_Record_RecordSet $oldExdates,Sabre\VObject\Component\VEvent $vevent)
586     {
587         $exDate = clone $vevent->{'RECURRENCE-ID'}->getDateTime();
588         $exDate->setTimeZone(new DateTimeZone('UTC'));
589         $exDateString = $exDate->format('Y-m-d H:i:s');
590         
591         foreach ($oldExdates as $id => $oldExdate) {
592             if ($exDateString == substr((string) $oldExdate->recurid, -19)) {
593                 return $oldExdate;
594             }
595         }
596         
597         return new Calendar_Model_Event();
598     }
599     
600     /**
601      * get attendee array for given contact
602      * 
603      * @param  \Sabre\VObject\Property\ICalendar\CalAddress  $calAddress  the attendee row from the vevent object
604      * @return array
605      */
606     protected function _getAttendee(\Sabre\VObject\Property\ICalendar\CalAddress $calAddress)
607     {
608         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) 
609             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' attendee ' . $calAddress->serialize());
610         
611         if (isset($calAddress['CUTYPE']) && in_array($calAddress['CUTYPE']->getValue(), array('INDIVIDUAL', Calendar_Model_Attender::USERTYPE_GROUP, Calendar_Model_Attender::USERTYPE_RESOURCE))) {
612             $type = $calAddress['CUTYPE']->getValue() == 'INDIVIDUAL' ? Calendar_Model_Attender::USERTYPE_USER : $calAddress['CUTYPE']->getValue();
613         } else {
614             $type = Calendar_Model_Attender::USERTYPE_USER;
615         }
616         
617         if (isset($calAddress['ROLE']) && in_array($calAddress['ROLE']->getValue(), array(Calendar_Model_Attender::ROLE_OPTIONAL, Calendar_Model_Attender::ROLE_REQUIRED))) {
618             $role = $calAddress['ROLE']->getValue();
619         } else {
620             $role = Calendar_Model_Attender::ROLE_REQUIRED;
621         }
622         
623         if (isset($calAddress['PARTSTAT']) && in_array($calAddress['PARTSTAT']->getValue(), array(
624             Calendar_Model_Attender::STATUS_ACCEPTED,
625             Calendar_Model_Attender::STATUS_DECLINED,
626             Calendar_Model_Attender::STATUS_NEEDSACTION,
627             Calendar_Model_Attender::STATUS_TENTATIVE
628         ))) {
629             $status = $calAddress['PARTSTAT']->getValue();
630         } else {
631             $status = Calendar_Model_Attender::STATUS_NEEDSACTION;
632         }
633         
634         if (!empty($calAddress['EMAIL'])) {
635             $email = $calAddress['EMAIL']->getValue();
636         } else {
637             if (! preg_match('/(?P<protocol>mailto:|urn:uuid:)(?P<email>.*)/i', $calAddress->getValue(), $matches)) {
638                 if (preg_match(Tinebase_Mail::EMAIL_ADDRESS_REGEXP, $calAddress->getValue())) {
639                     $email = $calAddress->getValue();
640                 } else {
641                     if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) 
642                         Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' invalid attendee provided: ' . $calAddress->getValue());
643                     return null;
644                 }
645             } else {
646                 $email = $matches['email'];
647             }
648         }
649         
650         $fullName = isset($calAddress['CN']) ? $calAddress['CN']->getValue() : $email;
651         
652         if (preg_match('/(?P<firstName>\S*) (?P<lastNameName>\S*)/', $fullName, $matches)) {
653             $firstName = $matches['firstName'];
654             $lastName  = $matches['lastNameName'];
655         } else {
656             $firstName = null;
657             $lastName  = $fullName;
658         }
659
660         $attendee = array(
661             'userType'  => $type,
662             'firstName' => $firstName,
663             'lastName'  => $lastName,
664             'partStat'  => $status,
665             'role'      => $role,
666             'email'     => $email
667         );
668         
669         return $attendee;
670     }
671     
672     /**
673      * parse VEVENT part of VCALENDAR
674      * 
675      * @param  \Sabre\VObject\Component\VEvent  $vevent  the VEVENT to parse
676      * @param  Calendar_Model_Event             $event   the Tine 2.0 event to update
677      * @param  array                            $options
678      */
679     protected function _convertVevent(\Sabre\VObject\Component\VEvent $vevent, Calendar_Model_Event $event, $options)
680     {
681         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE))
682             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' vevent ' . $vevent->serialize());
683         
684         $newAttendees = array();
685         $shortenedFields = array();
686         $attachments = new Tinebase_Record_RecordSet('Tinebase_Model_Tree_Node');
687         $event->alarms = new Tinebase_Record_RecordSet('Tinebase_Model_Alarm');
688         $skipFieldsIfOnlyBasicData = array('ATTENDEE', 'UID', 'ORGANIZER', 'VALARM', 'ATTACH', 'CATEGORIES');
689         
690         foreach ($vevent->children() as $property) {
691             if (isset($this->_options['onlyBasicData'])
692                 && $this->_options['onlyBasicData']
693                 && in_array((string) $property->name, $skipFieldsIfOnlyBasicData))
694             {
695                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG))
696                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Skipping '
697                             . $property->name . ' (using option onlyBasicData)');
698                 continue;
699             }
700             
701             switch ($property->name) {
702                 case 'CREATED':
703                 case 'DTSTAMP':
704                     if (! isset($options[self::OPTION_USE_SERVER_MODLOG]) || $options[self::OPTION_USE_SERVER_MODLOG] !== true) {
705                         $event->{$property->name == 'CREATED' ? 'creation_time' : 'last_modified_time'} = $this->_convertToTinebaseDateTime($property);
706                     }
707                     break;
708                     
709                 case 'LAST-MODIFIED':
710                     $event->last_modified_time = new Tinebase_DateTime($property->getValue());
711                     break;
712                 
713                 case 'ATTENDEE':
714                     $newAttendee = $this->_getAttendee($property);
715                     if ($newAttendee) {
716                         $newAttendees[] = $newAttendee;
717                     }
718                     break;
719                     
720                 case 'CLASS':
721                     if (in_array($property->getValue(), array(Calendar_Model_Event::CLASS_PRIVATE, Calendar_Model_Event::CLASS_PUBLIC))) {
722                         $event->class = $property->getValue();
723                     } else {
724                         $event->class = Calendar_Model_Event::CLASS_PUBLIC;
725                     }
726                     
727                     break;
728
729                 case 'STATUS':
730                     if (in_array($property->getValue(), array(Calendar_Model_Event::STATUS_CONFIRMED, Calendar_Model_Event::STATUS_TENTATIVE, Calendar_Model_Event::STATUS_CANCELED))) {
731                         $event->status = $property->getValue();
732                     } else {
733                         $event->status = Calendar_Model_Event::STATUS_CONFIRMED;
734                     }
735                     break;
736                     
737                 case 'DTEND':
738                     
739                     if (isset($property['VALUE']) && strtoupper($property['VALUE']) == 'DATE') {
740                         // all day event
741                         $event->is_all_day_event = true;
742                         $dtend = $this->_convertToTinebaseDateTime($property, TRUE);
743                         
744                         // whole day events ends at 23:59:59 in Tine 2.0 but 00:00 the next day in vcalendar
745                         $dtend->subSecond(1);
746                     } else {
747                         $event->is_all_day_event = false;
748                         $dtend = $this->_convertToTinebaseDateTime($property);
749                     }
750                     
751                     $event->dtend = $dtend;
752                     
753                     break;
754                     
755                 case 'DTSTART':
756                     if (isset($property['VALUE']) && strtoupper($property['VALUE']) == 'DATE') {
757                         // all day event
758                         $event->is_all_day_event = true;
759                         $dtstart = $this->_convertToTinebaseDateTime($property, TRUE);
760                     } else {
761                         $event->is_all_day_event = false;
762                         $dtstart = $this->_convertToTinebaseDateTime($property);
763                     }
764                     
765                     $event->originator_tz = $dtstart->getTimezone()->getName();
766                     $event->dtstart = $dtstart;
767                     
768                     break;
769                     
770                 case 'SEQUENCE':
771                     if (! isset($options[self::OPTION_USE_SERVER_MODLOG]) || $options[self::OPTION_USE_SERVER_MODLOG] !== true) {
772                         $event->seq = $property->getValue();
773                     }
774                     // iMIP only
775                     $event->external_seq = $property->getValue();
776                     break;
777                     
778                 case 'DESCRIPTION':
779                 case 'LOCATION':
780                 case 'SUMMARY':
781                     $key = strtolower($property->name);
782                     $value = $property->getValue();
783                     switch ($key) {
784                         case 'summary':
785                         case 'location':
786                             if (strlen($value) > 255) {
787                                 $shortenedFields[$key] = $value;
788                                 $endPos = strpos($value, "\n") !== false && strpos($value, "\n") < 255 
789                                     ? strpos($value, "\n") 
790                                     : 255;
791                                 if (extension_loaded('mbstring')) {
792                                     $value = mb_substr($value, 0, $endPos, 'UTF-8');
793                                 } else {
794                                     $value = Tinebase_Core::filterInputForDatabase(substr($value, 0, $endPos));
795                                 }
796                             }
797                             break;
798                     }
799                     $event->$key = $value;
800                     
801                     break;
802                     
803                 case 'ORGANIZER':
804                     $email = null;
805                     
806                     if (!empty($property['EMAIL'])) {
807                         $email = $property['EMAIL'];
808                     } elseif (preg_match('/mailto:(?P<email>.*)/i', $property->getValue(), $matches)) {
809                         $email = $matches['email'];
810                     }
811                     
812                     if ($email !== null) {
813                         // it's not possible to change the organizer by spec
814                         if (empty($event->organizer)) {
815                             $name = isset($property['CN']) ? $property['CN']->getValue() : $email;
816                             $contact = Calendar_Model_Attender::resolveEmailToContact(array(
817                                 'email'     => $email,
818                                 'lastName'  => $name,
819                             ));
820                         
821                             $event->organizer = $contact->getId();
822                         }
823                         
824                         // Lightning attaches organizer ATTENDEE properties to ORGANIZER property and does not add an ATTENDEE for the organizer
825                         if (isset($property['PARTSTAT'])) {
826                             $newAttendees[] = $this->_getAttendee($property);
827                         }
828                     }
829                     
830                     break;
831
832                 case 'RECURRENCE-ID':
833                     // original start of the event
834                     $event->recurid = $this->_convertToTinebaseDateTime($property);
835                     
836                     // convert recurrence id to utc
837                     $event->recurid->setTimezone('UTC');
838                     
839                     break;
840                     
841                 case 'RRULE':
842                     $rruleString = $property->getValue();
843                     
844                     // convert date format
845                     $rruleString = preg_replace_callback('/UNTIL=([\dTZ]+)(?=;?)/', function($matches) {
846                         if (strlen($matches[1]) < 10) {
847                             $dtUntil = date_create($matches[1], new DateTimeZone ((string) Tinebase_Core::getUserTimezone()));
848                             $dtUntil->setTimezone(new DateTimeZone('UTC'));
849                         } else {
850                             $dtUntil = date_create($matches[1]);
851                         }
852                         
853                         return 'UNTIL=' . $dtUntil->format(Tinebase_Record_Abstract::ISO8601LONG);
854                     }, $rruleString);
855
856                     // remove additional days from BYMONTHDAY property (BYMONTHDAY=11,15 => BYMONTHDAY=11)
857                     $rruleString = preg_replace('/(BYMONTHDAY=)([\d]+),([,\d]+)/', '$1$2', $rruleString);
858                     
859                     $event->rrule = $rruleString;
860                     
861                     // process exceptions
862                     if (isset($vevent->EXDATE)) {
863                         $exdates = new Tinebase_Record_RecordSet('Calendar_Model_Event');
864                         
865                         foreach ($vevent->EXDATE as $exdate) {
866                             foreach ($exdate->getDateTimes() as $exception) {
867                                 if (isset($exdate['VALUE']) && strtoupper($exdate['VALUE']) == 'DATE') {
868                                     $recurid = new Tinebase_DateTime($exception->format(Tinebase_Record_Abstract::ISO8601LONG), (string) Tinebase_Core::getUserTimezone());
869                                 } else {
870                                     $recurid = new Tinebase_DateTime($exception->format(Tinebase_Record_Abstract::ISO8601LONG), $exception->getTimezone());
871                                 }
872                                 $recurid->setTimezone(new DateTimeZone('UTC'));
873                                 
874                                 $eventException = new Calendar_Model_Event(array(
875                                     'recurid'    => $recurid,
876                                     'is_deleted' => true
877                                 ));
878                         
879                                 $exdates->addRecord($eventException);
880                             }
881                         }
882                     
883                         $event->exdate = $exdates;
884                     }
885                     
886                     break;
887                     
888                 case 'TRANSP':
889                     if (in_array($property->getValue(), array(Calendar_Model_Event::TRANSP_OPAQUE, Calendar_Model_Event::TRANSP_TRANSP))) {
890                         $event->transp = $property->getValue();
891                     } else {
892                         $event->transp = Calendar_Model_Event::TRANSP_TRANSP;
893                     }
894                     
895                     break;
896                     
897                 case 'UID':
898                     // it's not possible to change the uid by spec
899                     if (!empty($event->uid)) {
900                         continue;
901                     }
902                     
903                     $event->uid = $property->getValue();
904                 
905                     break;
906                     
907                 case 'VALARM':
908                     $this->_parseAlarm($event, $property, $vevent);
909                     break;
910                     
911                 case 'CATEGORIES':
912                     $tags = Tinebase_Model_Tag::resolveTagNameToTag($property->getParts(), 'Calendar');
913                     if (! isset($event->tags)) {
914                         $event->tags = $tags;
915                     } else {
916                         $event->tags->merge($tags);
917                     }
918                     break;
919                     
920                 case 'ATTACH':
921                     $name = (string) $property['FILENAME'];
922                     $managedId = (string) $property['MANAGED-ID'];
923                     $value = (string) $property['VALUE'];
924                     $attachment = NULL;
925                     $readFromURL = false;
926                     $url = '';
927                     
928                     if (Tinebase_Core::isLogLevel(Zend_Log::INFO))
929                         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' attachment found: ' . $name . ' ' . $managedId);
930                     
931                     if ($managedId) {
932                         $attachment = $event->attachments instanceof Tinebase_Record_RecordSet ?
933                             $event->attachments->filter('hash', $property['MANAGED-ID'])->getFirstRecord() :
934                             NULL;
935                         
936                         // NOTE: we might miss a attachment here for the following reasons
937                         //       1. client reuses a managed id (we are server):
938                         //          We havn't observerd this yet. iCal client reuse manged id's
939                         //          from base events in exceptions but this is covered as we 
940                         //          initialize new exceptions with base event attachments
941                         //          
942                         //          When a client reuses a managed id it's not clear yet if
943                         //          this managed id needs to be in the same series/calendar/server
944                         //
945                         //          As we use the object hash the managed id might be used in the 
946                         //          same files with different names. We need to evaluate the name
947                         //          (if attached) in this case as well.
948                         //       
949                         //       2. server send his managed id (we are client)
950                         //          * we need to download the attachment (here?)
951                         //          * we need to have a mapping externalid / internalid (where?)
952                         
953                         if (! $attachment) {
954                             $readFromURL = true;
955                             $url = $property->getValue();
956                         } else {
957                             $attachments->addRecord($attachment);
958                         }
959                     } elseif('URI' === $value) {
960                         /*
961                          * ATTACH;VALUE=URI:https://server.com/calendars/__uids__/0AA0
962  3A3B-F7B6-459A-AB3E-4726E53637D0/dropbox/4971F93F-8657-412B-841A-A0FD913
963  9CD61.dropbox/Canada.png
964                          */
965                         $url = $property->getValue();
966                         $urlParts = parse_url($url);
967                         $host = $urlParts['host'];
968                         $name = pathinfo($urlParts['path'], PATHINFO_BASENAME);
969
970                         // iCal 10.7 places URI before uploading
971                         if (parse_url(Tinebase_Core::getHostname(), PHP_URL_HOST) != $host) {
972                             $readFromURL = true;
973                         }
974                     }
975                     // base64
976                     else {
977                         // @TODO: implement (check if add / update / update is needed)
978                         if (Tinebase_Core::isLogLevel(Zend_Log::WARN))
979                                 Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' attachment found that could not be imported due to missing managed id');
980                     }
981                     
982                     if ($readFromURL) {
983                         if (preg_match('#^(https?://)(.*)$#', str_replace(array("\n","\r"), '', $url), $matches)) {
984                             // we are client and found an external hosted attachment that we need to import
985                             $userCredentialCache = Tinebase_Core::getUserCredentialCache();
986                             $url = $matches[1] . $userCredentialCache->username . ':' . $userCredentialCache->password . '@' . $matches[2];
987                             $attachmentInfo = $matches[1] . $matches[2]. ' ' . $name . ' ' . $managedId;
988                             if (Tinebase_Helper::urlExists($url)) {
989                                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO))
990                                     Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
991                                             . ' Downloading attachment: ' . $attachmentInfo);
992                                 
993                                 $stream = fopen($url, 'r');
994                                 $attachment = new Tinebase_Model_Tree_Node(array(
995                                     'name'         => rawurldecode($name),
996                                     'type'         => Tinebase_Model_Tree_Node::TYPE_FILE,
997                                     'contenttype'  => (string) $property['FMTTYPE'],
998                                     'tempFile'     => $stream,
999                                     ), true);
1000                                 $attachments->addRecord($attachment);
1001                             } else {
1002                                 if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ 
1003                                     . ' Url not found (got 404): ' . $attachmentInfo . ' - Skipping attachment');
1004                             }
1005                         } else {
1006                             if (Tinebase_Core::isLogLevel(Zend_Log::WARN))
1007                                 Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ 
1008                                     . ' Attachment found with malformed url: ' . $url);
1009                         }
1010                     }
1011                     break;
1012                     
1013                 case 'X-MOZ-LASTACK':
1014                     $lastAck = $this->_convertToTinebaseDateTime($property);
1015                     break;
1016                     
1017                 case 'X-MOZ-SNOOZE-TIME':
1018                     $snoozeTime = $this->_convertToTinebaseDateTime($property);
1019                     break;
1020                     
1021                 default:
1022                     // thunderbird saves snooze time for recurring event occurrences in properties with names like this -
1023                     // we just assume that the event/recur series has only one snooze time 
1024                     if (preg_match('/^X-MOZ-SNOOZE-TIME-[0-9]+$/', $property->name)) {
1025                         $snoozeTime = $this->_convertToTinebaseDateTime($property);
1026                         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
1027                             . ' Found snooze time for recur occurrence: ' . $snoozeTime->toString());
1028                     }
1029                     break;
1030             }
1031         }
1032
1033         // NOTE: X-CALENDARSERVER-ACCESS overwrites CLASS
1034         if (isset($vevent->{'X-CALENDARSERVER-ACCESS'})) {
1035             $event->class = $vevent->{'X-CALENDARSERVER-ACCESS'} == 'PUBLIC' ?
1036                 Calendar_Model_Event::CLASS_PUBLIC :
1037                 Calendar_Model_Event::CLASS_PRIVATE;
1038         }
1039
1040         foreach ($shortenedFields as $key => $value) {
1041             $event->description = "--------\n$key: $value";
1042         }
1043         
1044         if (isset($lastAck)) {
1045             Calendar_Controller_Alarm::setAcknowledgeTime($event->alarms, $lastAck);
1046         }
1047         if (isset($snoozeTime)) {
1048             Calendar_Controller_Alarm::setSnoozeTime($event->alarms, $snoozeTime);
1049         }
1050         
1051         // merge old and new attendee
1052         Calendar_Model_Attender::emailsToAttendee($event, $newAttendees);
1053         
1054         if (empty($event->seq)) {
1055             $event->seq = 1;
1056         }
1057         
1058         if (empty($event->class)) {
1059             $event->class = Calendar_Model_Event::CLASS_PUBLIC;
1060         }
1061         
1062         $this->_manageAttachmentsFromClient($event, $attachments);
1063         
1064         if (empty($event->dtend)) {
1065             if (empty($event->dtstart)) {
1066                 throw new Tinebase_Exception_UnexpectedValue("Got event without dtstart and dtend");
1067             }
1068             
1069             // TODO find out duration (see TRIGGER DURATION)
1070 //             if (isset($vevent->DURATION)) {
1071 //             }
1072             if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__
1073                     . ' Got event without dtend. Assuming 30 minutes duration');
1074             $event->dtend = clone $event->dtstart;
1075             $event->dtend->addMinute(30);
1076         }
1077         
1078         $this->_manageAttachmentsFromClient($event, $attachments);
1079         
1080         // convert all datetime fields to UTC
1081         $event->setTimezone('UTC');
1082     }
1083 }