add optional download attachment url property to ics
[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             if (isset($this->_options['addAttachmentsURL']) && $this->_options['addAttachmentsURL']) {
333                 $vevent->add($vcalendar->createProperty('URL', $baseUrl));
334             }
335         }
336         
337         $vcalendar->add($vevent);
338     }
339     
340     /**
341      * add event attendee to VEVENT object 
342      * 
343      * @param \Sabre\VObject\Component\VEvent $vevent
344      * @param Calendar_Model_Event            $event
345      */
346     protected function _addEventAttendee(\Sabre\VObject\Component\VEvent $vevent, Calendar_Model_Event $event)
347     {
348         if (empty($event->attendee)) {
349             return;
350         }
351         
352         Calendar_Model_Attender::resolveAttendee($event->attendee, FALSE, $event);
353
354         foreach($event->attendee as $eventAttendee) {
355             $attendeeEmail = $eventAttendee->getEmail();
356             
357             $parameters = array(
358                 'CN'       => $eventAttendee->getName(),
359                 'CUTYPE'   => Calendar_Convert_Event_VCalendar_Abstract::$cutypeMap[$eventAttendee->user_type],
360                 'PARTSTAT' => $eventAttendee->status,
361                 'ROLE'     => "{$eventAttendee->role}-PARTICIPANT",
362                 'RSVP'     => 'FALSE'
363             );
364             if (strpos($attendeeEmail, '@') !== false) {
365                 $parameters['EMAIL'] = $attendeeEmail;
366             }
367             $vevent->add('ATTENDEE', (strpos($attendeeEmail, '@') !== false ? 'mailto:' : 'urn:uuid:') . $attendeeEmail, $parameters);
368         }
369     }
370
371     /**
372      * set the METHOD for the generated VCALENDAR
373      *
374      * @param  string  $_method  the method
375      */
376     public function setMethod($method)
377     {
378         $this->_method = $method;
379     }
380     
381     /**
382      * converts vcalendar to Calendar_Model_Event
383      * 
384      * @param  mixed                 $_blob    the VCALENDAR to parse
385      * @param  Calendar_Model_Event  $_record  update existing event
386      * @param  array                 $options  array of options
387      * @return Calendar_Model_Event
388      */
389     public function toTine20Model($blob, Tinebase_Record_Abstract $_record = null, $options = array())
390     {
391         $vcalendar = self::getVObject($blob);
392         
393         // contains the VCALENDAR any VEVENTS
394         if (! isset($vcalendar->VEVENT)) {
395             throw new Tinebase_Exception_UnexpectedValue('no vevents found');
396         }
397         
398         // update a provided record or create a new one
399         if ($_record instanceof Calendar_Model_Event) {
400             $event = $_record;
401         } else {
402             $event = new Calendar_Model_Event(null, false);
403         }
404         
405         if (isset($vcalendar->METHOD)) {
406             $this->setMethod($vcalendar->METHOD);
407         }
408         
409         $baseVevent = $this->_findMainEvent($vcalendar);
410         
411         if (! $baseVevent) {
412             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
413                 . ' No main VEVENT found');
414             
415             if (! $_record && count($vcalendar->VEVENT) > 0) {
416                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
417                     . ' Convert recur exception without existing event using first VEVENT');
418                 $this->_convertVevent($vcalendar->VEVENT[0], $event, $options);
419             }
420         } else {
421             $this->_convertVevent($baseVevent, $event, $options);
422         }
423         
424         $this->_parseEventExceptions($event, $vcalendar, $baseVevent, $options);
425         
426         $event->isValid(true);
427         
428         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ 
429             . ' Event: ' . print_r($event->toArray(), true));
430         
431         return $event;
432     }
433     
434     /**
435      * find the main event - the main event has no RECURRENCE-ID
436      * 
437      * @param \Sabre\VObject\Component\VCalendar $vcalendar
438      * @return \Sabre\VObject\Component\VCalendar | null
439      */
440     protected function _findMainEvent(\Sabre\VObject\Component\VCalendar $vcalendar)
441     {
442         foreach ($vcalendar->VEVENT as $vevent) {
443             if (! isset($vevent->{'RECURRENCE-ID'})) {
444                 return $vevent;
445             }
446         }
447         
448         return null;
449     }
450     
451     /**
452      * parse event exceptions and add them to Tine 2.0 event record
453      * 
454      * @param  Calendar_Model_Event                $event
455      * @param  \Sabre\VObject\Component\VCalendar  $vcalendar
456      * @param  \Sabre\VObject\Component\VCalendar  $baseVevent
457      * @param  array                               $options
458      */
459     protected function _parseEventExceptions(Calendar_Model_Event $event, \Sabre\VObject\Component\VCalendar $vcalendar, $baseVevent = null, $options = array())
460     {
461         if (! $event->exdate instanceof Tinebase_Record_RecordSet) {
462             $event->exdate = new Tinebase_Record_RecordSet('Calendar_Model_Event');
463         }
464         $recurExceptions = $event->exdate->filter('is_deleted', false);
465         
466         foreach ($vcalendar->VEVENT as $vevent) {
467             if (isset($vevent->{'RECURRENCE-ID'}) && $event->uid == $vevent->UID) {
468                 $recurException = $this->_getRecurException($recurExceptions, $vevent);
469                 
470                 // initialize attendee with attendee from base events for new exceptions
471                 // this way we can keep attendee extra values like groupmember type
472                 // attendees which do not attend to the new exception will be removed in _convertVevent
473                 if (! $recurException->attendee instanceof Tinebase_Record_RecordSet) {
474                     $recurException->attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender');
475                     foreach ($event->attendee as $attendee) {
476                         $recurException->attendee->addRecord(new Calendar_Model_Attender(array(
477                             'user_id'   => $attendee->user_id,
478                             'user_type' => $attendee->user_type,
479                             'role'      => $attendee->role,
480                             'status'    => $attendee->status
481                         )));
482                     }
483                 }
484                 
485                 // initialize attachments from base event as clients may skip parameters like
486                 // name and content type and we can't backward relove them from managedId
487                 if ($event->attachments instanceof Tinebase_Record_RecordSet && 
488                         ! $recurException->attachments instanceof Tinebase_Record_RecordSet) {
489                     $recurException->attachments = new Tinebase_Record_RecordSet('Tinebase_Model_Tree_Node');
490                     foreach ($event->attachments as $attachment) {
491                         $recurException->attachments->addRecord(new Tinebase_Model_Tree_Node(array(
492                             'name'         => $attachment->name,
493                             'type'         => Tinebase_Model_Tree_Node::TYPE_FILE,
494                             'contenttype'  => $attachment->contenttype,
495                             'hash'         => $attachment->hash,
496                         ), true));
497                     }
498                 }
499                 
500                 if ($baseVevent) {
501                     $this->_adaptBaseEventProperties($vevent, $baseVevent);
502                 }
503                 
504                 $this->_convertVevent($vevent, $recurException, $options);
505                 
506                 if (! $recurException->getId()) {
507                     $event->exdate->addRecord($recurException);
508                 }
509             }
510         }
511     }
512     
513     /**
514      * adapt X-MOZ-LASTACK / X-MOZ-SNOOZE-TIME from base vevent
515      * 
516      * @see 0009396: alarm_ack_time and alarm_snooze_time are not updated
517      */
518     protected function _adaptBaseEventProperties($vevent, $baseVevent)
519     {
520         $propertiesToAdapt = array('X-MOZ-LASTACK', 'X-MOZ-SNOOZE-TIME');
521         
522         foreach ($propertiesToAdapt as $property) {
523             if (isset($baseVevent->{$property})) {
524                 $vevent->{$property} = $baseVevent->{$property};
525             }
526         }
527     }
528     
529     /**
530      * template method
531      * 
532      * implement if client has support for sending attachments
533      * 
534      * @param Calendar_Model_Event          $event
535      * @param Tinebase_Record_RecordSet     $attachments
536      */
537     protected function _manageAttachmentsFromClient($event, $attachments) {}
538     
539     /**
540      * convert VCALENDAR to Tinebase_Record_RecordSet of Calendar_Model_Event
541      * 
542      * @param  mixed  $blob  the vcalendar to parse
543      * @param  array  $options
544      * @return Tinebase_Record_RecordSet
545      */
546     public function toTine20RecordSet($blob, $options = array())
547     {
548         $vcalendar = self::getVObject($blob);
549         
550         $result = new Tinebase_Record_RecordSet('Calendar_Model_Event');
551         
552         foreach ($vcalendar->VEVENT as $vevent) {
553             if (! isset($vevent->{'RECURRENCE-ID'})) {
554                 $event = new Calendar_Model_Event();
555                 $this->_convertVevent($vevent, $event, $options);
556                 if (! empty($event->rrule)) {
557                     $this->_parseEventExceptions($event, $vcalendar, $options);
558                 }
559                 $result->addRecord($event);
560             }
561         }
562         
563         return $result;
564     }
565     
566     /**
567      * get METHOD of current VCALENDAR or supplied blob
568      * 
569      * @param  string  $blob
570      * @return string|NULL
571      */
572     public function getMethod($blob = NULL)
573     {
574         if ($this->_method) {
575             return $this->_method;
576         }
577         
578         if ($blob !== NULL) {
579             $vcalendar = self::getVObject($blob);
580             return $vcalendar->METHOD;
581         }
582         
583         return null;
584     }
585
586     /**
587      * find a matching exdate or return an empty event record
588      * 
589      * @param  Tinebase_Record_RecordSet        $oldExdates
590      * @param  \Sabre\VObject\Component\VEvent  $vevent
591      * @return Calendar_Model_Event
592      */
593     protected function _getRecurException(Tinebase_Record_RecordSet $oldExdates,Sabre\VObject\Component\VEvent $vevent)
594     {
595         // we need to use the user timezone here if this is a DATE (like this: RECURRENCE-ID;VALUE=DATE:20140429)
596         $exDate = $this->_convertToTinebaseDateTime($vevent->{'RECURRENCE-ID'});
597         $exDate->setTimezone('UTC');
598         $exDateString = $exDate->format('Y-m-d H:i:s');
599
600         foreach ($oldExdates as $id => $oldExdate) {
601             if ($exDateString == substr((string) $oldExdate->recurid, -19)) {
602                 return $oldExdate;
603             }
604         }
605         
606         return new Calendar_Model_Event();
607     }
608     
609     /**
610      * get attendee array for given contact
611      * 
612      * @param  \Sabre\VObject\Property\ICalendar\CalAddress  $calAddress  the attendee row from the vevent object
613      * @return array
614      */
615     protected function _getAttendee(\Sabre\VObject\Property\ICalendar\CalAddress $calAddress)
616     {
617         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) 
618             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' attendee ' . $calAddress->serialize());
619         
620         if (isset($calAddress['CUTYPE']) && in_array($calAddress['CUTYPE']->getValue(), array('INDIVIDUAL', Calendar_Model_Attender::USERTYPE_GROUP, Calendar_Model_Attender::USERTYPE_RESOURCE))) {
621             $type = $calAddress['CUTYPE']->getValue() == 'INDIVIDUAL' ? Calendar_Model_Attender::USERTYPE_USER : $calAddress['CUTYPE']->getValue();
622         } else {
623             $type = Calendar_Model_Attender::USERTYPE_USER;
624         }
625         
626         if (isset($calAddress['ROLE']) && in_array($calAddress['ROLE']->getValue(), array(Calendar_Model_Attender::ROLE_OPTIONAL, Calendar_Model_Attender::ROLE_REQUIRED))) {
627             $role = $calAddress['ROLE']->getValue();
628         } else {
629             $role = Calendar_Model_Attender::ROLE_REQUIRED;
630         }
631         
632         if (isset($calAddress['PARTSTAT']) && in_array($calAddress['PARTSTAT']->getValue(), array(
633             Calendar_Model_Attender::STATUS_ACCEPTED,
634             Calendar_Model_Attender::STATUS_DECLINED,
635             Calendar_Model_Attender::STATUS_NEEDSACTION,
636             Calendar_Model_Attender::STATUS_TENTATIVE
637         ))) {
638             $status = $calAddress['PARTSTAT']->getValue();
639         } else {
640             $status = Calendar_Model_Attender::STATUS_NEEDSACTION;
641         }
642         
643         if (!empty($calAddress['EMAIL'])) {
644             $email = $calAddress['EMAIL']->getValue();
645         } else {
646             if (! preg_match('/(?P<protocol>mailto:|urn:uuid:)(?P<email>.*)/i', $calAddress->getValue(), $matches)) {
647                 if (preg_match(Tinebase_Mail::EMAIL_ADDRESS_REGEXP, $calAddress->getValue())) {
648                     $email = $calAddress->getValue();
649                 } else {
650                     if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) 
651                         Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' invalid attendee provided: ' . $calAddress->getValue());
652                     return null;
653                 }
654             } else {
655                 $email = $matches['email'];
656             }
657         }
658         
659         $fullName = isset($calAddress['CN']) ? $calAddress['CN']->getValue() : $email;
660         
661         if (preg_match('/(?P<firstName>\S*) (?P<lastNameName>\S*)/', $fullName, $matches)) {
662             $firstName = $matches['firstName'];
663             $lastName  = $matches['lastNameName'];
664         } else {
665             $firstName = null;
666             $lastName  = $fullName;
667         }
668
669         $attendee = array(
670             'userType'  => $type,
671             'firstName' => $firstName,
672             'lastName'  => $lastName,
673             'partStat'  => $status,
674             'role'      => $role,
675             'email'     => $email
676         );
677         
678         return $attendee;
679     }
680     
681     /**
682      * parse VEVENT part of VCALENDAR
683      * 
684      * @param  \Sabre\VObject\Component\VEvent  $vevent  the VEVENT to parse
685      * @param  Calendar_Model_Event             $event   the Tine 2.0 event to update
686      * @param  array                            $options
687      */
688     protected function _convertVevent(\Sabre\VObject\Component\VEvent $vevent, Calendar_Model_Event $event, $options)
689     {
690         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE))
691             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' vevent ' . $vevent->serialize());
692         
693         $newAttendees = array();
694         $attachments = new Tinebase_Record_RecordSet('Tinebase_Model_Tree_Node');
695         $event->alarms = new Tinebase_Record_RecordSet('Tinebase_Model_Alarm');
696         $skipFieldsIfOnlyBasicData = array('ATTENDEE', 'UID', 'ORGANIZER', 'VALARM', 'ATTACH', 'CATEGORIES');
697         
698         foreach ($vevent->children() as $property) {
699             if (isset($this->_options['onlyBasicData'])
700                 && $this->_options['onlyBasicData']
701                 && in_array((string) $property->name, $skipFieldsIfOnlyBasicData))
702             {
703                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG))
704                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Skipping '
705                             . $property->name . ' (using option onlyBasicData)');
706                 continue;
707             }
708             
709             switch ($property->name) {
710                 case 'CREATED':
711                 case 'DTSTAMP':
712                     if (! isset($options[self::OPTION_USE_SERVER_MODLOG]) || $options[self::OPTION_USE_SERVER_MODLOG] !== true) {
713                         $event->{$property->name == 'CREATED' ? 'creation_time' : 'last_modified_time'} = $this->_convertToTinebaseDateTime($property);
714                     }
715                     break;
716                     
717                 case 'LAST-MODIFIED':
718                     $event->last_modified_time = new Tinebase_DateTime($property->getValue());
719                     break;
720                 
721                 case 'ATTENDEE':
722                     $newAttendee = $this->_getAttendee($property);
723                     if ($newAttendee) {
724                         $newAttendees[] = $newAttendee;
725                     }
726                     break;
727                     
728                 case 'CLASS':
729                     if (in_array($property->getValue(), array(Calendar_Model_Event::CLASS_PRIVATE, Calendar_Model_Event::CLASS_PUBLIC))) {
730                         $event->class = $property->getValue();
731                     } else {
732                         $event->class = Calendar_Model_Event::CLASS_PUBLIC;
733                     }
734                     
735                     break;
736
737                 case 'STATUS':
738                     if (in_array($property->getValue(), array(Calendar_Model_Event::STATUS_CONFIRMED, Calendar_Model_Event::STATUS_TENTATIVE, Calendar_Model_Event::STATUS_CANCELED))) {
739                         $event->status = $property->getValue();
740                     } else if ($property->getValue() == 'CANCELLED'){
741                         $event->status = Calendar_Model_Event::STATUS_CANCELED;
742                     } else {
743                         $event->status = Calendar_Model_Event::STATUS_CONFIRMED;
744                     }
745                     break;
746                     
747                 case 'DTEND':
748                     
749                     if (isset($property['VALUE']) && strtoupper($property['VALUE']) == 'DATE') {
750                         // all day event
751                         $event->is_all_day_event = true;
752                         $dtend = $this->_convertToTinebaseDateTime($property, TRUE);
753                         
754                         // whole day events ends at 23:59:59 in Tine 2.0 but 00:00 the next day in vcalendar
755                         $dtend->subSecond(1);
756                     } else {
757                         $event->is_all_day_event = false;
758                         $dtend = $this->_convertToTinebaseDateTime($property);
759                     }
760                     
761                     $event->dtend = $dtend;
762                     
763                     break;
764                     
765                 case 'DTSTART':
766                     if (isset($property['VALUE']) && strtoupper($property['VALUE']) == 'DATE') {
767                         // all day event
768                         $event->is_all_day_event = true;
769                         $dtstart = $this->_convertToTinebaseDateTime($property, TRUE);
770                     } else {
771                         $event->is_all_day_event = false;
772                         $dtstart = $this->_convertToTinebaseDateTime($property);
773                     }
774                     
775                     $event->originator_tz = $dtstart->getTimezone()->getName();
776                     $event->dtstart = $dtstart;
777                     
778                     break;
779                     
780                 case 'SEQUENCE':
781                     if (! isset($options[self::OPTION_USE_SERVER_MODLOG]) || $options[self::OPTION_USE_SERVER_MODLOG] !== true) {
782                         $event->seq = $property->getValue();
783                     }
784                     // iMIP only
785                     $event->external_seq = $property->getValue();
786                     break;
787                     
788                 case 'DESCRIPTION':
789                 case 'LOCATION':
790                 case 'SUMMARY':
791                     $key = strtolower($property->name);
792                     $value = $property->getValue();
793                     if (in_array($key, array('location', 'summary')) && extension_loaded('mbstring')) {
794                         $value = mb_substr($value, 0, 1024, 'UTF-8');
795                     }
796
797                     $event->$key = $value;
798                     break;
799                     
800                 case 'ORGANIZER':
801                     $email = null;
802                     
803                     if (!empty($property['EMAIL'])) {
804                         $email = $property['EMAIL'];
805                     } elseif (preg_match('/mailto:(?P<email>.*)/i', $property->getValue(), $matches)) {
806                         $email = $matches['email'];
807                     }
808                     
809                     if ($email !== null) {
810                         // it's not possible to change the organizer by spec
811                         if (empty($event->organizer)) {
812                             $name = isset($property['CN']) ? $property['CN']->getValue() : $email;
813                             $contact = Calendar_Model_Attender::resolveEmailToContact(array(
814                                 'email'     => $email,
815                                 'lastName'  => $name,
816                             ));
817                         
818                             $event->organizer = $contact->getId();
819                         }
820                         
821                         // Lightning attaches organizer ATTENDEE properties to ORGANIZER property and does not add an ATTENDEE for the organizer
822                         if (isset($property['PARTSTAT'])) {
823                             $newAttendees[] = $this->_getAttendee($property);
824                         }
825                     }
826                     
827                     break;
828
829                 case 'RECURRENCE-ID':
830                     // original start of the event
831                     $event->recurid = $this->_convertToTinebaseDateTime($property);
832                     
833                     // convert recurrence id to utc
834                     $event->recurid->setTimezone('UTC');
835                     
836                     break;
837                     
838                 case 'RRULE':
839                     $rruleString = $property->getValue();
840                     
841                     // convert date format
842                     $rruleString = preg_replace_callback('/UNTIL=([\dTZ]+)(?=;?)/', function($matches) {
843                         $dtUntil = Calendar_Convert_Event_VCalendar_Abstract::getUTCDateFromStringInUsertime($matches[1]);
844                         return 'UNTIL=' . $dtUntil->format(Tinebase_Record_Abstract::ISO8601LONG);
845                     }, $rruleString);
846
847                     // remove additional days from BYMONTHDAY property (BYMONTHDAY=11,15 => BYMONTHDAY=11)
848                     $rruleString = preg_replace('/(BYMONTHDAY=)([\d]+),([,\d]+)/', '$1$2', $rruleString);
849                     
850                     $event->rrule = $rruleString;
851                     
852                     // process exceptions
853                     if (isset($vevent->EXDATE)) {
854                         $exdates = new Tinebase_Record_RecordSet('Calendar_Model_Event');
855                         
856                         foreach ($vevent->EXDATE as $exdate) {
857                             foreach ($exdate->getDateTimes() as $exception) {
858                                 if (isset($exdate['VALUE']) && strtoupper($exdate['VALUE']) == 'DATE') {
859                                     $recurid = new Tinebase_DateTime($exception->format(Tinebase_Record_Abstract::ISO8601LONG), (string) Tinebase_Core::getUserTimezone());
860                                 } else {
861                                     $recurid = new Tinebase_DateTime($exception->format(Tinebase_Record_Abstract::ISO8601LONG), $exception->getTimezone());
862                                 }
863                                 $recurid->setTimezone(new DateTimeZone('UTC'));
864                                 
865                                 $eventException = new Calendar_Model_Event(array(
866                                     'recurid'    => $recurid,
867                                     'is_deleted' => true
868                                 ));
869                         
870                                 $exdates->addRecord($eventException);
871                             }
872                         }
873                     
874                         $event->exdate = $exdates;
875                     }
876                     
877                     break;
878                     
879                 case 'TRANSP':
880                     if (in_array($property->getValue(), array(Calendar_Model_Event::TRANSP_OPAQUE, Calendar_Model_Event::TRANSP_TRANSP))) {
881                         $event->transp = $property->getValue();
882                     } else {
883                         $event->transp = Calendar_Model_Event::TRANSP_TRANSP;
884                     }
885                     
886                     break;
887                     
888                 case 'UID':
889                     // it's not possible to change the uid by spec
890                     if (!empty($event->uid)) {
891                         continue;
892                     }
893                     
894                     $event->uid = $property->getValue();
895                 
896                     break;
897                     
898                 case 'VALARM':
899                     $this->_parseAlarm($event, $property, $vevent);
900                     break;
901                     
902                 case 'CATEGORIES':
903                     $tags = Tinebase_Model_Tag::resolveTagNameToTag($property->getParts(), 'Calendar');
904                     if (! isset($event->tags)) {
905                         $event->tags = $tags;
906                     } else {
907                         $event->tags->merge($tags);
908                     }
909                     break;
910                     
911                 case 'ATTACH':
912                     $name = (string) $property['FILENAME'];
913                     $managedId = (string) $property['MANAGED-ID'];
914                     $value = (string) $property['VALUE'];
915                     $attachment = NULL;
916                     $readFromURL = false;
917                     $url = '';
918                     
919                     if (Tinebase_Core::isLogLevel(Zend_Log::INFO))
920                         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' attachment found: ' . $name . ' ' . $managedId);
921                     
922                     if ($managedId) {
923                         $attachment = $event->attachments instanceof Tinebase_Record_RecordSet ?
924                             $event->attachments->filter('hash', $property['MANAGED-ID'])->getFirstRecord() :
925                             NULL;
926                         
927                         // NOTE: we might miss a attachment here for the following reasons
928                         //       1. client reuses a managed id (we are server):
929                         //          We havn't observerd this yet. iCal client reuse manged id's
930                         //          from base events in exceptions but this is covered as we 
931                         //          initialize new exceptions with base event attachments
932                         //          
933                         //          When a client reuses a managed id it's not clear yet if
934                         //          this managed id needs to be in the same series/calendar/server
935                         //
936                         //          As we use the object hash the managed id might be used in the 
937                         //          same files with different names. We need to evaluate the name
938                         //          (if attached) in this case as well.
939                         //       
940                         //       2. server send his managed id (we are client)
941                         //          * we need to download the attachment (here?)
942                         //          * we need to have a mapping externalid / internalid (where?)
943                         
944                         if (! $attachment) {
945                             $readFromURL = true;
946                             $url = $property->getValue();
947                         } else {
948                             $attachments->addRecord($attachment);
949                         }
950                     } elseif('URI' === $value) {
951                         /*
952                          * ATTACH;VALUE=URI:https://server.com/calendars/__uids__/0AA0
953  3A3B-F7B6-459A-AB3E-4726E53637D0/dropbox/4971F93F-8657-412B-841A-A0FD913
954  9CD61.dropbox/Canada.png
955                          */
956                         $url = $property->getValue();
957                         $urlParts = parse_url($url);
958                         $host = $urlParts['host'];
959                         $name = pathinfo($urlParts['path'], PATHINFO_BASENAME);
960
961                         // iCal 10.7 places URI before uploading
962                         if (parse_url(Tinebase_Core::getHostname(), PHP_URL_HOST) != $host) {
963                             $readFromURL = true;
964                         }
965                     }
966                     // base64
967                     else {
968                         // @TODO: implement (check if add / update / update is needed)
969                         if (Tinebase_Core::isLogLevel(Zend_Log::WARN))
970                                 Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' attachment found that could not be imported due to missing managed id');
971                     }
972                     
973                     if ($readFromURL) {
974                         if (preg_match('#^(https?://)(.*)$#', str_replace(array("\n","\r"), '', $url), $matches)) {
975                             // we are client and found an external hosted attachment that we need to import
976                             $userCredentialCache = Tinebase_Core::getUserCredentialCache();
977                             $url = $matches[1] . $userCredentialCache->username . ':' . $userCredentialCache->password . '@' . $matches[2];
978                             $attachmentInfo = $matches[1] . $matches[2]. ' ' . $name . ' ' . $managedId;
979                             if (Tinebase_Helper::urlExists($url)) {
980                                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO))
981                                     Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
982                                             . ' Downloading attachment: ' . $attachmentInfo);
983                                 
984                                 $stream = fopen($url, 'r');
985                                 $attachment = new Tinebase_Model_Tree_Node(array(
986                                     'name'         => rawurldecode($name),
987                                     'type'         => Tinebase_Model_Tree_Node::TYPE_FILE,
988                                     'contenttype'  => (string) $property['FMTTYPE'],
989                                     'tempFile'     => $stream,
990                                     ), true);
991                                 $attachments->addRecord($attachment);
992                             } else {
993                                 if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ 
994                                     . ' Url not found (got 404): ' . $attachmentInfo . ' - Skipping attachment');
995                             }
996                         } else {
997                             if (Tinebase_Core::isLogLevel(Zend_Log::WARN))
998                                 Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ 
999                                     . ' Attachment found with malformed url: ' . $url);
1000                         }
1001                     }
1002                     break;
1003                     
1004                 case 'X-MOZ-LASTACK':
1005                     $lastAck = $this->_convertToTinebaseDateTime($property);
1006                     break;
1007                     
1008                 case 'X-MOZ-SNOOZE-TIME':
1009                     $snoozeTime = $this->_convertToTinebaseDateTime($property);
1010                     break;
1011                     
1012                 default:
1013                     // thunderbird saves snooze time for recurring event occurrences in properties with names like this -
1014                     // we just assume that the event/recur series has only one snooze time 
1015                     if (preg_match('/^X-MOZ-SNOOZE-TIME-[0-9]+$/', $property->name)) {
1016                         $snoozeTime = $this->_convertToTinebaseDateTime($property);
1017                         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
1018                             . ' Found snooze time for recur occurrence: ' . $snoozeTime->toString());
1019                     }
1020                     break;
1021             }
1022         }
1023
1024         // NOTE: X-CALENDARSERVER-ACCESS overwrites CLASS
1025         if (isset($vevent->{'X-CALENDARSERVER-ACCESS'})) {
1026             $event->class = $vevent->{'X-CALENDARSERVER-ACCESS'} == 'PUBLIC' ?
1027                 Calendar_Model_Event::CLASS_PUBLIC :
1028                 Calendar_Model_Event::CLASS_PRIVATE;
1029         }
1030
1031         if (isset($lastAck)) {
1032             Calendar_Controller_Alarm::setAcknowledgeTime($event->alarms, $lastAck);
1033         }
1034         if (isset($snoozeTime)) {
1035             Calendar_Controller_Alarm::setSnoozeTime($event->alarms, $snoozeTime);
1036         }
1037         
1038         // merge old and new attendee
1039         Calendar_Model_Attender::emailsToAttendee($event, $newAttendees);
1040         
1041         if (empty($event->seq)) {
1042             $event->seq = 1;
1043         }
1044         
1045         if (empty($event->class)) {
1046             $event->class = Calendar_Model_Event::CLASS_PUBLIC;
1047         }
1048         
1049         $this->_manageAttachmentsFromClient($event, $attachments);
1050         
1051         if (empty($event->dtend)) {
1052             if (empty($event->dtstart)) {
1053                 throw new Tinebase_Exception_UnexpectedValue("Got event without dtstart and dtend");
1054             }
1055             
1056             // TODO find out duration (see TRIGGER DURATION)
1057 //             if (isset($vevent->DURATION)) {
1058 //             }
1059             if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__
1060                     . ' Got event without dtend. Assuming 30 minutes duration');
1061             $event->dtend = clone $event->dtstart;
1062             $event->dtend->addMinute(30);
1063         }
1064         
1065         $this->_manageAttachmentsFromClient($event, $attachments);
1066         
1067         // convert all datetime fields to UTC
1068         $event->setTimezone('UTC');
1069     }
1070     
1071     /**
1072      * get utc datetime from date string and handle dates (ie 20140922) in usertime
1073      * 
1074      * @param string $dateString
1075      * 
1076      * TODO maybe this can be replaced with _convertToTinebaseDateTime
1077      */
1078     static public function getUTCDateFromStringInUsertime($dateString)
1079     {
1080         if (strlen($dateString) < 10) {
1081             $date = date_create($dateString, new DateTimeZone ((string) Tinebase_Core::getUserTimezone()));
1082         } else {
1083             $date = date_create($dateString);
1084         }
1085         $date->setTimezone(new DateTimeZone('UTC'));
1086         return $date;
1087     }
1088 }