fixes empty dtend by assuming 30 minutes duration
[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         $vcalendar->add($vevent);
303     }
304     
305     /**
306      * add event attendee to VEVENT object 
307      * 
308      * @param \Sabre\VObject\Component\VEvent $vevent
309      * @param Calendar_Model_Event            $event
310      */
311     protected function _addEventAttendee(\Sabre\VObject\Component\VEvent $vevent, Calendar_Model_Event $event)
312     {
313         if (empty($event->attendee)) {
314             return;
315         }
316         
317         Calendar_Model_Attender::resolveAttendee($event->attendee, FALSE, $event);
318         
319         foreach($event->attendee as $eventAttendee) {
320             $attendeeEmail = $eventAttendee->getEmail();
321             
322             $parameters = array(
323                 'CN'       => $eventAttendee->getName(),
324                 'CUTYPE'   => Calendar_Convert_Event_VCalendar_Abstract::$cutypeMap[$eventAttendee->user_type],
325                 'PARTSTAT' => $eventAttendee->status,
326                 'ROLE'     => "{$eventAttendee->role}-PARTICIPANT",
327                 'RSVP'     => 'FALSE'
328             );
329             if (strpos($attendeeEmail, '@') !== false) {
330                 $parameters['EMAIL'] = $attendeeEmail;
331             }
332             $vevent->add('ATTENDEE', (strpos($attendeeEmail, '@') !== false ? 'mailto:' : 'urn:uuid:') . $attendeeEmail, $parameters);
333         }
334     }
335     
336     /**
337      * can be overwriten in extended class to modify/cleanup $_vcalendar
338      * 
339      * @param \Sabre\VObject\Component\VCalendar $vcalendar
340      */
341     protected function _afterFromTine20Model(\Sabre\VObject\Component\VCalendar $vcalendar)
342     {
343     }
344     
345     /**
346      * set the METHOD for the generated VCALENDAR
347      *
348      * @param  string  $_method  the method
349      */
350     public function setMethod($method)
351     {
352         $this->_method = $method;
353     }
354     
355     /**
356      * converts vcalendar to Calendar_Model_Event
357      * 
358      * @param  mixed                 $_blob    the VCALENDAR to parse
359      * @param  Calendar_Model_Event  $_record  update existing event
360      * @param  array                 $options  array of options
361      * @return Calendar_Model_Event
362      */
363     public function toTine20Model($blob, Tinebase_Record_Abstract $_record = null, $options = array())
364     {
365         $vcalendar = self::getVObject($blob);
366         
367         // contains the VCALENDAR any VEVENTS
368         if (! isset($vcalendar->VEVENT)) {
369             throw new Tinebase_Exception_UnexpectedValue('no vevents found');
370         }
371         
372         // update a provided record or create a new one
373         if ($_record instanceof Calendar_Model_Event) {
374             $event = $_record;
375         } else {
376             $event = new Calendar_Model_Event(null, false);
377         }
378         
379         if (isset($vcalendar->METHOD)) {
380             $this->setMethod($vcalendar->METHOD);
381         }
382         
383         $baseVevent = $this->_findMainEvent($vcalendar);
384         
385         if (! $baseVevent) {
386             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
387                 . ' No main VEVENT found');
388             
389             if (! $_record && count($vcalendar->VEVENT) > 0) {
390                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
391                     . ' Convert recur exception without existing event using first VEVENT');
392                 $this->_convertVevent($vcalendar->VEVENT[0], $event, $options);
393             }
394         } else {
395             $this->_convertVevent($baseVevent, $event, $options);
396         }
397         
398         // TODO only do this for events with rrule?
399         // if (! empty($event->rrule)) {
400         $this->_parseEventExceptions($event, $vcalendar, $baseVevent, $options);
401         
402         $event->isValid(true);
403         
404         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ 
405             . ' Event: ' . print_r($event->toArray(), true));
406         
407         return $event;
408     }
409     
410     /**
411      * find the main event - the main event has no RECURRENCE-ID
412      * 
413      * @param \Sabre\VObject\Component\VCalendar $vcalendar
414      * @return \Sabre\VObject\Component\VCalendar | null
415      */
416     protected function _findMainEvent(\Sabre\VObject\Component\VCalendar $vcalendar)
417     {
418         foreach ($vcalendar->VEVENT as $vevent) {
419             if (! isset($vevent->{'RECURRENCE-ID'})) {
420                 return $vevent;
421             }
422         }
423         
424         return null;
425     }
426     
427     /**
428      * parse event exceptions and add them to Tine 2.0 event record
429      * 
430      * @param  Calendar_Model_Event                $event
431      * @param  \Sabre\VObject\Component\VCalendar  $vcalendar
432      * @param  \Sabre\VObject\Component\VCalendar  $baseVevent
433      * @param  array                               $options
434      */
435     protected function _parseEventExceptions(Calendar_Model_Event $event, \Sabre\VObject\Component\VCalendar $vcalendar, $baseVevent = null, $options = array())
436     {
437         if (! $event->exdate instanceof Tinebase_Record_RecordSet) {
438             $event->exdate = new Tinebase_Record_RecordSet('Calendar_Model_Event');
439         }
440         $recurExceptions =  $event->exdate->filter('is_deleted', false);
441         
442         foreach ($vcalendar->VEVENT as $vevent) {
443             if (isset($vevent->{'RECURRENCE-ID'}) && $event->uid == $vevent->UID) {
444                 $recurException = $this->_getRecurException($recurExceptions, $vevent);
445                 
446                 // initialize attendee with attendee from base events for new exceptions
447                 // this way we can keep attendee extra values like groupmember type
448                 // attendees which do not attend to the new exception will be removed in _convertVevent
449                 if (! $recurException->attendee instanceof Tinebase_Record_RecordSet) {
450                     $recurException->attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender');
451                     foreach ($event->attendee as $attendee) {
452                         $recurException->attendee->addRecord(new Calendar_Model_Attender(array(
453                             'user_id'   => $attendee->user_id,
454                             'user_type' => $attendee->user_type,
455                             'role'      => $attendee->role,
456                             'status'    => $attendee->status
457                         )));
458                     }
459                 }
460                 
461                 if ($baseVevent) {
462                     $this->_adaptBaseEventProperties($vevent, $baseVevent);
463                 }
464                 
465                 $this->_convertVevent($vevent, $recurException, $options);
466                 
467                 if (! $recurException->getId()) {
468                     $event->exdate->addRecord($recurException);
469                 }
470             }
471         }
472     }
473     
474     /**
475      * adapt X-MOZ-LASTACK / X-MOZ-SNOOZE-TIME from base vevent
476      * 
477      * @see 0009396: alarm_ack_time and alarm_snooze_time are not updated
478      */
479     protected function _adaptBaseEventProperties($vevent, $baseVevent)
480     {
481         $propertiesToAdapt = array('X-MOZ-LASTACK', 'X-MOZ-SNOOZE-TIME');
482         
483         foreach ($propertiesToAdapt as $property) {
484             if (isset($baseVevent->{$property})) {
485                 $vevent->{$property} = $baseVevent->{$property};
486             }
487         }
488     }
489     
490     /**
491      * convert VCALENDAR to Tinebase_Record_RecordSet of Calendar_Model_Event
492      * 
493      * @param  mixed  $blob  the vcalendar to parse
494      * @param  array  $options
495      * @return Tinebase_Record_RecordSet
496      */
497     public function toTine20RecordSet($blob, $options = array())
498     {
499         $vcalendar = self::getVObject($blob);
500         
501         $result = new Tinebase_Record_RecordSet('Calendar_Model_Event');
502         
503         foreach ($vcalendar->VEVENT as $vevent) {
504             if (! isset($vevent->{'RECURRENCE-ID'})) {
505                 $event = new Calendar_Model_Event();
506                 $this->_convertVevent($vevent, $event, $options);
507                 if (! empty($event->rrule)) {
508                     $this->_parseEventExceptions($event, $vcalendar, $options);
509                 }
510                 $result->addRecord($event);
511             }
512         }
513         
514         return $result;
515     }
516     
517     /**
518      * returns VObject of input data
519      * 
520      * @param   mixed  $blob
521      * @return  \Sabre\VObject\Component\VCalendar
522      */
523     public static function getVObject($blob)
524     {
525         if ($blob instanceof \Sabre\VObject\Component\VCalendar) {
526             return $blob;
527         }
528         
529         if (is_resource($blob)) {
530             $blob = stream_get_contents($blob);
531         }
532         
533         $vcalendar = self::readVCalBlob($blob);
534         
535         return $vcalendar;
536     }
537     
538     /**
539      * reads vcal blob and tries to repair some parsing problems that Sabre has
540      * 
541      * @param string $blob
542      * @param integer $failcount
543      * @param integer $spacecount
544      * @param integer $lastBrokenLineNumber
545      * @param array $lastLines
546      * @throws Sabre\VObject\ParseException
547      * @return Sabre\VObject\Component\VCalendar
548      * 
549      * @see 0006110: handle iMIP messages from outlook
550      * 
551      * @todo maybe we can remove this when #7438 is resolved
552      */
553     public static function readVCalBlob($blob, $failcount = 0, $spacecount = 0, $lastBrokenLineNumber = 0, $lastLines = array())
554     {
555         // convert to utf-8
556         $blob = mbConvertTo($blob);
557         
558         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ .
559             ' ' . $blob);
560         
561         try {
562             $vcalendar = \Sabre\VObject\Reader::read($blob);
563         } catch (Sabre\VObject\ParseException $svpe) {
564             // NOTE: we try to repair\Sabre\VObject\Reader as it fails to detect followup lines that do not begin with a space or tab
565             if ($failcount < 10 && preg_match(
566                 '/Invalid VObject, line ([0-9]+) did not follow the icalendar\/vcard format/', $svpe->getMessage(), $matches
567             )) {
568                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .
569                     ' ' . $svpe->getMessage() .
570                     ' lastBrokenLineNumber: ' . $lastBrokenLineNumber);
571                 
572                 $brokenLineNumber = $matches[1] - 1 + $spacecount;
573                 
574                 if ($lastBrokenLineNumber === $brokenLineNumber) {
575                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .
576                         ' Try again: concat this line to previous line.');
577                     $lines = $lastLines;
578                     $brokenLineNumber--;
579                     // increase spacecount because one line got removed
580                     $spacecount++;
581                 } else {
582                     $lines = preg_split('/[\r\n]*\n/', $blob);
583                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .
584                         ' Concat next line to this one.');
585                     $lastLines = $lines; // for retry
586                 }
587                 $lines[$brokenLineNumber] .= $lines[$brokenLineNumber + 1];
588                 unset($lines[$brokenLineNumber + 1]);
589                 
590                 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ .
591                     ' failcount: ' . $failcount .
592                     ' brokenLineNumber: ' . $brokenLineNumber .
593                     ' spacecount: ' . $spacecount);
594                 
595                 $vcalendar = self::readVCalBlob(implode("\n", $lines), $failcount + 1, $spacecount, $brokenLineNumber, $lastLines);
596             } else {
597                 throw $svpe;
598             }
599         }
600         
601         return $vcalendar;
602     }
603     
604     /**
605      * get METHOD of current VCALENDAR or supplied blob
606      * 
607      * @param  string  $blob
608      * @return string|NULL
609      */
610     public function getMethod($blob = NULL)
611     {
612         if ($this->_method) {
613             return $this->_method;
614         }
615         
616         if ($blob !== NULL) {
617             $vcalendar = self::getVObject($blob);
618             return $vcalendar->METHOD;
619         }
620         
621         return null;
622     }
623
624     /**
625      * find a matching exdate or return an empty event record
626      * 
627      * @param  Tinebase_Record_RecordSet        $oldExdates
628      * @param  \Sabre\VObject\Component\VEvent  $vevent
629      * @return Calendar_Model_Event
630      */
631     protected function _getRecurException(Tinebase_Record_RecordSet $oldExdates,Sabre\VObject\Component\VEvent $vevent)
632     {
633         $exDate = clone $vevent->{'RECURRENCE-ID'}->getDateTime();
634         $exDate->setTimeZone(new DateTimeZone('UTC'));
635         $exDateString = $exDate->format('Y-m-d H:i:s');
636         
637         foreach ($oldExdates as $id => $oldExdate) {
638             if ($exDateString == substr((string) $oldExdate->recurid, -19)) {
639                 return $oldExdate;
640             }
641         }
642         
643         return new Calendar_Model_Event();
644     }
645     
646     /**
647      * get attendee array for given contact
648      * 
649      * @param  \Sabre\VObject\Property\ICalendar\CalAddress  $calAddress  the attendee row from the vevent object
650      * @return array
651      */
652     protected function _getAttendee(\Sabre\VObject\Property\ICalendar\CalAddress $calAddress)
653     {
654         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) 
655             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' attendee ' . $calAddress->serialize());
656         
657         if (isset($calAddress['CUTYPE']) && in_array($calAddress['CUTYPE']->getValue(), array('INDIVIDUAL', Calendar_Model_Attender::USERTYPE_GROUP, Calendar_Model_Attender::USERTYPE_RESOURCE))) {
658             $type = $calAddress['CUTYPE']->getValue() == 'INDIVIDUAL' ? Calendar_Model_Attender::USERTYPE_USER : $calAddress['CUTYPE']->getValue();
659         } else {
660             $type = Calendar_Model_Attender::USERTYPE_USER;
661         }
662         
663         if (isset($calAddress['ROLE']) && in_array($calAddress['ROLE']->getValue(), array(Calendar_Model_Attender::ROLE_OPTIONAL, Calendar_Model_Attender::ROLE_REQUIRED))) {
664             $role = $calAddress['ROLE']->getValue();
665         } else {
666             $role = Calendar_Model_Attender::ROLE_REQUIRED;
667         }
668         
669         if (isset($calAddress['PARTSTAT']) && in_array($calAddress['PARTSTAT']->getValue(), array(
670             Calendar_Model_Attender::STATUS_ACCEPTED,
671             Calendar_Model_Attender::STATUS_DECLINED,
672             Calendar_Model_Attender::STATUS_NEEDSACTION,
673             Calendar_Model_Attender::STATUS_TENTATIVE
674         ))) {
675             $status = $calAddress['PARTSTAT']->getValue();
676         } else {
677             $status = Calendar_Model_Attender::STATUS_NEEDSACTION;
678         }
679         
680         if (!empty($calAddress['EMAIL'])) {
681             $email = $calAddress['EMAIL']->getValue();
682         } else {
683             if (!preg_match('/(?P<protocol>mailto:|urn:uuid:)(?P<email>.*)/i', $calAddress->getValue(), $matches)) {
684                 throw new Tinebase_Exception_UnexpectedValue('invalid attendee provided: ' . $calAddress->getValue());
685             }
686             $email = $matches['email'];
687         }
688         
689         $fullName = isset($calAddress['CN']) ? $calAddress['CN']->getValue() : $email;
690         
691         if (preg_match('/(?P<firstName>\S*) (?P<lastNameName>\S*)/', $fullName, $matches)) {
692             $firstName = $matches['firstName'];
693             $lastName  = $matches['lastNameName'];
694         } else {
695             $firstName = null;
696             $lastName  = $fullName;
697         }
698
699         $attendee = array(
700             'userType'  => $type,
701             'firstName' => $firstName,
702             'lastName'  => $lastName,
703             'partStat'  => $status,
704             'role'      => $role,
705             'email'     => $email
706         );
707         
708         return $attendee;
709     }
710     
711     /**
712      * parse VEVENT part of VCALENDAR
713      * 
714      * @param  \Sabre\VObject\Component\VEvent  $vevent  the VEVENT to parse
715      * @param  Calendar_Model_Event             $event   the Tine 2.0 event to update
716      * @param  array                            $options
717      */
718     protected function _convertVevent(\Sabre\VObject\Component\VEvent $vevent, Calendar_Model_Event $event, $options)
719     {
720         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) 
721             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' vevent ' . $vevent->serialize());
722         
723         $newAttendees = array();
724         $event->alarms = new Tinebase_Record_RecordSet('Tinebase_Model_Alarm');
725         
726         foreach ($vevent->children() as $property) {
727             switch ($property->name) {
728                 case 'CREATED':
729                 case 'DTSTAMP':
730                     if (! isset($options[self::OPTION_USE_SERVER_MODLOG]) || $options[self::OPTION_USE_SERVER_MODLOG] !== true) {
731                         $event->{$property->name == 'CREATED' ? 'creation_time' : 'last_modified_time'} = $this->_convertToTinebaseDateTime($property);
732                     }
733                     break;
734                     
735                 case 'LAST-MODIFIED':
736                     $event->last_modified_time = new Tinebase_DateTime($property->getValue());
737                     break;
738                 
739                 case 'ATTENDEE':
740                     $newAttendee = $this->_getAttendee($property);
741                     if ($newAttendee) {
742                         $newAttendees[] = $newAttendee;
743                     }
744                     break;
745                     
746                 case 'CLASS':
747                     if (in_array($property->getValue(), array(Calendar_Model_Event::CLASS_PRIVATE, Calendar_Model_Event::CLASS_PUBLIC))) {
748                         $event->class = $property->getValue();
749                     } else {
750                         $event->class = Calendar_Model_Event::CLASS_PUBLIC;
751                     }
752                     
753                     break;
754                     
755                 case 'STATUS':
756                     if (in_array($property->getValue(), array(Calendar_Model_Event::STATUS_CONFIRMED, Calendar_Model_Event::STATUS_TENTATIVE, Calendar_Model_Event::STATUS_CANCELED))) {
757                         $event->status = $property->getValue();
758                     } else {
759                         $event->status = Calendar_Model_Event::STATUS_CONFIRMED;
760                     }
761                     break;
762                     
763                 case 'DTEND':
764                     
765                     if (isset($property['VALUE']) && strtoupper($property['VALUE']) == 'DATE') {
766                         // all day event
767                         $event->is_all_day_event = true;
768                         $dtend = $this->_convertToTinebaseDateTime($property, TRUE);
769                         
770                         // whole day events ends at 23:59:59 in Tine 2.0 but 00:00 the next day in vcalendar
771                         $dtend->subSecond(1);
772                     } else {
773                         $event->is_all_day_event = false;
774                         $dtend = $this->_convertToTinebaseDateTime($property);
775                     }
776                     
777                     $event->dtend = $dtend;
778                     
779                     break;
780                     
781                 case 'DTSTART':
782                     if (isset($property['VALUE']) && strtoupper($property['VALUE']) == 'DATE') {
783                         // all day event
784                         $event->is_all_day_event = true;
785                         $dtstart = $this->_convertToTinebaseDateTime($property, TRUE);
786                     } else {
787                         $event->is_all_day_event = false;
788                         $dtstart = $this->_convertToTinebaseDateTime($property);
789                     }
790                     
791                     $event->originator_tz = $dtstart->getTimezone()->getName();
792                     $event->dtstart = $dtstart;
793                     
794                     break;
795                     
796                 case 'SEQUENCE':
797                     if (! isset($options[self::OPTION_USE_SERVER_MODLOG]) || $options[self::OPTION_USE_SERVER_MODLOG] !== true) {
798                         $event->seq = $property->getValue();
799                     }
800                     break;
801                     
802                 case 'DESCRIPTION':
803                 case 'LOCATION':
804                 case 'UID':
805                 case 'SUMMARY':
806                     $key = strtolower($property->name);
807                     $event->$key = $property->getValue();
808                     break;
809                     
810                 case 'ORGANIZER':
811                     $email = null;
812                     
813                     if (!empty($property['EMAIL'])) {
814                         $email = $property['EMAIL'];
815                     } elseif (preg_match('/mailto:(?P<email>.*)/i', $property->getValue(), $matches)) {
816                         $email = $matches['email'];
817                     }
818                     
819                     if ($email !== null) {
820                         // it's not possible to change the organizer by spec
821                         if (empty($event->organizer)) {
822                             $name = isset($property['CN']) ? $property['CN']->getValue() : $email;
823                             $contact = Calendar_Model_Attender::resolveEmailToContact(array(
824                                 'email'     => $email,
825                                 'lastName'  => $name,
826                             ));
827                         
828                             $event->organizer = $contact->getId();
829                         }
830                         
831                         // Lightning attaches organizer ATTENDEE properties to ORGANIZER property and does not add an ATTENDEE for the organizer
832                         if (isset($property['PARTSTAT'])) {
833                             $newAttendees[] = $this->_getAttendee($property);
834                         }
835                     }
836                     
837                     break;
838
839                 case 'RECURRENCE-ID':
840                     // original start of the event
841                     $event->recurid = $this->_convertToTinebaseDateTime($property);
842                     
843                     // convert recurrence id to utc
844                     $event->recurid->setTimezone('UTC');
845                     
846                     break;
847                     
848                 case 'RRULE':
849                     $rruleString = $property->getValue();
850                     
851                     // convert date format
852                     $rruleString = preg_replace_callback('/UNTIL=([\dTZ]+)(?=;?)/', function($matches) {
853                         if (strlen($matches[1]) < 10) {
854                             $dtUntil = date_create($matches[1], new DateTimeZone ((string) Tinebase_Core::get(Tinebase_Core::USERTIMEZONE)));
855                             $dtUntil->setTimezone(new DateTimeZone('UTC'));
856                         } else {
857                             $dtUntil = date_create($matches[1]);
858                         }
859                         
860                         return 'UNTIL=' . $dtUntil->format(Tinebase_Record_Abstract::ISO8601LONG);
861                     }, $rruleString);
862
863                     // remove additional days from BYMONTHDAY property (BYMONTHDAY=11,15 => BYMONTHDAY=11)
864                     $rruleString = preg_replace('/(BYMONTHDAY=)([\d]+),([,\d]+)/', '$1$2', $rruleString);
865                     
866                     $event->rrule = $rruleString;
867                     
868                     // process exceptions
869                     if (isset($vevent->EXDATE)) {
870                         $exdates = new Tinebase_Record_RecordSet('Calendar_Model_Event');
871                         
872                         foreach ($vevent->EXDATE as $exdate) {
873                             foreach ($exdate->getDateTimes() as $exception) {
874                                 if (isset($exdate['VALUE']) && strtoupper($exdate['VALUE']) == 'DATE') {
875                                     $recurid = new Tinebase_DateTime($exception->format(Tinebase_Record_Abstract::ISO8601LONG), (string) Tinebase_Core::get(Tinebase_Core::USERTIMEZONE));
876                                 } else {
877                                     $recurid = new Tinebase_DateTime($exception->format(Tinebase_Record_Abstract::ISO8601LONG), $exception->getTimezone());
878                                 }
879                                 $recurid->setTimezone(new DateTimeZone('UTC'));
880                                 
881                                 $eventException = new Calendar_Model_Event(array(
882                                     'recurid'    => $recurid,
883                                     'is_deleted' => true
884                                 ));
885                         
886                                 $exdates->addRecord($eventException);
887                             }
888                         }
889                     
890                         $event->exdate = $exdates;
891                     }
892                     
893                     break;
894                     
895                 case 'TRANSP':
896                     if (in_array($property->getValue(), array(Calendar_Model_Event::TRANSP_OPAQUE, Calendar_Model_Event::TRANSP_TRANSP))) {
897                         $event->transp = $property->getValue();
898                     } else {
899                         $event->transp = Calendar_Model_Event::TRANSP_TRANSP;
900                     }
901                     
902                     break;
903                     
904                 case 'UID':
905                     // it's not possible to change the uid by spec
906                     if (!empty($event->uid)) {
907                         continue;
908                     }
909                     
910                     $event->uid = $property->getValue();
911                 
912                     break;
913                     
914                 case 'VALARM':
915                     $this->_parseAlarm($event, $property, $vevent);
916                     break;
917                     
918                 case 'CATEGORIES':
919                     $tags = Tinebase_Model_Tag::resolveTagNameToTag($property->getParts(), 'Calendar');
920                     if (! isset($event->tags)) {
921                         $event->tags = $tags;
922                     } else {
923                         $event->tags->merge($tags);
924                     }
925                     break;
926                     
927                 case 'X-MOZ-LASTACK':
928                     $lastAck = $this->_convertToTinebaseDateTime($property);
929                     break;
930                     
931                 case 'X-MOZ-SNOOZE-TIME':
932                     $snoozeTime = $this->_convertToTinebaseDateTime($property);
933                     break;
934                     
935                 default:
936                     // thunderbird saves snooze time for recurring event occurrences in properties with names like this -
937                     // we just assume that the event/recur series has only one snooze time 
938                     if (preg_match('/^X-MOZ-SNOOZE-TIME-[0-9]+$/', $property->name)) {
939                         $snoozeTime = $this->_convertToTinebaseDateTime($property);
940                         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
941                             . ' Found snooze time for recur occurrence: ' . $snoozeTime->toString());
942                     }
943                     break;
944             }
945         }
946         
947         if (isset($lastAck)) {
948             Calendar_Controller_Alarm::setAcknowledgeTime($event->alarms, $lastAck);
949         }
950         if (isset($snoozeTime)) {
951             Calendar_Controller_Alarm::setSnoozeTime($event->alarms, $snoozeTime);
952         }
953         
954         // merge old and new attendee
955         Calendar_Model_Attender::emailsToAttendee($event, $newAttendees);
956         
957         if (empty($event->seq)) {
958             $event->seq = 1;
959         }
960         
961         if (empty($event->class)) {
962             $event->class = Calendar_Model_Event::CLASS_PUBLIC;
963         }
964         
965         if (empty($event->dtend)) {
966             // TODO find out duration (see TRIGGER DURATION)
967 //             if (isset($vevent->DURATION)) {
968 //             }
969             if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__
970                     . ' Got event without dtend. Assuming 30 minutes duration');
971             $event->dtend = clone $event->dtstart;
972             $event->dtend->addMinute(30);
973         }
974         
975         // convert all datetime fields to UTC
976         $event->setTimezone('UTC');
977     }
978     
979     /**
980      * parse valarm properties
981      * 
982      * @param Calendar_Model_Event $event
983      * @param unknown $valarms
984      * @param \Sabre\VObject\Component\VEvent $vevent
985      */
986     protected function _parseAlarm(Calendar_Model_Event $event, $valarms, \Sabre\VObject\Component\VEvent $vevent)
987     {
988         foreach ($valarms as $valarm) {
989             
990             if ($valarm->ACTION == 'NONE') {
991                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
992                         . ' We can\'t cope with action NONE: iCal 6.0 sends default alarms in the year 1976 with action NONE. Skipping alarm.');
993                 continue;
994             }
995             
996             if (! is_object($valarm->TRIGGER)) {
997                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
998                 . ' Alarm has no TRIGGER value. Skipping it.');
999                 continue;
1000             }
1001             
1002             # TRIGGER:-PT15M
1003             if (is_string($valarm->TRIGGER->getValue()) && $valarm->TRIGGER instanceof Sabre\VObject\Property\ICalendar\Duration) {
1004                 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
1005                 . ' Adding DURATION trigger value for ' . $valarm->TRIGGER->getValue());
1006                 $valarm->TRIGGER->add('VALUE', 'DURATION');
1007             }
1008             
1009             $trigger = is_object($valarm->TRIGGER['VALUE']) ? $valarm->TRIGGER['VALUE'] : (is_object($valarm->TRIGGER['RELATED']) ? $valarm->TRIGGER['RELATED'] : NULL);
1010             
1011             if ($trigger === NULL) {
1012                 // added Trigger/Related for eM Client alarms
1013                 // 2014-01-03 - Bullshit, why don't we have testdata for emclient alarms?
1014                         //              this alarm handling should be refactored, the logic is scrambled
1015                 // @see 0006110: handle iMIP messages from outlook
1016                 // @todo fix 0007446: handle broken alarm in outlook invitation message
1017                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
1018                 . ' Alarm has no TRIGGER value. Skipping it.');
1019                 continue;
1020             }
1021             
1022             switch (strtoupper($trigger->getValue())) {
1023                 # TRIGGER;VALUE=DATE-TIME:20111031T130000Z
1024                 case 'DATE-TIME':
1025                     $alarmTime = new Tinebase_DateTime($valarm->TRIGGER->getValue());
1026                     $alarmTime->setTimezone('UTC');
1027                     
1028                     $alarm = new Tinebase_Model_Alarm(array(
1029                         'alarm_time'        => $alarmTime,
1030                         'minutes_before'    => 'custom',
1031                         'model'             => 'Calendar_Model_Event'
1032                     ));
1033                     
1034                     break;
1035                 
1036                 # TRIGGER;VALUE=DURATION:-PT1H15M
1037                 case 'DURATION':
1038                 default:
1039                     $alarmTime = $this->_convertToTinebaseDateTime($vevent->DTSTART);
1040                     $alarmTime->setTimezone('UTC');
1041                     
1042                     preg_match('/(?P<invert>[+-]?)(?P<spec>P.*)/', $valarm->TRIGGER->getValue(), $matches);
1043                     $duration = new DateInterval($matches['spec']);
1044                     $duration->invert = !!($matches['invert'] === '-');
1045                     
1046                     $alarm = new Tinebase_Model_Alarm(array(
1047                         'alarm_time'        => $alarmTime->add($duration),
1048                         'minutes_before'    => ($duration->format('%d') * 60 * 24) + ($duration->format('%h') * 60) + ($duration->format('%i')),
1049                         'model'             => 'Calendar_Model_Event'
1050                     ));
1051                     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
1052                         . ' Adding DURATION alarm ' . print_r($alarm->toArray(), true));
1053             }
1054             
1055             if ($valarm->ACKNOWLEDGED) {
1056                 $dtack = $valarm->ACKNOWLEDGED->getDateTime();
1057                 Calendar_Controller_Alarm::setAcknowledgeTime($alarm, $dtack);
1058             }
1059             
1060             $event->alarms->addRecord($alarm);
1061         }
1062     }
1063     
1064     /**
1065      * get datetime from sabredav datetime property (user TZ is fallback)
1066      * 
1067      * @param  Sabre\VObject\Property  $dateTimeProperty
1068      * @param  boolean                 $_useUserTZ
1069      * @return Tinebase_DateTime
1070      * 
1071      * @todo try to guess some common timezones
1072      */
1073     protected function _convertToTinebaseDateTime(\Sabre\VObject\Property $dateTimeProperty, $_useUserTZ = FALSE)
1074     {
1075         $defaultTimezone = date_default_timezone_get();
1076         date_default_timezone_set((string) Tinebase_Core::get(Tinebase_Core::USERTIMEZONE));
1077         
1078         if ($dateTimeProperty instanceof Sabre\VObject\Property\ICalendar\DateTime) {
1079             $dateTime = $dateTimeProperty->getDateTime();
1080             $tz = ($_useUserTZ || (isset($dateTimeProperty['VALUE']) && strtoupper($dateTimeProperty['VALUE']) == 'DATE')) ? 
1081                 (string) Tinebase_Core::get(Tinebase_Core::USERTIMEZONE) : 
1082                 $dateTime->getTimezone();
1083             
1084             $result = new Tinebase_DateTime($dateTime->format(Tinebase_Record_Abstract::ISO8601LONG), $tz);
1085         } else {
1086             $result = new Tinebase_DateTime($dateTimeProperty->getValue());
1087         }
1088         
1089         date_default_timezone_set($defaultTimezone);
1090         
1091         return $result;
1092     }
1093 }