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