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