remove unused listener and it's event model
[tine20] / tine20 / Calendar / Controller / Event.php
1 <?php
2 /**
3  * Tine 2.0
4  * 
5  * @package     Calendar
6  * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
7  * @author      Cornelius Weiss <c.weiss@metaways.de>
8  * @copyright   Copyright (c) 2010-2017 Metaways Infosystems GmbH (http://www.metaways.de)
9  */
10
11 /**
12  * Calendar Event Controller
13  * 
14  * In the calendar application, the container grants concept is slightly extended:
15  *  1. GRANTS for events are not only based on the events "calendar" (technically 
16  *     a container) but additionally a USER gets implicit grants for an event if 
17  *     he is ATTENDER (+READ GRANT) or ORGANIZER (+READ,EDIT GRANT).
18  *  2. ATTENDER which are invited to a certain "event" can assign the "event" to
19  *     one of their personal calenders as "display calendar" (technically personal 
20  *     containers they are admin of). The "display calendar" of an ATTENDER is
21  *     stored in the attendee table.  Each USER has a default calendar, as 
22  *     PREFERENCE,  all invitations are assigned to.
23  *  3. The "effective GRANT" a USER has on an event (read/update/delete/...) is the 
24  *     maximum GRANT of the following sources: 
25  *      - container: GRANT the USER has to the calender of the event
26  *      - implicit:  Additional READ GRANT for an attender and READ,EDIT
27  *                   GRANT for the organizer.
28 *       - inherited: FREEBUSY, READ, PRIVATE, SYNC, EXPORT can be inherited
29 *                    from the GRANTS USER has to the a display calendar
30  * 
31  * When Applying/Asuring grants, we have to deal with two differnt situations:
32  *  A: Check: Check individual grants on a event (record) basis.
33  *            This is required for create/update/delete actions and done by 
34  *            this controllers _checkGrant method.
35  *  B: Seach: From the grants perspective this is a multi step process
36  *            1. fetch all records with appropriate grants from backend
37  *            2. cleanup records user has only free/busy grant for
38  * 
39  *  NOTE: To empower the client for enabling/disabling of actions based on the 
40  *        grants a user has to an event, we need to compute the "effective GRANT"
41  *        for read/search operations.
42  *                  
43  * Case A is not critical, as the amount of data is low. 
44  * Case B however is the hard one, as lots of events and calendars may be
45  * involved.
46  * 
47  * NOTE: the backend always fetches full records for grant calculations.
48  *       searching ids only does not hlep with performance
49  * 
50  * @package Calendar
51  */
52 class Calendar_Controller_Event extends Tinebase_Controller_Record_Abstract implements Tinebase_Controller_Alarm_Interface
53 {
54     /**
55      * @var boolean
56      * 
57      * just set is_delete=1 if record is going to be deleted
58      */
59     protected $_purgeRecords = FALSE;
60     
61     /**
62      * send notifications?
63      *
64      * @var boolean
65      */
66     protected $_sendNotifications = TRUE;
67     
68     /**
69      * @see Tinebase_Controller_Record_Abstract
70      * 
71      * @var boolean
72      */
73     protected $_resolveCustomFields = TRUE;
74
75     /**
76      * @var Calendar_Model_Attender
77      */
78     protected $_calendarUser = NULL;
79
80     /**
81      * @var Calendar_Controller_Event
82      */
83     private static $_instance = NULL;
84     
85     /**
86      * the constructor
87      *
88      * don't use the constructor. use the singleton 
89      */
90     private function __construct()
91     {
92         $this->_applicationName = 'Calendar';
93         $this->_modelName       = 'Calendar_Model_Event';
94         $this->_backend         = new Calendar_Backend_Sql();
95
96         // set default CU
97         $this->setCalendarUser(new Calendar_Model_Attender(array(
98             'user_type' => Calendar_Model_Attender::USERTYPE_USER,
99             'user_id'   => Calendar_Controller_MSEventFacade::getCurrentUserContactId()
100         )));
101     }
102
103     /**
104      * don't clone. Use the singleton.
105      */
106     private function __clone() 
107     {
108         
109     }
110     
111     /**
112      * singleton
113      *
114      * @return Calendar_Controller_Event
115      */
116     public static function getInstance() 
117     {
118         if (self::$_instance === NULL) {
119             self::$_instance = new Calendar_Controller_Event();
120         }
121         return self::$_instance;
122     }
123
124     /**
125      * sets current calendar user
126      *
127      * @param Calendar_Model_Attender $_calUser
128      * @return Calendar_Model_Attender oldUser
129      */
130     public function setCalendarUser(Calendar_Model_Attender $_calUser)
131     {
132         if (! in_array($_calUser->user_type, array(Calendar_Model_Attender::USERTYPE_USER, Calendar_Model_Attender::USERTYPE_GROUPMEMBER))) {
133             throw new Tinebase_Exception_UnexpectedValue('Calendar user must be a contact');
134         }
135         $oldUser = $this->_calendarUser;
136         $this->_calendarUser = $_calUser;
137
138         return $oldUser;
139     }
140
141     /**
142      * get current calendar user
143      *
144      * @return Calendar_Model_Attender
145      */
146     public function getCalendarUser()
147     {
148         return $this->_calendarUser;
149     }
150
151     /**
152      * checks if all attendee of given event are not busy for given event
153      * 
154      * @param Calendar_Model_Event $_event
155      * @return void
156      * @throws Calendar_Exception_AttendeeBusy
157      */
158     public function checkBusyConflicts($_event)
159     {
160         $ignoreUIDs = !empty($_event->uid) ? array($_event->uid) : array();
161         
162         if ($_event->transp == Calendar_Model_Event::TRANSP_TRANSP || count($_event->attendee) < 1) {
163             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
164                 . " Skipping free/busy check because event is transparent or has no attendee");
165             return;
166         }
167
168         $periods = $this->getBlockingPeriods($_event, array(
169             'from'  => $_event->dtstart,
170             'until' => $_event->dtstart->getClone()->addMonth(2)
171         ));
172
173         $fbInfo = $this->getFreeBusyInfo($periods, $_event->attendee, $ignoreUIDs);
174         
175         if (count($fbInfo) > 0) {
176             $busyException = new Calendar_Exception_AttendeeBusy();
177             $busyException->setFreeBusyInfo($fbInfo);
178             
179             Calendar_Model_Attender::resolveAttendee($_event->attendee, /* resolve_display_containers = */ false);
180             $busyException->setEvent($_event);
181             
182             throw $busyException;
183         }
184         
185         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
186             . " Free/busy check: no conflict found");
187     }
188     
189     /**
190      * add one record
191      *
192      * @param   Tinebase_Record_Interface $_record
193      * @param   bool                      $_checkBusyConflicts
194      * @return  Tinebase_Record_Interface
195      * @throws  Tinebase_Exception_AccessDenied
196      * @throws  Tinebase_Exception_Record_Validation
197      */
198     public function create(Tinebase_Record_Interface $_record, $_checkBusyConflicts = FALSE, $skipEvent = false)
199     {
200         try {
201             $db = $this->_backend->getAdapter();
202             $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
203             
204             $this->_inspectEvent($_record, $skipEvent);
205             
206             // we need to resolve groupmembers before free/busy checking
207             Calendar_Model_Attender::resolveGroupMembers($_record->attendee);
208             
209             if ($_checkBusyConflicts) {
210                 // ensure that all attendee are free
211                 $this->checkBusyConflicts($_record);
212             }
213             
214             $sendNotifications = $this->_sendNotifications;
215             $this->_sendNotifications = FALSE;
216             
217             $createdEvent = parent::create($_record);
218             
219             $this->_sendNotifications = $sendNotifications;
220             
221             Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
222         } catch (Exception $e) {
223             Tinebase_TransactionManager::getInstance()->rollBack();
224             throw $e;
225         }
226         
227         // send notifications
228         if ($this->_sendNotifications && $_record->mute != 1) {
229             $this->doSendNotifications($createdEvent, Tinebase_Core::getUser(), 'created');
230         }        
231
232         return $createdEvent;
233     }
234     
235     /**
236      * inspect creation of one record (after create)
237      *
238      * @param   Tinebase_Record_Interface $_createdRecord
239      * @param   Tinebase_Record_Interface $_record
240      * @return  void
241      */
242     protected function _inspectAfterCreate($_createdRecord, Tinebase_Record_Interface $_record)
243     {
244         $this->_saveAttendee($_record, $_createdRecord);
245     }
246     
247     /**
248      * deletes a recur series
249      *
250      * @param  Calendar_Model_Event $_recurInstance
251      * @return void
252      */
253     public function deleteRecurSeries($_recurInstance)
254     {
255         $baseEvent = $this->getRecurBaseEvent($_recurInstance);
256         $this->delete($baseEvent->getId());
257     }
258     
259     /**
260      * Gets all entries
261      *
262      * @param string $_orderBy Order result by
263      * @param string $_orderDirection Order direction - allowed are ASC and DESC
264      * @throws Tinebase_Exception_InvalidArgument
265      * @return Tinebase_Record_RecordSet
266      */
267     public function getAll($_orderBy = 'id', $_orderDirection = 'ASC') 
268     {
269         throw new Tinebase_Exception_NotImplemented('not implemented');
270     }
271
272     /**
273      * returns period filter expressing blocking times caused by given event
274      *
275      * @param  Calendar_Model_Event         $event
276      * @param  array                        $checkPeriod array(
277             "from"  => DateTime  (defaults to dtstart)
278             "until" => DateTime  (defaults to dtstart + 2 years)
279             "max"   => Integer   (defaults to 25)
280         )
281      * @return Calendar_Model_EventFilter
282      */
283     public function getBlockingPeriods($event, $checkPeriod = array())
284     {
285         $eventSet = new Tinebase_Record_RecordSet('Calendar_Model_Event', array($event));
286
287         if (! empty($event->rrule)) {
288             try {
289                 $eventSet->merge($this->getRecurExceptions($event, true));
290             } catch (Tinebase_Exception_NotFound $e) {
291                 // it's ok, event is not exising yet so we don't have exceptions as well
292             }
293
294             $from = isset($checkPeriod['from']) ? $checkPeriod['from'] : clone $event->dtstart;
295             $until = isset($checkPeriod['until']) ? $checkPeriod['until'] : $from->getClone()->addMonth(24);
296             Calendar_Model_Rrule::mergeRecurrenceSet($eventSet, $from, $until);
297         }
298
299         $periodFilters = array();
300         foreach ($eventSet as $candidate) {
301             if ($candidate->transp != Calendar_Model_Event::TRANSP_TRANSP) {
302                 $periodFilters[] = array(
303                     'field' => 'period',
304                     'operator' => 'within',
305                     'value' => array(
306                         'from' => $candidate->dtstart,
307                         'until' => $candidate->dtend,
308                     ),
309                 );
310             }
311         }
312
313         $filter = new Calendar_Model_EventFilter($periodFilters, Tinebase_Model_Filter_FilterGroup::CONDITION_OR);
314
315         return $filter;
316     }
317
318     /**
319      * returns conflicting periods
320      *
321      * @param Calendar_Model_EventFilter $periodCandidates
322      * @param Calendar_Model_EventFilter $conflictCriteria
323      * @param bool                       $getAll
324      * @return array
325      */
326     public function getConflictingPeriods($periodCandidates, $conflictCriteria, $getAll=false)
327     {
328         $conflictFilter = clone $conflictCriteria;
329         $conflictFilter->addFilterGroup($periodCandidates);
330         $conflictCandidates = $this->search($conflictFilter);
331
332         $from = $until = false;
333         foreach ($periodCandidates as $periodFilter) {
334             $period = $periodFilter->getValue();
335             $from = $from ? min($from, $period['from']) : $period['from'];
336             $until = $until ?  max($until, $period['until']) : $period['until'];
337         }
338         Calendar_Model_Rrule::mergeRecurrenceSet($conflictCandidates, $from, $until);
339
340         $conflicts = array();
341         foreach ($periodCandidates as $periodFilter) {
342             $period = $periodFilter->getValue();
343
344             foreach($conflictCandidates as $event) {
345                 if ($event->dtstart->isEarlier($period['until']) && $event->dtend->isLater($period['from'])) {
346                     $conflicts[] = array(
347                         'from' => $period['from'],
348                         'until' => $period['until'],
349                         'event' => $event
350                     );
351
352                     if (! $getAll) {
353                         break;
354                     }
355                 }
356             }
357         }
358
359         return $conflicts;
360     }
361
362     /**
363      * @param Tinebase_Record_RecordSet $_records
364      * @return array
365      */
366     public function mergeFreeBusyInfo(Tinebase_Record_RecordSet $_records)
367     {
368         $_records->sort('dtstart');
369         $result = array();
370         /** @var Calendar_Model_Event $event */
371         foreach($_records as $event) {
372             foreach($result as $key => &$period) {
373                 if ($event->dtstart->isEarlierOrEquals($period['dtend'])) {
374                     if ($event->dtend->isLaterOrEquals($period['dtstart'])) {
375                         if ($event->dtstart->isEarlier($period['dtstart'])) {
376                             $period['dtstart'] = clone $event->dtstart;
377                         }
378                         if ($event->dtend->isLater($period['dtend'])) {
379                             $period['dtend'] = clone $event->dtend;
380                         }
381                         continue 2;
382                     } else {
383                         throw new Tinebase_Exception_UnexpectedValue('record set sort by dtstart did not work!');
384                     }
385                 }
386             }
387             $result[] = array(
388                 'dtstart' => $event->dtstart,
389                 'dtend' => $event->dtend
390             );
391         }
392
393         return $result;
394     }
395
396     /**
397      * returns freebusy information for given period and given attendee
398      * 
399      * @todo merge overlapping events to one freebusy entry
400      * 
401      * @param  Calendar_Model_EventFilter                           $_periods
402      * @param  Tinebase_Record_RecordSet                            $_attendee
403      * @param  array                                                $_ignoreUIDs
404      * @return Tinebase_Record_RecordSet of Calendar_Model_FreeBusy
405      */
406     public function getFreeBusyInfo($_periods, $_attendee, $_ignoreUIDs = array())
407     {
408         $fbInfoSet = new Tinebase_Record_RecordSet('Calendar_Model_FreeBusy');
409         
410         // map groupmembers to users
411         $attendee = clone $_attendee;
412         $groupmembers = $attendee->filter('user_type', Calendar_Model_Attender::USERTYPE_GROUPMEMBER);
413         $groupmembers->user_type = Calendar_Model_Attender::USERTYPE_USER;
414         /*$groups = $attendee->filter('user_type', Calendar_Model_Attender::USERTYPE_GROUP);
415         $attendee->removeRecords($groups);
416         /** @var Calendar_Model_Attender $group *
417         foreach($groups as $group) {
418             $group = Tinebase_Group::getInstance()->getGroupById($group->user_id);
419
420             // fetch list only if list_id is not NULL, otherwise we get back an empty list object
421             if (!empty($group->list_id)) {
422                 $contactList = Addressbook_Controller_List::getInstance()->get($group->list_id);
423                 foreach ($contactList->members as $member) {
424                     $attendee->addRecord(new Calendar_Model_Attender(array(
425                         'user_id' => $member,
426                         'user_type' => Calendar_Model_Attender::USERTYPE_USER
427                     ), true));
428                 }
429             }
430         }*/
431         
432         $conflictCriteria = new Calendar_Model_EventFilter(array(
433             array('field' => 'attender', 'operator' => 'in',     'value' => $attendee),
434             array('field' => 'transp',   'operator' => 'equals', 'value' => Calendar_Model_Event::TRANSP_OPAQUE)
435         ));
436
437         $conflictingPeriods = $this->getConflictingPeriods($_periods, $conflictCriteria, true);
438
439         // create a typemap
440         $typeMap = array();
441         foreach ($attendee as $attender) {
442             if (! isset($typeMap[$attender['user_type']])) {
443                 $typeMap[$attender['user_type']] = array();
444             }
445             if (is_object($attender['user_id'])) {
446                 $attender['user_id'] = $attender['user_id']->getId();
447             }
448             $typeMap[$attender['user_type']][$attender['user_id']] = array();
449         }
450         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . ' ' . __LINE__
451             . ' value: ' . print_r($typeMap, true));
452
453         // fetch resources to get freebusy type
454         // NOTE: we could add busy_type to attendee later
455         if (isset($typeMap[Calendar_Model_Attender::USERTYPE_RESOURCE])) {
456             $resources = Calendar_Controller_Resource::getInstance()->getMultiple(array_keys($typeMap[Calendar_Model_Attender::USERTYPE_RESOURCE]), true);
457         }
458
459         $processedEvents = array();
460
461         foreach ($conflictingPeriods as $conflictingPeriod) {
462             $event = $conflictingPeriod['event'];
463
464             // one event may conflict multiple periods
465             if (in_array($event, $processedEvents)) {
466                 continue;
467             }
468
469             $processedEvents[] = $event;
470
471             // skip events with ignoreUID
472             if (in_array($event->uid, $_ignoreUIDs)) {
473                 continue;
474             }
475
476             // map groupmembers to users
477             $groupmembers = $event->attendee->filter('user_type', Calendar_Model_Attender::USERTYPE_GROUPMEMBER);
478             $groupmembers->user_type = Calendar_Model_Attender::USERTYPE_USER;
479
480             foreach ($event->attendee as $attender) {
481                 // skip declined/transp events
482                 if ($attender->status == Calendar_Model_Attender::STATUS_DECLINED ||
483                     $attender->transp == Calendar_Model_Event::TRANSP_TRANSP) {
484                     continue;
485                 }
486
487                 if ((isset($typeMap[$attender->user_type]) || array_key_exists($attender->user_type, $typeMap)) && (isset($typeMap[$attender->user_type][$attender->user_id]) || array_key_exists($attender->user_id, $typeMap[$attender->user_type]))) {
488                     $type = Calendar_Model_FreeBusy::FREEBUSY_BUSY;
489
490                     if ($attender->user_type == Calendar_Model_Attender::USERTYPE_RESOURCE) {
491                         $resource = $resources->getById($attender->user_id);
492                         if ($resource) {
493                             $type = $resource->busy_type;
494                         }
495                     }
496
497                     $fbInfo = new Calendar_Model_FreeBusy(array(
498                         'user_type' => $attender->user_type,
499                         'user_id'   => $attender->user_id,
500                         'dtstart'   => clone $event->dtstart,
501                         'dtend'     => clone $event->dtend,
502                         'type'      => $type,
503                     ), true);
504                     
505                     if ($event->{Tinebase_Model_Grants::GRANT_READ}) {
506                         $fbInfo->event = clone $event;
507                         unset($fbInfo->event->attendee);
508                     }
509                     
510                     //$typeMap[$attender->user_type][$attender->user_id][] = $fbInfo;
511                     $fbInfoSet->addRecord($fbInfo);
512                 }
513             }
514         }
515         
516         return $fbInfoSet;
517     }
518
519     /**
520      * update future constraint exdates of a single event
521      *
522      * @param $_record
523      */
524     public function setConstraintsExdates($_record)
525     {
526         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
527             . ' event has rrule constrains, calculating exdates');
528
529         $exdates = is_array($_record->exdate) ? $_record->exdate : array();
530
531         // own event should not trigger constraints conflicts
532         if ($_record->rrule_constraints && $_record->rrule_constraints instanceof Calendar_Model_EventFilter) {
533             $constraints = clone $_record->rrule_constraints;
534             $constraints->addFilter(new Tinebase_Model_Filter_Text('uid', 'not', $_record->uid));
535
536             $constrainExdatePeriods = $this->getConflictingPeriods($this->getBlockingPeriods($_record), $constraints);
537             foreach ($constrainExdatePeriods as $constrainExdatePeriod) {
538                 $exdates[] = $constrainExdatePeriod['from'];
539             }
540         }
541
542         $_record->exdate = array_unique($exdates);
543     }
544
545     /**
546      * update all future constraints exdates
547      */
548     public function updateConstraintsExdates()
549     {
550         // find all future recur events with constraints (ignoring ACL's)
551         $constraintsEventIds = $this->_backend->search(new Calendar_Model_EventFilter(array(
552             array('field' => 'period', 'operator' => 'within', 'value' => array(
553                 'from' => Tinebase_DateTime::now(),
554                 'until' => Tinebase_DateTime::now()->addMonth(24)
555             )),
556             array('field' => 'rrule_contraints', 'operator' => 'notnull', 'value' => NULL)
557         )), NULL, 'id');
558
559         // update each
560         foreach ($constraintsEventIds as $constraintsEventId) {
561             try {
562                 $event = $this->_backend->get($constraintsEventId);
563                 $this->setConstraintsExdates($event);
564                 // NOTE: touch also updates
565                 $this->_touch($event);
566             } catch (Exception $e) {
567                 Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
568                     . " cannot update constraints exdates for event {$constraintsEventId}: " . $e->getMessage());
569                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
570                     . " cannot update constraints exdates for event {$constraintsEventId}: " . $e);
571             }
572         }
573     }
574
575     /**
576      * get list of records
577      *
578      * @param Tinebase_Model_Filter_FilterGroup             $_filter
579      * @param Tinebase_Model_Pagination                     $_pagination
580      * @param bool                                          $_getRelations
581      * @param boolean                                       $_onlyIds
582      * @param string                                        $_action for right/acl check
583      * @return Tinebase_Record_RecordSet|array
584      */
585     public function search(Tinebase_Model_Filter_FilterGroup $_filter = NULL, Tinebase_Model_Pagination $_pagination = NULL, $_getRelations = FALSE, $_onlyIds = FALSE, $_action = 'get')
586     {
587         $events = parent::search($_filter, $_pagination, $_getRelations, $_onlyIds, $_action);
588         if (! $_onlyIds) {
589             $this->_freeBusyCleanup($events, $_action);
590         }
591         
592         return $events;
593     }
594     
595     /**
596      * Returns a set of records identified by their id's
597      *
598      * @param   array $_ids       array of record identifiers
599      * @param   bool  $_ignoreACL don't check acl grants
600      * @return  Tinebase_Record_RecordSet of $this->_modelName
601      */
602     public function getMultiple($_ids, $_ignoreACL = false)
603     {
604         $events = parent::getMultiple($_ids, $_ignoreACL = false);
605         if ($_ignoreACL !== true) {
606             $this->_freeBusyCleanup($events, 'get');
607         }
608         
609         return $events;
610     }
611     
612     /**
613      * cleanup search results (freebusy)
614      * 
615      * @param Tinebase_Record_RecordSet $_events
616      * @param string $_action
617      */
618     protected function _freeBusyCleanup(Tinebase_Record_RecordSet $_events, $_action)
619     {
620         foreach ($_events as $event) {
621             $doFreeBusyCleanup = $event->doFreeBusyCleanup();
622             if ($doFreeBusyCleanup && $_action !== 'get') {
623                 $_events->removeRecord($event);
624             }
625         }
626     }
627
628     /**
629      * @param Calendar_Model_Event $_event with
630      *   attendee to find free timeslot for
631      *   dtstart, dtend -> to calculate duration
632      *   rrule optional
633      * @param array $_options
634      *  'from'         datetime (optional, defaults event->dtstart) from where to start searching
635      *  'until'        datetime (optional, defaults 2 years) until when to giveup searching
636      *  'constraints'  array    (optional, defaults to 8-20 'FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR') array of timespecs to limit the search with
637      *     timespec:
638      *       dtstart,
639      *       dtend,
640      *       rrule ... for example "work days" -> 'FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR'
641      * @return Tinebase_Record_RecordSet record set of event sugestions
642      * @throws Tinebase_Exception_NotImplemented
643      */
644     public function searchFreeTime($_event, $_options)
645     {
646         $functionTime = time();
647
648         // validate $_event, originator_tz will be validated by setTimezone() call
649         if (!isset($_event->dtstart) || !$_event->dtstart instanceof Tinebase_DateTime) {
650             throw new Tinebase_Exception_UnexpectedValue('dtstart needs to be set');
651         }
652         if (!isset($_event->dtstart) || !$_event->dtstart instanceof Tinebase_DateTime) {
653             throw new Tinebase_Exception_UnexpectedValue('dtend needs to be set');
654         }
655         if (!isset($_event->attendee) || !$_event->attendee instanceof Tinebase_Record_RecordSet ||
656                 $_event->attendee->count() < 1) {
657             throw new Tinebase_Exception_UnexpectedValue('attendee needs to be set and contain at least one attendee');
658         }
659
660         if (empty($_event->originator_tz)) {
661             $_event->originator_tz = Tinebase_Core::getUserTimezone();
662         }
663
664         $from = isset($_options['from']) ? ($_options['from'] instanceof Tinebase_DateTime ? $_options['from'] :
665             new Tinebase_DateTime($_options['from'])) : clone $_event->dtstart;
666         $until = isset($_options['until']) ? ($_options['until'] instanceof Tinebase_DateTime ? $_options['until'] :
667             new Tinebase_DateTime($_options['until'])) : $_event->dtend->getClone()->addYear(2);
668
669         $currentFrom = $from->getClone();
670         $currentUntil = $from->getClone()->addDay(6)->setTime(23, 59, 59);
671         if ($currentUntil->isLater($until)) {
672             $currentUntil = clone $until;
673         }
674         $durationSec = (int)$_event->dtend->getTimestamp() - (int)$_event->dtstart->getTimestamp();
675         $constraints = new Tinebase_Record_RecordSet('Calendar_Model_Event', array());
676         $exceptions = new Tinebase_Record_RecordSet('Calendar_Model_Event', array());
677
678         if (isset($_options['constraints'])) {
679             foreach ($_options['constraints'] as $constraint) {
680                 if (!isset($constraint['dtstart']) || !isset($constraint['dtend'])) {
681                     // LOG
682                     continue;
683                 }
684                 $constraint['uid'] = Tinebase_Record_Abstract::generateUID();
685                 $event = new Calendar_Model_Event(array(), true);
686                 $event->setFromJsonInUsersTimezone($constraint);
687                 $event->originator_tz = $_event->originator_tz;
688                 $constraints->addRecord($event);
689             }
690         }
691
692         if ($constraints->count() === 0) {
693             //here the timezone will come from the getClone, not need to set it
694             $constraints->addRecord(new Calendar_Model_Event(
695                 array(
696                     'uid'           => Tinebase_Record_Abstract::generateUID(),
697                     'dtstart'       => $currentFrom->getClone()->setHour(8)->setMinute(0)->setSecond(0),
698                     'dtend'         => $currentFrom->getClone()->setHour(20)->setMinute(0)->setSecond(0),
699                     'rrule'         => 'FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR',
700                     'originator_tz' => $_event->originator_tz
701                 ), true)
702             );
703         }
704
705         do {
706             if (time() - $functionTime > 23) {
707                 $exception = new Calendar_Exception_AttendeeBusy();
708                 $exception->setEvent(new Calendar_Model_Event(array('dtend' => $currentFrom), true));
709                 throw $exception;
710             }
711
712             $currentConstraints = clone $constraints;
713             Calendar_Model_Rrule::mergeRecurrenceSet($currentConstraints, $currentFrom, $currentUntil);
714             $currentConstraints->sort('dtstart');
715             $remove = array();
716
717             // sort out constraints that do not fit the rrule
718             if (!empty($_event->rrule)) {
719                 /** @var Calendar_Model_Event $event */
720                 foreach ($currentConstraints as $event) {
721                     $recurEvent = clone $_event;
722                     $recurEvent->uid = Tinebase_Record_Abstract::generateUID();
723                     $recurEvent->dtstart = $event->dtstart->getClone()->subDay(1);
724                     if ($_event->is_all_day_event) {
725                         $recurEvent->dtend = $event->dtend->getClone()->subDay(1);
726                     } else {
727                         $recurEvent->dtend = $recurEvent->dtstart->getClone()->addSecond($durationSec);
728                     }
729                     if (null === ($recurEvent = Calendar_Model_Rrule::computeNextOccurrence($recurEvent, $exceptions, $event->dtstart))
730                             || $recurEvent->dtstart->isLater($event->dtend)) {
731                         $remove[] = $event;
732                     }
733                 }
734                 foreach($remove as $event) {
735                     $currentConstraints->removeRecord($event);
736                 }
737             }
738
739             if ($currentConstraints->count() > 0) {
740                 $periods = array();
741                 /** @var Calendar_Model_Event $event */
742                 foreach ($currentConstraints as $event) {
743                     $periods[] = array(
744                         'field' => 'period',
745                         'operator' => 'within',
746                         'value' => array(
747                             'from' => $event->dtstart,
748                             'until' => $event->dtend
749                         ),
750                     );
751                 }
752
753                 $busySlots = $this->getFreeBusyInfo(new Calendar_Model_EventFilter($periods, Tinebase_Model_Filter_FilterGroup::CONDITION_OR), $_event->attendee);
754                 $busySlots = $this->mergeFreeBusyInfo($busySlots);
755
756                 /** @var Calendar_Model_Event $event */
757                 foreach ($currentConstraints as $event) {
758                     if ($event->dtend->isEarlierOrEquals($currentFrom)) {
759                         continue;
760                     }
761
762                     if ($_event->is_all_day_event) {
763                         $durationSec = (int)$event->dtend->getTimestamp() - (int)$event->dtstart->getTimestamp();
764                     }
765
766                     $constraintStart = (int)$event->dtstart->getTimestamp();
767                     if ($constraintStart < (int)$currentFrom->getTimestamp()) {
768                         $constraintStart = (int)$currentFrom->getTimestamp();
769                     }
770                     $constraintEnd = (int)$event->dtend->getTimestamp();
771                     if ($constraintEnd > (int)$currentUntil->getTimestamp()) {
772                         $constraintEnd = (int)$currentUntil->getTimestamp();
773                     }
774                     $lastBusyEnd = $constraintStart;
775                     $remove = array();
776                     /** @var Calendar_Model_FreeBusy $busy */
777                     foreach ($busySlots as $key => $busy) {
778                         $busyStart = (int)$busy['dtstart']->getTimestamp();
779                         $busyEnd = (int)$busy['dtend']->getTimestamp();
780
781                         if ($busyEnd < $constraintStart) {
782                             $remove[] = $key;
783                             continue;
784                         }
785
786                         if ($busyStart > ($constraintEnd - $durationSec)) {
787                             $lastBusyEnd = $busyEnd;
788                             break;
789                         }
790
791                         if (($lastBusyEnd + $durationSec) <= $busyStart) {
792                             // check between $lastBusyEnd and $busyStart
793                             $result = $this->_tryForFreeSlot($_event, $lastBusyEnd, $busyStart, $durationSec, $until);
794                             if ($result->count() > 0) {
795                                 if ($_event->is_all_day_event) {
796                                     $result->getFirstRecord()->dtstart = $_event->dtstart;
797                                     $result->getFirstRecord()->dtend = $_event->dtend;
798                                 }
799                                 return $result;
800                             }
801                         }
802                         $lastBusyEnd = $busyEnd;
803                     }
804                     foreach ($remove as $key) {
805                         unset($busySlots[$key]);
806                     }
807
808                     if (($lastBusyEnd + $durationSec) <= $constraintEnd) {
809                         // check between $lastBusyEnd and $constraintEnd
810                         $result = $this->_tryForFreeSlot($_event, $lastBusyEnd, $constraintEnd, $durationSec, $until);
811                         if ($result->count() > 0) {
812                             if ($_event->is_all_day_event) {
813                                 $result->getFirstRecord()->dtstart = $_event->dtstart;
814                                 $result->getFirstRecord()->dtend = $_event->dtend;
815                             }
816                             return $result;
817                         }
818                     }
819                 }
820             }
821
822             $currentFrom->addDay(7)->setTime(0, 0, 0);
823             $currentUntil->addDay(7);
824             if ($currentUntil->isLater($until)) {
825                 $currentUntil = clone $until;
826             }
827         } while ($until->isLater($currentFrom));
828
829         return new Tinebase_Record_RecordSet('Calendar_Model_Event', array());
830     }
831
832     protected function _tryForFreeSlot(Calendar_Model_Event $_event, $_startSec, $_endSec, $_durationSec, Tinebase_DateTime $_until)
833     {
834         $event = new Calendar_Model_Event(array(
835             'uid'           => Tinebase_Record_Abstract::generateUID(),
836             'dtstart'       => new Tinebase_DateTime($_startSec),
837             'dtend'         => new Tinebase_DateTime($_startSec + $_durationSec),
838             'originator_tz' => $_event->originator_tz,
839         ), true);
840         $result = new Tinebase_Record_RecordSet('Calendar_Model_Event', array($event));
841
842         if (!empty($_event->rrule)) {
843             $event->rrule = $_event->rrule;
844             do {
845                 $until = $event->dtstart->getClone()->addMonth(2);
846                 if ($until->isLater($_until)) {
847                     $until = $_until;
848                 }
849                 $periods = $this->getBlockingPeriods($event, array(
850                     'from'  => $event->dtstart,
851                     'until' => $until
852                 ));
853                 $busySlots = $this->getFreeBusyInfo($periods, $_event->attendee);
854                 $event->dtstart->addMinute(15);
855                 $event->dtend->addMinute(15);
856             } while($busySlots->count() > 0 && $event->dtend->getTimestamp() <= $_endSec && $event->dtend->isEarlierOrEquals($_until));
857
858             if ($busySlots->count() > 0) {
859                 $result->removeAll();
860             } else {
861                 $event->dtstart->subMinute(15);
862                 $event->dtend->subMinute(15);
863             }
864         }
865
866         return $result;
867     }
868     
869     /**
870      * update one record
871      *
872      * @param   Tinebase_Record_Interface $_record
873      * @param   bool                      $_checkBusyConflicts
874      * @param   string                    $range
875      * @return  Tinebase_Record_Interface
876      * @throws  Tinebase_Exception_AccessDenied
877      * @throws  Tinebase_Exception_Record_Validation
878      */
879     public function update(Tinebase_Record_Interface $_record, $_checkBusyConflicts = FALSE, $range = Calendar_Model_Event::RANGE_THIS, $skipEvent = false)
880     {
881         /** @var Calendar_Model_Event $_record */
882         try {
883             $db = $this->_backend->getAdapter();
884             $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
885             
886             $sendNotifications = $this->sendNotifications(FALSE);
887
888             $event = $this->get($_record->getId());
889             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
890                     .' Going to update the following event. rawdata: ' . print_r($event->toArray(), true));
891
892             //NOTE we check via get(full rights) here whereas _updateACLCheck later checks limited rights from search
893             if ($this->_doContainerACLChecks === FALSE || $event->hasGrant(Tinebase_Model_Grants::GRANT_EDIT)) {
894                 Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " updating event: {$_record->id} (range: {$range})");
895                 
896                 // we need to resolve groupmembers before free/busy checking
897                 Calendar_Model_Attender::resolveGroupMembers($_record->attendee);
898                 $this->_inspectEvent($_record, $skipEvent);
899                
900                 if ($_checkBusyConflicts) {
901                     if ($event->isRescheduled($_record) ||
902                         count(array_diff($_record->attendee->user_id, $event->attendee->user_id)) > 0
903                     ) {
904                         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
905                             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
906                                 . " Ensure that all attendee are free with free/busy check ... ");
907                         }
908                         $this->checkBusyConflicts($_record);
909                     } else {
910                         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
911                             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
912                                 . " Skipping free/busy check because event has not been rescheduled and no new attender has been added");
913                         }
914                     }
915                 }
916
917                 parent::update($_record);
918                 
919             } else if ($_record->attendee instanceof Tinebase_Record_RecordSet) {
920                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
921                     . " user has no editGrant for event: {$_record->id}, updating attendee status with valid authKey only");
922                 foreach ($_record->attendee as $attender) {
923                     if ($attender->status_authkey) {
924                         $this->attenderStatusUpdate($_record, $attender, $attender->status_authkey);
925                     }
926                 }
927             }
928
929             if ($_record->isRecurException() && in_array($range, array(Calendar_Model_Event::RANGE_ALL, Calendar_Model_Event::RANGE_THISANDFUTURE))) {
930                 $this->_updateExdateRange($_record, $range, $event);
931             }
932
933             Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
934         } catch (Exception $e) {
935             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Rolling back because: ' . $e);
936             Tinebase_TransactionManager::getInstance()->rollBack();
937             $this->sendNotifications($sendNotifications);
938             throw $e;
939         }
940         
941         $updatedEvent = $this->get($event->getId());
942         
943         // send notifications
944         $this->sendNotifications($sendNotifications);
945         if ($this->_sendNotifications && $_record->mute != 1) {
946             $this->doSendNotifications($updatedEvent, Tinebase_Core::getUser(), 'changed', $event);
947         }
948         return $updatedEvent;
949     }
950     
951     /**
952      * inspect update of one record (after update)
953      *
954      * @param   Tinebase_Record_Interface $updatedRecord   the just updated record
955      * @param   Tinebase_Record_Interface $record          the update record
956      * @param   Tinebase_Record_Interface $currentRecord   the current record (before update)
957      * @return  void
958      */
959     protected function _inspectAfterUpdate($updatedRecord, $record, $currentRecord)
960     {
961         $this->_saveAttendee($record, $currentRecord, $record->isRescheduled($currentRecord));
962         // need to save new attendee set in $updatedRecord for modlog
963         $updatedRecord->attendee = clone($record->attendee);
964     }
965     
966     /**
967      * update range of events starting with given recur exception
968      * 
969      * @param Calendar_Model_Event $exdate
970      * @param string $range
971      */
972     protected function _updateExdateRange($exdate, $range, $oldExdate)
973     {
974         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
975             . ' Updating events (range: ' . $range . ') belonging to recur exception event ' . $exdate->getId());
976         
977         $baseEvent = $this->getRecurBaseEvent($exdate);
978         /** @var Tinebase_Record_Diff $diff */
979         $diff = $oldExdate->diff($exdate);
980         
981         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
982             . ' Exdate diff: ' . print_r($diff->toArray(), TRUE));
983         
984         if ($range === Calendar_Model_Event::RANGE_ALL) {
985             $events = $this->getRecurExceptions($baseEvent);
986             $events->addRecord($baseEvent);
987             $this->_applyExdateDiffToRecordSet($exdate, $diff, $events);
988         } else if ($range === Calendar_Model_Event::RANGE_THISANDFUTURE) {
989             $nextRegularRecurEvent = Calendar_Model_Rrule::computeNextOccurrence($baseEvent, new Tinebase_Record_RecordSet('Calendar_Model_Event'), $exdate->dtstart);
990             
991             if ($nextRegularRecurEvent == $baseEvent) {
992                 // NOTE if a fist instance exception takes place before the
993                 //      series would start normally, $nextOccurence is the
994                 //      baseEvent of the series. As createRecurException can't
995                 //      deal with this situation we update whole series here
996                 $this->_updateExdateRange($exdate, Calendar_Model_Event::RANGE_ALL, $oldExdate);
997             } else if ($nextRegularRecurEvent !== NULL && ! $nextRegularRecurEvent->dtstart->isEarlier($exdate->dtstart)) {
998                 $this->_applyDiff($nextRegularRecurEvent, $diff, $exdate, FALSE);
999                 
1000                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1001                     . ' Next recur exception event at: ' . $nextRegularRecurEvent->dtstart->toString());
1002                 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
1003                     . ' ' . print_r($nextRegularRecurEvent->toArray(), TRUE));
1004                 
1005                 $nextRegularRecurEvent->mute = $exdate->mute;
1006                 $newBaseEvent = $this->createRecurException($nextRegularRecurEvent, FALSE, TRUE);
1007                 // @todo this should be done by createRecurException
1008                 $exdatesOfNewBaseEvent = $this->getRecurExceptions($newBaseEvent);
1009                 $this->_applyExdateDiffToRecordSet($exdate, $diff, $exdatesOfNewBaseEvent);
1010             } else {
1011                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1012                     . ' No upcoming occurrences found.');
1013             }
1014         }
1015     }
1016
1017     protected function _applyDTStartToBaseEventRRULE($_dtstart, $_baseEvent)
1018     {
1019         /** @var Calendar_Model_Rrule $rrule */
1020         /*$rrule = $_baseEvent->rrule;
1021         if (! $rrule instanceof Calendar_Model_Rrule) {
1022             $rrule = new Calendar_Model_Rrule($rrule);
1023         }
1024
1025         switch($rrule->freq)
1026         {
1027             case Calendar_Model_Rrule::FREQ_DAILY
1028         }
1029
1030         if ($rrule->freq == Calendar_Model_Rrule::FREQ_WEEKLY) {
1031
1032         }
1033
1034         if ($rrule->freq == Calendar_Model_Rrule::FREQ_MONTHLY) {
1035             if (!empty($rrule->byday)) {
1036
1037             } elseif(!empty($rrule->bymonthday)) {
1038
1039             }
1040         }
1041
1042         if ($rrule->freq == Calendar_Model_Rrule::FREQ_YEARLY) {
1043             // bymonthday + bymonth
1044         }
1045
1046         switch($rrule->byday)
1047         {
1048
1049         }*/
1050     }
1051     
1052     /**
1053      * apply exdate diff to a recordset of events
1054      * 
1055      * @param Calendar_Model_Event $exdate
1056      * @param Tinebase_Record_Diff $diff
1057      * @param Tinebase_Record_RecordSet $events
1058      */
1059     protected function _applyExdateDiffToRecordSet($exdate, $diff, $events)
1060     {
1061         // make sure baseEvent gets updated first to circumvent concurrency conflicts
1062         $events->sort('recurdid', 'ASC');
1063
1064         foreach ($events as $event) {
1065             if ($event->getId() === $exdate->getId()) {
1066                 // skip the exdate
1067                 continue;
1068             }
1069             $this->_applyDiff($event, $diff, $exdate, FALSE);
1070             $this->update($event);
1071         }
1072     }
1073     
1074     /**
1075      * merge updates from exdate into event
1076      * 
1077      * @param Calendar_Model_Event $event
1078      * @param Tinebase_Record_Diff $diff
1079      * @param Calendar_Model_Event $exdate
1080      * @param boolean $overwriteMods
1081      * 
1082      * @todo is $overwriteMods needed?
1083      */
1084     protected function _applyDiff($event, $diff, $exdate, $overwriteMods = TRUE)
1085     {
1086         if (! $overwriteMods) {
1087             $recentChanges = Tinebase_Timemachine_ModificationLog::getInstance()->getModifications('Calendar', $event, NULL, 'Sql', $exdate->creation_time)->filter('change_type', Tinebase_Timemachine_ModificationLog::UPDATED);
1088             if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
1089                 . ' Recent changes (since ' . $exdate->creation_time->toString() . '): ' . print_r($recentChanges->toArray(), TRUE));
1090         } else {
1091             $recentChanges = new Tinebase_Record_RecordSet('Tinebase_Model_ModificationLog');
1092         }
1093
1094         $changedAttributes = Tinebase_Timemachine_ModificationLog::getModifiedAttributes($recentChanges);
1095         $diffIgnore = array('organizer', 'seq', 'last_modified_by', 'last_modified_time', 'dtstart', 'dtend');
1096         foreach ($diff->diff as $key => $newValue) {
1097             if ($key === 'attendee') {
1098                 if (in_array($key, $changedAttributes)) {
1099                     $attendeeDiff = $diff->diff['attendee'];
1100                     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
1101                         . ' Attendee diff: ' . print_r($attendeeDiff->toArray(), TRUE));
1102                     foreach ($attendeeDiff['added'] as $attenderToAdd) {
1103                         $attenderToAdd->setId(NULL);
1104                         $event->attendee->addRecord($attenderToAdd);
1105                     }
1106                     foreach ($attendeeDiff['removed'] as $attenderToRemove) {
1107                         $attenderInCurrentSet = Calendar_Model_Attender::getAttendee($event->attendee, $attenderToRemove);
1108                         if ($attenderInCurrentSet) {
1109                             $event->attendee->removeRecord($attenderInCurrentSet);
1110                         }
1111                     }
1112                 } else {
1113                     // remove ids of new attendee
1114                     $attendee = clone($exdate->attendee);
1115                     foreach ($attendee as $attender) {
1116                         if (! $event->attendee->getById($attender->getId())) {
1117                             $attender->setId(NULL);
1118                         }
1119                     }
1120                     $event->attendee = $attendee;
1121                 }
1122             } else if (! in_array($key, $diffIgnore) && ! in_array($key, $changedAttributes)) {
1123                 $event->{$key} = $exdate->{$key};
1124             } else {
1125                 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
1126                     . ' Ignore / recently changed: ' . $key);
1127             }
1128         }
1129         
1130         if ((isset($diff->diff['dtstart']) || array_key_exists('dtstart', $diff->diff)) || (isset($diff->diff['dtend']) || array_key_exists('dtend', $diff->diff))) {
1131             $this->_applyTimeDiff($event, $exdate);
1132         }
1133     }
1134     
1135     /**
1136      * update multiple records
1137      * 
1138      * @param   Tinebase_Model_Filter_FilterGroup $_filter
1139      * @param   array $_data
1140      * @return  integer number of updated records
1141      */
1142     public function updateMultiple($_filter, $_data)
1143     {
1144         $this->_checkRight('update');
1145         $this->checkFilterACL($_filter, 'update');
1146         
1147         // get only ids
1148         $ids = $this->_backend->search($_filter, NULL, TRUE);
1149         
1150         foreach ($ids as $eventId) {
1151             $event = $this->get($eventId);
1152             foreach ($_data as $field => $value) {
1153                 $event->$field = $value;
1154             }
1155             
1156             $this->update($event);
1157         }
1158         
1159         return count($ids);
1160     }
1161     
1162     /**
1163      * Deletes a set of records.
1164      * 
1165      * If one of the records could not be deleted, no record is deleted
1166      * 
1167      * @param   array $_ids array of record identifiers
1168      * @param   string $range
1169      * @return  NULL
1170      * @throws Tinebase_Exception_NotFound|Tinebase_Exception
1171      */
1172     public function delete($_ids, $range = Calendar_Model_Event::RANGE_THIS)
1173     {
1174         if ($_ids instanceof $this->_modelName) {
1175             $_ids = (array)$_ids->getId();
1176         }
1177         
1178         $records = $this->_backend->getMultiple((array) $_ids);
1179         
1180         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1181             . " Deleting " . count($records) . ' with range ' . $range . ' ...');
1182         
1183         foreach ($records as $record) {
1184             if ($record->isRecurException() && in_array($range, array(Calendar_Model_Event::RANGE_ALL, Calendar_Model_Event::RANGE_THISANDFUTURE))) {
1185                 $this->_deleteExdateRange($record, $range);
1186             }
1187             
1188             try {
1189                 $db = $this->_backend->getAdapter();
1190                 $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
1191                 
1192                 // delete if delete grant is present
1193                 if ($this->_doContainerACLChecks === FALSE || $record->hasGrant(Tinebase_Model_Grants::GRANT_DELETE)) {
1194                     // NOTE delete needs to update sequence otherwise iTIP based protocolls ignore the delete
1195                     $record->status = Calendar_Model_Event::STATUS_CANCELED;
1196                     $this->_touch($record);
1197                     if ($record->isRecurException()) {
1198                         try {
1199                             $baseEvent = $this->getRecurBaseEvent($record);
1200                             $this->_touch($baseEvent);
1201                         } catch (Tinebase_Exception_NotFound $tnfe) {
1202                             // base Event might be gone already
1203                             if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__
1204                                 . " BaseEvent of exdate {$record->uid} to delete not found ");
1205
1206                         }
1207                     }
1208                     parent::delete($record);
1209                 }
1210                 
1211                 // otherwise update status for user to DECLINED
1212                 else if ($record->attendee instanceof Tinebase_Record_RecordSet) {
1213                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " user has no deleteGrant for event: " . $record->id . ", updating own status to DECLINED only");
1214                     $ownContact = Tinebase_Core::getUser()->contact_id;
1215                     foreach ($record->attendee as $attender) {
1216                         if ($attender->user_id == $ownContact && in_array($attender->user_type, array(Calendar_Model_Attender::USERTYPE_USER, Calendar_Model_Attender::USERTYPE_GROUPMEMBER))) {
1217                             $attender->status = Calendar_Model_Attender::STATUS_DECLINED;
1218                             $this->attenderStatusUpdate($record, $attender, $attender->status_authkey);
1219                         }
1220                     }
1221                 }
1222                 
1223                 // increase display container content sequence for all attendee of deleted event
1224                 if ($record->attendee instanceof Tinebase_Record_RecordSet) {
1225                     foreach ($record->attendee as $attender) {
1226                         $this->_increaseDisplayContainerContentSequence($attender, $record, Tinebase_Model_ContainerContent::ACTION_DELETE);
1227                     }
1228                 }
1229                 
1230                 Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
1231             } catch (Exception $e) {
1232                 Tinebase_TransactionManager::getInstance()->rollBack();
1233                 throw $e;
1234             }
1235         }
1236     }
1237     
1238     /**
1239      * delete range of events starting with given recur exception
1240      *
1241      * NOTE: if exdate is persistent, it will not be deleted by this function
1242      *       but by the original call of delete
1243      *
1244      * @param Calendar_Model_Event $exdate
1245      * @param string $range
1246      */
1247     protected function _deleteExdateRange($exdate, $range)
1248     {
1249         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1250             . ' Deleting events (range: ' . $range . ') belonging to recur exception event ' . $exdate->getId());
1251         
1252         $baseEvent = $this->getRecurBaseEvent($exdate);
1253         
1254         if ($range === Calendar_Model_Event::RANGE_ALL) {
1255             $this->deleteRecurSeries($exdate);
1256         } else if ($range === Calendar_Model_Event::RANGE_THISANDFUTURE) {
1257             $nextRegularRecurEvent = Calendar_Model_Rrule::computeNextOccurrence($baseEvent, new Tinebase_Record_RecordSet('Calendar_Model_Event'), $exdate->dtstart);
1258             
1259             if ($nextRegularRecurEvent == $baseEvent) {
1260                 // NOTE if a fist instance exception takes place before the
1261                 //      series would start normally, $nextOccurence is the
1262                 //      baseEvent of the series. As createRecurException can't
1263                 //      deal with this situation we delete whole series here
1264                 $this->_deleteExdateRange($exdate, Calendar_Model_Event::RANGE_ALL);
1265             } else {
1266                 $this->createRecurException($nextRegularRecurEvent, TRUE, TRUE);
1267             }
1268         }
1269     }
1270     
1271     /**
1272      * updates a recur series
1273      *
1274      * @param  Calendar_Model_Event $_recurInstance
1275      * @param  bool                 $_checkBusyConflicts
1276      * @return Calendar_Model_Event
1277      */
1278     public function updateRecurSeries($_recurInstance, $_checkBusyConflicts = FALSE)
1279     {
1280         $baseEvent = $this->getRecurBaseEvent($_recurInstance);
1281
1282         $originalDtStart = $_recurInstance->getOriginalDtStart();
1283         $originalDtStart->setTimezone(Tinebase_DateTime::TIMEZONE_UTC);
1284         $dtStart = $_recurInstance->dtstart;
1285         if (! $dtStart instanceof Tinebase_DateTime) {
1286             $dtStart = new Tinebase_DateTime($dtStart);
1287         }
1288         $dtStart->setTimezone(Tinebase_DateTime::TIMEZONE_UTC);
1289         $dtEnd = $_recurInstance->dtEnd;
1290         if (! $dtEnd instanceof Tinebase_DateTime) {
1291             $dtEnd = new Tinebase_DateTime($dtEnd);
1292         }
1293         $dtEnd->setTimezone(Tinebase_DateTime::TIMEZONE_UTC);
1294
1295         if ($originalDtStart->compare($dtStart) !== 0 ||
1296             (($orgDiff = $baseEvent->dtend->diff($baseEvent->dtstart)) &&
1297                 ($newDiff = $dtEnd->diff($dtStart)) &&
1298                 (
1299                     $orgDiff->days !== $newDiff->days ||
1300                     $orgDiff->h !== $newDiff->h ||
1301                     $orgDiff->m !== $newDiff->m ||
1302                     $orgDiff->s !== $newDiff->s
1303                 )
1304             )) {
1305             if (strpos($baseEvent->rrule->byday, ',') !== false ||
1306                 strpos($baseEvent->rrule->bymonthday, ',') !== false ) {
1307                 throw new Tinebase_Exception_UnexpectedValue('dont change complex stuff like that');
1308             }
1309         }
1310
1311         // replace baseEvent with adopted instance
1312         $newBaseEvent = clone $_recurInstance;
1313         $newBaseEvent->setId($baseEvent->getId());
1314         unset($newBaseEvent->recurid);
1315         $newBaseEvent->exdate = $baseEvent->exdate;
1316         
1317         $this->_applyTimeDiff($newBaseEvent, $_recurInstance, $baseEvent);
1318         
1319         return $this->update($newBaseEvent, $_checkBusyConflicts);
1320     }
1321     
1322     /**
1323      * apply time diff
1324      * 
1325      * @param Calendar_Model_Event $newEvent
1326      * @param Calendar_Model_Event $fromEvent
1327      * @param Calendar_Model_Event $baseEvent
1328      */
1329     protected function _applyTimeDiff($newEvent, $fromEvent, $baseEvent = NULL)
1330     {
1331         if (! $baseEvent) {
1332             $baseEvent = $newEvent;
1333         }
1334         
1335         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
1336             . ' New event: ' . print_r($newEvent->toArray(), TRUE));
1337         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
1338             . ' From event: ' . print_r($fromEvent->toArray(), TRUE));
1339         
1340         // compute time diff (NOTE: if the $fromEvent is the baseEvent, it has no recurid)
1341         $originalDtStart = $fromEvent->recurid ? new Tinebase_DateTime(substr($fromEvent->recurid, -19), 'UTC') : clone $baseEvent->dtstart;
1342         
1343         $dtstartDiff = $originalDtStart->diff($fromEvent->dtstart);
1344         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1345             . " Dtstart diff: " . $dtstartDiff->format('%H:%M:%i'));
1346         $eventDuration = $fromEvent->dtstart->diff($fromEvent->dtend);
1347         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1348             . " Duration diff: " . $dtstartDiff->format('%H:%M:%i'));
1349         
1350         $newEvent->dtstart = clone $baseEvent->dtstart;
1351         $newEvent->dtstart->add($dtstartDiff);
1352         
1353         $newEvent->dtend = clone $newEvent->dtstart;
1354         $newEvent->dtend->add($eventDuration);
1355     }
1356     
1357     /**
1358      * creates an exception instance of a recurring event
1359      *
1360      * NOTE: deleting persistent exceptions is done via a normal delete action
1361      *       and handled in the deleteInspection
1362      * 
1363      * @param  Calendar_Model_Event  $_event
1364      * @param  bool                  $_deleteInstance
1365      * @param  bool                  $_allFollowing
1366      * @param  bool                  $_checkBusyConflicts
1367      * @return Calendar_Model_Event  exception Event | updated baseEvent
1368      * 
1369      * @todo replace $_allFollowing param with $range
1370      * @deprecated replace with create/update/delete
1371      */
1372     public function createRecurException($_event, $_deleteInstance = FALSE, $_allFollowing = FALSE, $_checkBusyConflicts = FALSE)
1373     {
1374         $baseEvent = $this->getRecurBaseEvent($_event);
1375         
1376         if ($baseEvent->last_modified_time != $_event->last_modified_time) {
1377             if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__
1378                 . " It is not allowed to create recur instance if it is clone of base event");
1379             throw new Tinebase_Timemachine_Exception_ConcurrencyConflict('concurrency conflict!');
1380         }
1381
1382 //        // Maybe Later
1383 //        // exdates needs to stay in baseEvents container
1384 //        if ($_event->container_id != $baseEvent->container_id) {
1385 //            throw new Calendar_Exception_ExdateContainer();
1386 //        }
1387
1388         // check if this is an exception to the first occurence
1389         if ($baseEvent->getId() == $_event->getId()) {
1390             if ($_allFollowing) {
1391                 throw new Exception('please edit or delete complete series!');
1392             }
1393             // NOTE: if the baseEvent gets a time change, we can't compute the recurdid w.o. knowing the original dtstart
1394             $recurid = $baseEvent->setRecurId($baseEvent->getId());
1395             unset($baseEvent->recurid);
1396             $_event->recurid = $recurid;
1397         }
1398         
1399         // just do attender status update if user has no edit grant
1400         if ($this->_doContainerACLChecks && !$baseEvent->{Tinebase_Model_Grants::GRANT_EDIT}) {
1401             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1402                 . " user has no editGrant for event: '{$baseEvent->getId()}'. Only creating exception for attendee status");
1403             if ($_event->attendee instanceof Tinebase_Record_RecordSet) {
1404                 foreach ($_event->attendee as $attender) {
1405                     if ($attender->status_authkey) {
1406                         $exceptionAttender = $this->attenderStatusCreateRecurException($_event, $attender, $attender->status_authkey, $_allFollowing);
1407                     }
1408                 }
1409             }
1410             
1411             if (! isset($exceptionAttender)) {
1412                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG) && $_event->attendee instanceof Tinebase_Record_RecordSet) {
1413                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " Failed to update attendee: " . print_r($_event->attendee->toArray(), true));
1414                 }
1415                 throw new Tinebase_Exception_AccessDenied('Failed to update attendee, status authkey might be missing');
1416             }
1417             
1418             return $this->get($exceptionAttender->cal_event_id);
1419         }
1420         
1421         // NOTE: recurid is computed by rrule recur computations and therefore is already part of the event.
1422         if (empty($_event->recurid)) {
1423             throw new Exception('recurid must be present to create exceptions!');
1424         }
1425         
1426         // we do notifications ourself
1427         $sendNotifications = $this->sendNotifications(FALSE);
1428         
1429         // EDIT for baseEvent is checked above, CREATE, DELETE for recur exceptions is implied with it
1430         $doContainerACLChecks = $this->doContainerACLChecks(FALSE);
1431         
1432         $db = $this->_backend->getAdapter();
1433         $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
1434         
1435         $exdate = new Tinebase_DateTime(substr($_event->recurid, -19));
1436         $exdates = is_array($baseEvent->exdate) ? $baseEvent->exdate : array();
1437         $originalDtstart = $_event->getOriginalDtStart();
1438         $originalEvent = Calendar_Model_Rrule::computeNextOccurrence($baseEvent, new Tinebase_Record_RecordSet('Calendar_Model_Event'), $originalDtstart);
1439         
1440         if ($_allFollowing != TRUE) {
1441             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
1442                 . " Adding exdate for: '{$_event->recurid}'");
1443             
1444             array_push($exdates, $exdate);
1445             $baseEvent->exdate = $exdates;
1446             $updatedBaseEvent = $this->update($baseEvent, FALSE);
1447             
1448             if ($_deleteInstance == FALSE) {
1449                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
1450                     . " Creating persistent exception for: '{$_event->recurid}'");
1451                 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ 
1452                     . " Recur exception: " . print_r($_event->toArray(), TRUE));
1453
1454                 $_event->base_event_id = $baseEvent->getId();
1455                 $_event->setId(NULL);
1456                 unset($_event->rrule);
1457                 unset($_event->exdate);
1458             
1459                 foreach (array('attendee', 'notes', 'alarms') as $prop) {
1460                     if ($_event->{$prop} instanceof Tinebase_Record_RecordSet) {
1461                         $_event->{$prop}->setId(NULL);
1462                     }
1463                 }
1464                 
1465                 $originalDtstart = $_event->getOriginalDtStart();
1466                 $dtStartHasDiff = $originalDtstart->compare($_event->dtstart) != 0; // php52 compat
1467                 
1468                 if (! $dtStartHasDiff) {
1469                     $attendees = $_event->attendee;
1470                     unset($_event->attendee);
1471                 }
1472                 $note = $_event->notes;
1473                 unset($_event->notes);
1474                 $persistentExceptionEvent = $this->create($_event, $_checkBusyConflicts);
1475                 
1476                 if (! $dtStartHasDiff) {
1477                     // we save attendee seperatly to preserve their attributes
1478                     if ($attendees instanceof Tinebase_Record_RecordSet) {
1479                         $attendees->cal_event_id = $persistentExceptionEvent->getId();
1480                         $calendar = Tinebase_Container::getInstance()->getContainerById($_event->container_id);
1481                         foreach ($attendees as $attendee) {
1482                             $this->_createAttender($attendee, $_event, TRUE, $calendar);
1483                             $this->_increaseDisplayContainerContentSequence($attendee, $persistentExceptionEvent, Tinebase_Model_ContainerContent::ACTION_CREATE);
1484                         }
1485                     }
1486                 }
1487                 
1488                 // @todo save notes and add a update note -> what was updated? -> modlog is also missing
1489                 $persistentExceptionEvent = $this->get($persistentExceptionEvent->getId());
1490             }
1491             
1492         } else {
1493             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " shorten recur series for/to: '{$_event->recurid}'");
1494                 
1495             // split past/future exceptions
1496             $pastExdates = array();
1497             $futureExdates = array();
1498             foreach($exdates as $exdate) {
1499                 $exdate->isLater($_event->dtstart) ? $futureExdates[] = $exdate : $pastExdates[] = $exdate;
1500             }
1501             
1502             $persistentExceptionEvents = $this->getRecurExceptions($_event);
1503             $pastPersistentExceptionEvents = new Tinebase_Record_RecordSet('Calendar_Model_Event');
1504             $futurePersistentExceptionEvents = new Tinebase_Record_RecordSet('Calendar_Model_Event');
1505             foreach ($persistentExceptionEvents as $persistentExceptionEvent) {
1506                 $persistentExceptionEvent->getOriginalDtStart()->isLater($_event->dtstart) ?
1507                     $futurePersistentExceptionEvents->addRecord($persistentExceptionEvent) :
1508                     $pastPersistentExceptionEvents->addRecord($persistentExceptionEvent);
1509             }
1510             
1511             // update baseEvent
1512             $rrule = Calendar_Model_Rrule::getRruleFromString($baseEvent->rrule);
1513             if (isset($rrule->count)) {
1514                 // get all occurences and find the split
1515                 
1516                 $exdate = $baseEvent->exdate;
1517                 $baseEvent->exdate = NULL;
1518                     //$baseCountOccurrence = Calendar_Model_Rrule::computeNextOccurrence($baseEvent, new Tinebase_Record_RecordSet('Calendar_Model_Event'), $baseEvent->rrule_until, $baseCount);
1519                 $recurSet = Calendar_Model_Rrule::computeRecurrenceSet($baseEvent, new Tinebase_Record_RecordSet('Calendar_Model_Event'), $baseEvent->dtstart, $baseEvent->rrule_until);
1520                 $baseEvent->exdate = $exdate;
1521                 
1522                 $originalDtstart = $_event->getOriginalDtStart();
1523                 foreach($recurSet as $idx => $rInstance) {
1524                     if ($rInstance->dtstart >= $originalDtstart) break;
1525                 }
1526                 
1527                 $rrule->count = $idx+1;
1528             } else {
1529                 $lastBaseOccurence = Calendar_Model_Rrule::computeNextOccurrence($baseEvent, new Tinebase_Record_RecordSet('Calendar_Model_Event'), $_event->getOriginalDtStart()->subSecond(1), -1);
1530                 $rrule->until = $lastBaseOccurence ? $lastBaseOccurence->getOriginalDtStart() : $baseEvent->dtstart;
1531             }
1532             $baseEvent->rrule = (string) $rrule;
1533             $baseEvent->exdate = $pastExdates;
1534
1535             // NOTE: we don't want implicit attendee updates
1536             //$updatedBaseEvent = $this->update($baseEvent, FALSE);
1537             $this->_inspectEvent($baseEvent);
1538             $updatedBaseEvent = parent::update($baseEvent);
1539             
1540             if ($_deleteInstance == TRUE) {
1541                 // delete all future persistent events
1542                 $this->delete($futurePersistentExceptionEvents->getId());
1543             } else {
1544                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " create new recur series for/at: '{$_event->recurid}'");
1545                 
1546                 // NOTE: in order to move exceptions correctly in time we need to find out the original dtstart
1547                 //       and create the new baseEvent with this time. A following update also updates its exceptions
1548                 $originalDtstart = new Tinebase_DateTime(substr($_event->recurid, -19));
1549                 $adoptedDtstart = clone $_event->dtstart;
1550                 $dtStartHasDiff = $adoptedDtstart->compare($originalDtstart) != 0; // php52 compat
1551                 $eventLength = $_event->dtstart->diff($_event->dtend);
1552                 
1553                 $_event->dtstart = clone $originalDtstart;
1554                 $_event->dtend = clone $originalDtstart;
1555                 $_event->dtend->add($eventLength);
1556                 
1557                 // adopt count
1558                 if (isset($rrule->count)) {
1559                     $baseCount = $rrule->count;
1560                     $rrule = Calendar_Model_Rrule::getRruleFromString($_event->rrule);
1561                     $rrule->count = $rrule->count - $baseCount;
1562                     $_event->rrule = (string) $rrule;
1563                 }
1564                 
1565                 $_event->setId(Tinebase_Record_Abstract::generateUID());
1566                 $_event->uid = $futurePersistentExceptionEvents->uid = Tinebase_Record_Abstract::generateUID();
1567                 $_event->setId(Tinebase_Record_Abstract::generateUID());
1568                 $futurePersistentExceptionEvents->setRecurId($_event->getId());
1569                 unset($_event->recurid);
1570                 unset($_event->base_event_id);
1571                 foreach(array('attendee', 'notes', 'alarms') as $prop) {
1572                     if ($_event->{$prop} instanceof Tinebase_Record_RecordSet) {
1573                         $_event->{$prop}->setId(NULL);
1574                     }
1575                 }
1576                 $_event->exdate = $futureExdates;
1577
1578                 $attendees = $_event->attendee; unset($_event->attendee);
1579                 $note = $_event->notes; unset($_event->notes);
1580                 $persistentExceptionEvent = $this->create($_event, $_checkBusyConflicts && $dtStartHasDiff);
1581                 
1582                 // we save attendee separately to preserve their attributes
1583                 if ($attendees instanceof Tinebase_Record_RecordSet) {
1584                     foreach($attendees as $attendee) {
1585                         $this->_createAttender($attendee, $persistentExceptionEvent, true);
1586                     }
1587                 }
1588                 
1589                 // @todo save notes and add a update note -> what was updated? -> modlog is also missing
1590                 
1591                 $persistentExceptionEvent = $this->get($persistentExceptionEvent->getId());
1592                 
1593                 foreach($futurePersistentExceptionEvents as $futurePersistentExceptionEvent) {
1594                     $this->update($futurePersistentExceptionEvent, FALSE);
1595                 }
1596                 
1597                 if ($dtStartHasDiff) {
1598                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " new recur series has adpted dtstart -> update to adopt exceptions'");
1599                     $persistentExceptionEvent->dtstart = clone $adoptedDtstart;
1600                     $persistentExceptionEvent->dtend = clone $adoptedDtstart;
1601                     $persistentExceptionEvent->dtend->add($eventLength);
1602                     
1603                     $persistentExceptionEvent = $this->update($persistentExceptionEvent, $_checkBusyConflicts);
1604                 }
1605             }
1606         }
1607         
1608         Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
1609         
1610         // restore original notification handling
1611         $this->sendNotifications($sendNotifications);
1612         $notificationAction = $_deleteInstance ? 'deleted' : 'changed';
1613         $notificationEvent = $_deleteInstance ? $_event : $persistentExceptionEvent;
1614         
1615         // restore acl
1616         $this->doContainerACLChecks($doContainerACLChecks);
1617         
1618         // send notifications
1619         if ($this->_sendNotifications && $_event->mute != 1) {
1620             // NOTE: recur exception is a fake event from client. 
1621             //       this might lead to problems, so we wrap the calls
1622             try {
1623                 if (count($_event->attendee) > 0) {
1624                     $_event->attendee->bypassFilters = TRUE;
1625                 }
1626                 $_event->created_by = $baseEvent->created_by;
1627                 
1628                 $this->doSendNotifications($notificationEvent, Tinebase_Core::getUser(), $notificationAction, $originalEvent);
1629             } catch (Exception $e) {
1630                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " " . $e->getTraceAsString());
1631                 Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . " could not send notification {$e->getMessage()}");
1632             }
1633         }
1634         
1635         return $_deleteInstance ? $updatedBaseEvent : $persistentExceptionEvent;
1636     }
1637     
1638     /**
1639      * (non-PHPdoc)
1640      * @see Tinebase_Controller_Record_Abstract::get()
1641      */
1642     public function get($_id, $_containerId = NULL, $_getRelatedData = TRUE, $_getDeleted = FALSE)
1643     {
1644         if (preg_match('/^fakeid(.*):(.*)/', $_id, $matches)) {
1645             $baseEvent = $this->get($matches[1]);
1646             $exceptions = $this->getRecurExceptions($baseEvent);
1647             $originalDtStart = new Tinebase_DateTime($matches[2]);
1648
1649             $exdates = $exceptions->getOriginalDtStart();
1650             $exdate = array_search($originalDtStart, $exdates);
1651
1652             return $exdate !== false ? $exceptions[$exdate] :
1653                 Calendar_Model_Rrule::computeNextOccurrence($baseEvent, $exceptions, $originalDtStart);
1654         } else {
1655             return parent::get($_id, $_containerId, $_getRelatedData, $_getDeleted);
1656         }
1657     }
1658     
1659     /**
1660      * returns base event of a recurring series
1661      *
1662      * @param  Calendar_Model_Event $_event
1663      * @return Calendar_Model_Event
1664      */
1665     public function getRecurBaseEvent($_event)
1666     {
1667         $baseEventId = $_event->base_event_id ?: $_event->id;
1668
1669         if (! $baseEventId) {
1670             throw new Tinebase_Exception_NotFound('base event of a recurring series not found');
1671         }
1672
1673         // make sure we have a 'fully featured' event
1674         return $this->get($baseEventId);
1675     }
1676
1677     /**
1678      * returns all persistent recur exceptions of recur series
1679      * 
1680      * NOTE: deleted instances are saved in the base events exception property
1681      * NOTE: returns all exceptions regardless of current filters and access restrictions
1682      * 
1683      * @param  Calendar_Model_Event        $_event
1684      * @param  boolean                     $_fakeDeletedInstances
1685      * @param  Calendar_Model_EventFilter  $_eventFilter
1686      * @return Tinebase_Record_RecordSet of Calendar_Model_Event
1687      */
1688     public function getRecurExceptions($_event, $_fakeDeletedInstances = FALSE, $_eventFilter = NULL)
1689     {
1690         $baseEventId = $_event->base_event_id ?: $_event->id;
1691
1692         $exceptionFilter = new Calendar_Model_EventFilter(array(
1693             array('field' => 'base_event_id', 'operator' => 'equals',  'value' => $baseEventId),
1694             array('field' => 'recurid',       'operator' => 'notnull', 'value' => NULL)
1695         ));
1696         
1697         if ($_eventFilter instanceof Calendar_Model_EventFilter) {
1698             $exceptionFilter->addFilterGroup($_eventFilter);
1699         }
1700         
1701         $exceptions = $this->_backend->search($exceptionFilter);
1702         
1703         if ($_fakeDeletedInstances) {
1704             $baseEvent = $this->getRecurBaseEvent($_event);
1705             $this->fakeDeletedExceptions($baseEvent, $exceptions);
1706         }
1707         
1708         $exceptions->exdate = NULL;
1709         $exceptions->rrule = NULL;
1710         $exceptions->rrule_until = NULL;
1711         
1712         return $exceptions;
1713     }
1714
1715     /**
1716      * add exceptions events for deleted instances
1717      *
1718      * @param Calendar_Model_Event $baseEvent
1719      * @param Tinebase_Record_RecordSet $exceptions
1720      */
1721     public function fakeDeletedExceptions($baseEvent, $exceptions)
1722     {
1723         $eventLength = $baseEvent->dtstart->diff($baseEvent->dtend);
1724
1725         // compute remaining exdates
1726         $deletedInstanceDtStarts = array_diff(array_unique((array) $baseEvent->exdate), $exceptions->getOriginalDtStart());
1727
1728         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .
1729             ' Faking ' . count($deletedInstanceDtStarts) . ' deleted exceptions');
1730
1731         foreach((array) $deletedInstanceDtStarts as $deletedInstanceDtStart) {
1732             $fakeEvent = clone $baseEvent;
1733             $fakeEvent->setId(NULL);
1734
1735             $fakeEvent->dtstart = clone $deletedInstanceDtStart;
1736             $fakeEvent->dtend = clone $deletedInstanceDtStart;
1737             $fakeEvent->dtend->add($eventLength);
1738             $fakeEvent->is_deleted = TRUE;
1739             $fakeEvent->setRecurId($baseEvent->getId());
1740             $fakeEvent->rrule = null;
1741
1742             $exceptions->addRecord($fakeEvent);
1743         }
1744     }
1745
1746    /**
1747     * adopt alarm time to next occurrence for recurring events
1748     *
1749     * @param Tinebase_Record_Abstract $_record
1750     * @param Tinebase_Model_Alarm $_alarm
1751     * @param bool $_nextBy {instance|time} set recurr alarm to next from given instance or next by current time
1752     * @return void
1753     */
1754     public function adoptAlarmTime(Tinebase_Record_Abstract $_record, Tinebase_Model_Alarm $_alarm, $_nextBy = 'time')
1755     {
1756         if ($_record->rrule) {
1757             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .
1758                  ' Adopting alarm time for next recur occurrence (by ' . $_nextBy . ')');
1759             if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ .
1760                  ' ' . print_r($_record->toArray(), TRUE));
1761             
1762             if ($_nextBy == 'time') {
1763                 // NOTE: this also finds instances running right now
1764                 $from = Tinebase_DateTime::now();
1765             
1766             } else {
1767                 $recurid = $_alarm->getOption('recurid');
1768                 $instanceStart = $recurid ? new Tinebase_DateTime(substr($recurid, -19)) : clone $_record->dtstart;
1769                 $eventLength = $_record->dtstart->diff($_record->dtend);
1770                 
1771                 $instanceStart->setTimezone($_record->originator_tz);
1772                 $from = $instanceStart->add($eventLength);
1773                 $from->setTimezone('UTC');
1774             }
1775             
1776             // compute next
1777             $exceptions = $this->getRecurExceptions($_record);
1778             $nextOccurrence = Calendar_Model_Rrule::computeNextOccurrence($_record, $exceptions, $from);
1779             
1780             if ($nextOccurrence === NULL) {
1781                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ .
1782                     ' Recur series is over, no more alarms pending');
1783             } else {
1784                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .
1785                     ' Found next occurrence, adopting alarm to dtstart ' . $nextOccurrence->dtstart->toString());
1786             }
1787             
1788             // save recurid so we know for which recurrance the alarm is for
1789             $_alarm->setOption('recurid', isset($nextOccurrence) ? $nextOccurrence->recurid : NULL);
1790             
1791             $_alarm->sent_status = $nextOccurrence ? Tinebase_Model_Alarm::STATUS_PENDING : Tinebase_Model_Alarm::STATUS_SUCCESS;
1792             $_alarm->sent_message = $nextOccurrence ?  '' : 'Nothing to send, series is over';
1793             
1794             $eventStart = $nextOccurrence ? clone $nextOccurrence->dtstart : clone $_record->dtstart;
1795         } else {
1796             $eventStart = clone $_record->dtstart;
1797         }
1798         
1799         // save minutes before / compute it for custom alarms
1800         $minutesBefore = $_alarm->minutes_before == Tinebase_Model_Alarm::OPTION_CUSTOM 
1801             ? ($_record->dtstart->getTimestamp() - $_alarm->alarm_time->getTimestamp()) / 60 
1802             : $_alarm->minutes_before;
1803         $minutesBefore = round($minutesBefore);
1804         
1805         $_alarm->setOption('minutes_before', $minutesBefore);
1806         $_alarm->alarm_time = $eventStart->subMinute($minutesBefore);
1807         
1808         if ($_record->rrule && $_alarm->sent_status == Tinebase_Model_Alarm::STATUS_PENDING && $_alarm->alarm_time < $_alarm->sent_time) {
1809             $this->adoptAlarmTime($_record, $_alarm, 'instance');
1810         }
1811         
1812         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ .
1813             ' alarm: ' . print_r($_alarm->toArray(), true));
1814     }
1815     
1816     /****************************** overwritten functions ************************/
1817     
1818     /**
1819      * restore original alarm time of recurring events
1820      * 
1821      * @param Tinebase_Record_Interface $_record
1822      * @return void
1823      */
1824     protected function _inspectAlarmGet(Tinebase_Record_Interface $_record)
1825     {
1826         foreach ($_record->alarms as $alarm) {
1827             if ($recurid = $alarm->getOption('recurid')) {
1828                 $alarm->alarm_time = clone $_record->dtstart;
1829                 $alarm->alarm_time->subMinute((int) $alarm->getOption('minutes_before'));
1830             }
1831         }
1832         
1833         parent::_inspectAlarmGet($_record);
1834     }
1835     
1836     /**
1837      * adopt alarm time to next occurance for recurring events
1838      * 
1839      * @param Tinebase_Record_Interface $_record
1840      * @param Tinebase_Model_Alarm $_alarm
1841      * @param bool $_nextBy {instance|time} set recurr alarm to next from given instance or next by current time
1842      * @return void
1843      * @throws Tinebase_Exception_InvalidArgument
1844      */
1845     protected function _inspectAlarmSet(Tinebase_Record_Interface $_record, Tinebase_Model_Alarm $_alarm, $_nextBy = 'time')
1846     {
1847         parent::_inspectAlarmSet($_record, $_alarm);
1848         $this->adoptAlarmTime($_record, $_alarm, 'time');
1849     }
1850     
1851     /**
1852      * inspect update of one record
1853      * 
1854      * @param   Tinebase_Record_Interface $_record      the update record
1855      * @param   Tinebase_Record_Interface $_oldRecord   the current persistent record
1856      * @return  void
1857      */
1858     protected function _inspectBeforeUpdate($_record, $_oldRecord)
1859     {
1860         // if dtstart of an event changes, we update the originator_tz, alarm times
1861         if (! $_oldRecord->dtstart->equals($_record->dtstart)) {
1862             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' dtstart changed -> adopting organizer_tz');
1863             $_record->originator_tz = Tinebase_Core::getUserTimezone();
1864             if (! empty($_record->rrule)) {
1865                 $diff = $_oldRecord->dtstart->diff($_record->dtstart);
1866                 $this->_updateRecurIdOfExdates($_record, $diff);
1867             }
1868         }
1869         
1870         // delete recur exceptions if update is no longer a recur series
1871         if (! empty($_oldRecord->rrule) && empty($_record->rrule)) {
1872             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' deleting recur exceptions as event is no longer a recur series');
1873             $this->_backend->delete($this->getRecurExceptions($_record));
1874         }
1875         
1876         // touch base event of a recur series if an persistent exception changes
1877         if ($_record->recurid) {
1878             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' touch base event of a persistent exception');
1879             $baseEvent = $this->getRecurBaseEvent($_record);
1880             $this->_touch($baseEvent, TRUE);
1881         }
1882
1883         if (empty($_record->recurid) && ! empty($_record->rrule) && (string)$_record->rrule == (string)$_oldRecord->rrule && $_record->dtstart->compare($_oldRecord->dtstart, 'Y-m-d') !== 0) {
1884             // we are in a base event & dtstart changed the date & the rrule was not changed
1885             // if easy rrule, try to adapt
1886             $rrule = $_record->rrule;
1887             if (! $rrule instanceof Calendar_Model_Rrule) {
1888                 $rrule = new Calendar_Model_Rrule($rrule);
1889             } else {
1890                 $rrule = clone $rrule;
1891             }
1892
1893             switch($rrule->freq)
1894             {
1895                 case Calendar_Model_Rrule::FREQ_WEEKLY:
1896                     // only do simple bydays
1897                     if (empty($rrule->byday) || !isset(Calendar_Model_Rrule::$WEEKDAY_MAP[$rrule->byday])) {
1898                         break;
1899                     }
1900
1901                     // check old dtstart matches byday, if not, we abort
1902                     if (strtolower($_oldRecord->dtstart->format('D')) !== Calendar_Model_Rrule::$WEEKDAY_MAP[$rrule->byday]) {
1903                         break;
1904                     }
1905
1906                     $rrule->byday = Calendar_Model_Rrule::$WEEKDAY_MAP_REVERSE[strtolower($_record->dtstart->format('D'))];
1907                     $_record->rrule = $rrule;
1908                     break;
1909
1910                 case Calendar_Model_Rrule::FREQ_MONTHLY:
1911                     // if there is no day specification, nothing to do
1912                     if (empty($rrule->byday) && empty($rrule->bymonthday)) {
1913                         break;
1914                     }
1915                     // only do simple rules
1916                     if (!empty($rrule->byday) && (strpos(',', $rrule->byday) !== false)) {
1917                         break;
1918                     }
1919                     if (!empty($rrule->bymonthday) && strpos(',', $rrule->bymonthday) !== false) {
1920                         break;
1921                     }
1922                     if (!empty($rrule->byday) && !empty($rrule->bymonthday)) {
1923                         break;
1924                     }
1925
1926                     if (!empty($rrule->byday)) {
1927                         $bydayPrefix = intval($rrule->byday);
1928                         $byday = substr($rrule->byday, -2);
1929
1930                         // if we dont have a quantifier we abort
1931                         if ($bydayPrefix === 0) {
1932                             break;
1933                         }
1934
1935                         // check old dtstart matches byday, if not we abort
1936                         if (strtolower($_oldRecord->dtstart->format('D')) !== Calendar_Model_Rrule::$WEEKDAY_MAP[$byday]) {
1937                             break;
1938                         }
1939
1940                         $dtstartJ = $_oldRecord->dtstart->format('j');
1941                         // check old dtstart matches bydayPrefix, if not we abort
1942                         if ($bydayPrefix === -1) {
1943                             if ($_oldRecord->dtstart->format('t') - $dtstartJ > 6) {
1944                                 break;
1945                             }
1946                         } else {
1947                             if ($dtstartJ - (($bydayPrefix-1)*7) > 6 || $dtstartJ - (($bydayPrefix-1)*7) < 1) {
1948                                 break;
1949                             }
1950                         }
1951
1952                         if ($_record->dtstart->format('j') > 28 || ($bydayPrefix === -1 && $_record->dtstart->format('t') - $_record->dtstart->format('j') < 7)) {
1953                             // keep -1 => last X
1954                             $prefix = '-1';
1955                         } else {
1956                             $prefix = floor(($_record->dtstart->format('j') - 1) / 7) + 1;
1957                         }
1958
1959                         $rrule->byday = $prefix . Calendar_Model_Rrule::$WEEKDAY_MAP_REVERSE[strtolower($_record->dtstart->format('D'))];
1960                         $_record->rrule = $rrule;
1961
1962                     } else {
1963
1964                         // check old dtstart matches bymonthday, if not we abort
1965                         if ($_oldRecord->dtstart->format('j') != $rrule->bymonthday) {
1966                             break;
1967                         }
1968
1969                         $rrule->bymonthday = $_record->dtstart->format('j');
1970                         $_record->rrule = $rrule;
1971                     }
1972
1973                     break;
1974
1975                 case Calendar_Model_Rrule::FREQ_YEARLY:
1976                     // only do simple rules
1977                     if (! empty($rrule->byday) || empty($rrule->bymonth) || empty($rrule->bymonthday) || strpos($rrule->bymonth, ',') !== false ||
1978                         strpos($rrule->bymonthday, ',') !== false ||
1979                         // check old dtstart matches the date
1980                         $_oldRecord->dtstart->format('j') != $rrule->bymonthday || $_oldRecord->dtstart->format('n') != $rrule->bymonth
1981                     ) {
1982                         break;
1983                     }
1984
1985                     $rrule->bymonthday = $_record->dtstart->format('j');
1986                     $rrule->bymonth = $_record->dtstart->format('n');
1987                     $_record->rrule = $rrule;
1988
1989                     break;
1990             }
1991         }
1992     }
1993     
1994     /**
1995      * update exdates and recurids if dtstart of an recurevent changes
1996      * 
1997      * @param Calendar_Model_Event $_record
1998      * @param DateInterval $diff
1999      */
2000     protected function _updateRecurIdOfExdates($_record, $diff)
2001     {
2002         // update exceptions
2003         $exceptions = $this->getRecurExceptions($_record);
2004         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' dtstart of a series changed -> adopting '. count($exceptions) . ' recurid(s)');
2005         $exdates = array();
2006         foreach ($exceptions as $exception) {
2007             $exception->recurid = new Tinebase_DateTime(substr($exception->recurid, -19));
2008             Calendar_Model_Rrule::addUTCDateDstFix($exception->recurid, $diff, $_record->originator_tz);
2009             $exdates[] = $exception->recurid;
2010             
2011             $exception->setRecurId($_record->getId());
2012             $this->_backend->update($exception);
2013         }
2014         
2015         $_record->exdate = $exdates;
2016     }
2017     
2018     /**
2019      * inspect before create/update
2020      * 
2021      * @TODO move stuff from other places here
2022      * @param   Calendar_Model_Event $_record      the record to inspect
2023      */
2024     protected function _inspectEvent($_record, $skipEvent = false)
2025     {
2026         $_record->uid = $_record->uid ? $_record->uid : Tinebase_Record_Abstract::generateUID();
2027         $_record->organizer = $_record->organizer ? $_record->organizer : Tinebase_Core::getUser()->contact_id;
2028         $_record->transp = $_record->transp ? $_record->transp : Calendar_Model_Event::TRANSP_OPAQUE;
2029
2030         $this->_inspectOriginatorTZ($_record);
2031
2032         if ($_record->hasExternalOrganizer()) {
2033             // assert calendarUser as attendee. This is important to keep the event in the loop via its displaycontianer(s)
2034             try {
2035                 $container = Tinebase_Container::getInstance()->getContainerById($_record->container_id);
2036                 $owner = $container->getOwner();
2037                 $calendarUserId = Addressbook_Controller_Contact::getInstance()->getContactByUserId($owner, true)->getId();
2038             } catch (Exception $e) {
2039                 $container = NULL;
2040                 $calendarUserId = Tinebase_Core::getUser()->contact_id;
2041             }
2042             
2043             $attendee = $_record->assertAttendee(new Calendar_Model_Attender(array(
2044                 'user_type'    => Calendar_Model_Attender::USERTYPE_USER,
2045                 'user_id'      => $calendarUserId
2046             )), false, false, true);
2047             
2048             if ($attendee && $container instanceof Tinebase_Model_Container) {
2049                 $attendee->displaycontainer_id = $container->getId();
2050             }
2051             
2052             if (! $container instanceof Tinebase_Model_Container || $container->type == Tinebase_Model_Container::TYPE_PERSONAL) {
2053                 // move into special (external users) container
2054                 $container = Calendar_Controller::getInstance()->getInvitationContainer($_record->resolveOrganizer());
2055                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2056                     . ' Setting container_id to ' . $container->getId() . ' for external organizer ' . $_record->organizer->email);
2057                 $_record->container_id = $container->getId();
2058             }
2059             
2060         }
2061         
2062         if ($_record->is_all_day_event) {
2063             // harmonize datetimes of all day events
2064             $_record->setTimezone($_record->originator_tz);
2065             if (! $_record->dtend) {
2066                 $_record->dtend = clone $_record->dtstart;
2067                 $_record->dtend->setTime(23,59,59);
2068             }
2069             $_record->dtstart->setTime(0,0,0);
2070             $_record->dtend->setTime(23,59,59);
2071             $_record->setTimezone('UTC');
2072         }
2073         $_record->setRruleUntil();
2074         
2075         if ($_record->rrule instanceof Calendar_Model_Rrule) {
2076             $_record->rrule->normalize($_record);
2077         }
2078
2079         if ($_record->isRecurException()) {
2080             $_record->rrule = NULL;
2081             $_record->rrule_constraints = NULL;
2082
2083 //            // Maybe Later
2084 //            $baseEvent = $this->getRecurBaseEvent($_record);
2085 //            // exdates needs to stay in baseEvents container
2086 //            if($_record->container_id != $baseEvent->container_id) {
2087 //                throw new Calendar_Exception_ExdateContainer();
2088 //            }
2089         }
2090
2091         // inspect rrule_constraints
2092         if ($_record->rrule_constraints) {
2093             $this->setConstraintsExdates($_record);
2094         }
2095
2096         if (!$skipEvent) {
2097             Tinebase_Record_PersistentObserver::getInstance()->fireEvent(new Calendar_Event_InspectEvent(array(
2098                 'observable' => $_record
2099             )));
2100         }
2101     }
2102
2103     /**
2104      * checks/sets originator timezone
2105      *
2106      * @param $record
2107      * @throws Tinebase_Exception_Record_Validation
2108      */
2109     protected function _inspectOriginatorTZ($record)
2110     {
2111         $record->originator_tz = $record->originator_tz ? $record->originator_tz : Tinebase_Core::getUserTimezone();
2112
2113         try {
2114             new DateTimeZone($record->originator_tz);
2115         } catch (Exception $e) {
2116             throw new Tinebase_Exception_Record_Validation('Bad Timezone: ' . $record->originator_tz);
2117         }
2118     }
2119     
2120     /**
2121      * inspects delete action
2122      *
2123      * @param array $_ids
2124      * @return array of ids to actually delete
2125      */
2126     protected function _inspectDelete(array $_ids) {
2127         $events = $this->_backend->getMultiple($_ids);
2128         
2129         foreach ($events as $event) {
2130             
2131             // implicitly delete persistent recur instances of series
2132             if (! empty($event->rrule)) {
2133                 $exceptionIds = $this->getRecurExceptions($event)->getId();
2134                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2135                     . ' Implicitly deleting ' . (count($exceptionIds) - 1 ) . ' persistent exception(s) for recurring series with uid' . $event->uid);
2136                 $_ids = array_merge($_ids, $exceptionIds);
2137             }
2138         }
2139         
2140         $this->_deleteAlarmsForIds($_ids);
2141         
2142         return array_unique($_ids);
2143     }
2144     
2145     /**
2146      * redefine required grants for get actions
2147      * 
2148      * @param Tinebase_Model_Filter_FilterGroup $_filter
2149      * @param string $_action get|update
2150      */
2151     public function checkFilterACL(Tinebase_Model_Filter_FilterGroup $_filter, $_action = 'get')
2152     {
2153         $hasGrantsFilter = FALSE;
2154         foreach($_filter->getAclFilters() as $aclFilter) {
2155             if ($aclFilter instanceof Calendar_Model_GrantFilter) {
2156                 $hasGrantsFilter = TRUE;
2157                 break;
2158             }
2159         }
2160         
2161         if (! $hasGrantsFilter && $this->_doContainerACLChecks) {
2162             // force a grant filter
2163             // NOTE: actual grants are set via setRequiredGrants later
2164             $grantsFilter = $_filter->createFilter('grants', 'in', '@setRequiredGrants');
2165             $_filter->addFilter($grantsFilter);
2166         }
2167         
2168         parent::checkFilterACL($_filter, $_action);
2169         
2170         if ($_action == 'get') {
2171             $_filter->setRequiredGrants(array(
2172                 Tinebase_Model_Grants::GRANT_FREEBUSY,
2173                 Tinebase_Model_Grants::GRANT_READ,
2174                 Tinebase_Model_Grants::GRANT_ADMIN,
2175             ));
2176         }
2177     }
2178     
2179     /**
2180      * check grant for action (CRUD)
2181      *
2182      * @param Tinebase_Record_Interface $_record
2183      * @param string $_action
2184      * @param boolean $_throw
2185      * @param string $_errorMessage
2186      * @param Tinebase_Record_Interface $_oldRecord
2187      * @return boolean
2188      * @throws Tinebase_Exception_AccessDenied
2189      * 
2190      * @todo use this function in other create + update functions
2191      * @todo invent concept for simple adding of grants (plugins?) 
2192      */
2193     protected function _checkGrant($_record, $_action, $_throw = TRUE, $_errorMessage = 'No Permission.', $_oldRecord = NULL)
2194     {
2195         if (    ! $this->_doContainerACLChecks 
2196             // admin grant includes all others (only if class is PUBLIC)
2197             ||  (! empty($this->class) && $this->class === Calendar_Model_Event::CLASS_PUBLIC 
2198                 && $_record->container_id && Tinebase_Core::getUser()->hasGrant($_record->container_id, Tinebase_Model_Grants::GRANT_ADMIN))
2199             // external invitations are in a spechial invitaion calendar. only attendee can see it via displaycal
2200             ||  $_record->hasExternalOrganizer()
2201         ) {
2202             return true;
2203         }
2204         
2205         switch ($_action) {
2206             case 'get':
2207                 // NOTE: free/busy is not a read grant!
2208                 $hasGrant = $_record->hasGrant(Tinebase_Model_Grants::GRANT_READ);
2209                 if (! $hasGrant) {
2210                     $_record->doFreeBusyCleanup();
2211                 }
2212                 break;
2213             case 'create':
2214                 $hasGrant = Tinebase_Core::getUser()->hasGrant($_record->container_id, Tinebase_Model_Grants::GRANT_ADD);
2215                 break;
2216             case 'update':
2217                 $hasGrant = (bool) $_oldRecord->hasGrant(Tinebase_Model_Grants::GRANT_EDIT);
2218                 
2219                 if ($_oldRecord->container_id != $_record->container_id) {
2220                     $hasGrant &= Tinebase_Core::getUser()->hasGrant($_record->container_id, Tinebase_Model_Grants::GRANT_ADD)
2221                                  && $_oldRecord->hasGrant(Tinebase_Model_Grants::GRANT_DELETE);
2222                 }
2223                 break;
2224             case 'delete':
2225                 $hasGrant = (bool) $_record->hasGrant(Tinebase_Model_Grants::GRANT_DELETE);
2226                 break;
2227             case 'sync':
2228                 $hasGrant = (bool) $_record->hasGrant(Tinebase_Model_Grants::GRANT_SYNC);
2229                 break;
2230             case 'export':
2231                 $hasGrant = (bool) $_record->hasGrant(Tinebase_Model_Grants::GRANT_EXPORT);
2232                 break;
2233         }
2234         
2235         if (! $hasGrant) {
2236             if ($_throw) {
2237                 throw new Tinebase_Exception_AccessDenied($_errorMessage);
2238             } else {
2239                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2240                     . ' No permissions to ' . $_action . ' in container ' . $_record->container_id);
2241             }
2242         }
2243         
2244         return $hasGrant;
2245     }
2246     
2247     /**
2248      * touches (sets seq, last_modified_time and container content sequence) given event
2249      * 
2250      * @param  $_event
2251      * @return void
2252      */
2253     protected function _touch($_event, $_setModifier = FALSE)
2254     {
2255         $_event->last_modified_time = Tinebase_DateTime::now();
2256         $_event->seq = (int)$_event->seq + 1;
2257         if ($_setModifier) {
2258             $_event->last_modified_by = Tinebase_Core::getUser()->getId();
2259         }
2260         
2261         $this->_backend->update($_event);
2262         
2263         $this->_increaseContainerContentSequence($_event, Tinebase_Model_ContainerContent::ACTION_UPDATE);
2264     }
2265     
2266     /**
2267      * increase container content sequence
2268      *
2269      * @param Tinebase_Record_Interface $_record
2270      * @param string $action
2271      */
2272     protected function _increaseContainerContentSequence(Tinebase_Record_Interface $record, $action = NULL)
2273     {
2274         parent::_increaseContainerContentSequence($record, $action);
2275         
2276         if ($record->attendee instanceof Tinebase_Record_RecordSet) {
2277             $updatedContainerIds = array($record->container_id);
2278             foreach ($record->attendee as $attender) {
2279                 if (isset($attender->displaycontainer_id) && ! in_array($attender->displaycontainer_id, $updatedContainerIds)) {
2280                     Tinebase_Container::getInstance()->increaseContentSequence($attender->displaycontainer_id, $action, $record->getId());
2281                     $updatedContainerIds[] = $attender->displaycontainer_id;
2282                 }
2283             }
2284         }
2285     }
2286     
2287     
2288     /****************************** attendee functions ************************/
2289     
2290     /**
2291      * creates an attender status exception of a recurring event series
2292      * 
2293      * NOTE: Recur exceptions are implicitly created
2294      *
2295      * @param  Calendar_Model_Event    $_recurInstance
2296      * @param  Calendar_Model_Attender $_attender
2297      * @param  string                  $_authKey
2298      * @param  bool                    $_allFollowing
2299      * @return Calendar_Model_Attender updated attender
2300      */
2301     public function attenderStatusCreateRecurException($_recurInstance, $_attender, $_authKey, $_allFollowing = FALSE)
2302     {
2303         try {
2304             $db = $this->_backend->getAdapter();
2305             $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
2306             
2307             $baseEvent = $this->getRecurBaseEvent($_recurInstance);
2308             $baseEventAttendee = Calendar_Model_Attender::getAttendee($baseEvent->attendee, $_attender);
2309             
2310             if ($baseEvent->getId() == $_recurInstance->getId()) {
2311                 // exception to the first occurence
2312                 $_recurInstance->setRecurId($baseEvent->getId());
2313             }
2314             
2315             // NOTE: recurid is computed by rrule recur computations and therefore is already part of the event.
2316             if (empty($_recurInstance->recurid)) {
2317                 throw new Exception('recurid must be present to create exceptions!');
2318             }
2319             
2320             try {
2321                 // check if we already have a persistent exception for this event
2322                 $eventInstance = $this->_backend->getByProperty($_recurInstance->recurid, $_property = 'recurid');
2323                 
2324                 // NOTE: the user must exist (added by someone with appropriate rights by createRecurException)
2325                 $exceptionAttender = Calendar_Model_Attender::getAttendee($eventInstance->attendee, $_attender);
2326                 if (! $exceptionAttender) {
2327                     throw new Tinebase_Exception_AccessDenied('not an attendee');
2328                 }
2329                 
2330                 
2331                 if ($exceptionAttender->status_authkey != $_authKey) {
2332                     // NOTE: it might happen, that the user set her status from the base event without knowing about 
2333                     //       an existing exception. In this case the base event authkey is also valid
2334                     if (! $baseEventAttendee || $baseEventAttendee->status_authkey != $_authKey) {
2335                         throw new Tinebase_Exception_AccessDenied('Attender authkey mismatch');
2336                     }
2337                 }
2338                 
2339             } catch (Tinebase_Exception_NotFound $e) {
2340                 // otherwise create it implicilty
2341                 
2342                 // check if this intance takes place
2343                 if (in_array($_recurInstance->dtstart, (array)$baseEvent->exdate)) {
2344                     throw new Tinebase_Exception_AccessDenied('Event instance is deleted and may not be recreated via status setting!');
2345                 }
2346                 
2347                 if (! $baseEventAttendee) {
2348                     throw new Tinebase_Exception_AccessDenied('not an attendee');
2349                 }
2350                 
2351                 if ($baseEventAttendee->status_authkey != $_authKey) {
2352                     throw new Tinebase_Exception_AccessDenied('Attender authkey mismatch');
2353                 }
2354                 
2355                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " creating recur exception for a exceptional attendee status");
2356                 
2357                 $doContainerAclChecks = $this->doContainerACLChecks(FALSE);
2358                 $sendNotifications = $this->sendNotifications(FALSE);
2359                 
2360                 // NOTE: the user might have no edit grants, so let's be carefull
2361                 $diff = $baseEvent->dtstart->diff($baseEvent->dtend);
2362                 
2363                 $baseEvent->dtstart = new Tinebase_DateTime(substr($_recurInstance->recurid, -19), 'UTC');
2364                 $baseEvent->dtend   = clone $baseEvent->dtstart;
2365                 $baseEvent->dtend->add($diff);
2366
2367                 $baseEvent->base_event_id = $baseEvent->id;
2368                 $baseEvent->id = $_recurInstance->id;
2369                 $baseEvent->recurid = $_recurInstance->recurid;
2370
2371                 $attendee = $baseEvent->attendee;
2372                 unset($baseEvent->attendee);
2373                 
2374                 $eventInstance = $this->createRecurException($baseEvent, FALSE, $_allFollowing);
2375                 $eventInstance->attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender');
2376                 $this->doContainerACLChecks($doContainerAclChecks);
2377                 $this->sendNotifications($sendNotifications);
2378                 
2379                 foreach ($attendee as $attender) {
2380                     $attender->setId(NULL);
2381                     $attender->cal_event_id = $eventInstance->getId();
2382                     
2383                     $attender = $this->_backend->createAttendee($attender);
2384                     $eventInstance->attendee->addRecord($attender);
2385                     $this->_increaseDisplayContainerContentSequence($attender, $eventInstance, Tinebase_Model_ContainerContent::ACTION_CREATE);
2386                 }
2387                 
2388                 $exceptionAttender = Calendar_Model_Attender::getAttendee($eventInstance->attendee, $_attender);
2389             }
2390             
2391             $exceptionAttender->status = $_attender->status;
2392             $exceptionAttender->transp = $_attender->transp;
2393             $eventInstance->alarms     = clone $_recurInstance->alarms;
2394             $eventInstance->alarms->setId(NULL);
2395             
2396             $updatedAttender = $this->attenderStatusUpdate($eventInstance, $exceptionAttender, $exceptionAttender->status_authkey);
2397             
2398             Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
2399         } catch (Exception $e) {
2400             Tinebase_TransactionManager::getInstance()->rollBack();
2401             throw $e;
2402         }
2403         
2404         return $updatedAttender;
2405     }
2406     
2407     /**
2408      * updates an attender status of a event
2409      * 
2410      * @param  Calendar_Model_Event    $_event
2411      * @param  Calendar_Model_Attender $_attender
2412      * @param  string                  $_authKey
2413      * @return Calendar_Model_Attender updated attender
2414      */
2415     public function attenderStatusUpdate(Calendar_Model_Event $_event, Calendar_Model_Attender $_attender, $_authKey)
2416     {
2417         try {
2418             $event = $this->get($_event->getId());
2419             
2420             if (! $event->attendee) {
2421                 throw new Tinebase_Exception_NotFound('Could not find any attendee of event.');
2422             }
2423             
2424             if (($currentAttender = Calendar_Model_Attender::getAttendee($event->attendee, $_attender)) == null) {
2425                 throw new Tinebase_Exception_NotFound('Could not find attender in event.');
2426             }
2427             
2428             $updatedAttender = clone $currentAttender;
2429             
2430             if ($currentAttender->status_authkey !== $_authKey) {
2431                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) 
2432                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " no permissions to update status for {$currentAttender->user_type} {$currentAttender->user_id}");
2433                 return $updatedAttender;
2434             }
2435             
2436             Calendar_Controller_Alarm::enforceACL($_event, $event);
2437             
2438             $currentAttenderDisplayContainerId = $currentAttender->displaycontainer_id instanceof Tinebase_Model_Container ? 
2439                 $currentAttender->displaycontainer_id->getId() : 
2440                 $currentAttender->displaycontainer_id;
2441             
2442             $attenderDisplayContainerId = $_attender->displaycontainer_id instanceof Tinebase_Model_Container ? 
2443                 $_attender->displaycontainer_id->getId() : 
2444                 $_attender->displaycontainer_id;
2445             
2446             // check if something what can be set as user has changed
2447             if ($currentAttender->status == $_attender->status &&
2448                 $currentAttenderDisplayContainerId  == $attenderDisplayContainerId   &&
2449                 $currentAttender->transp            == $_attender->transp            &&
2450                 ! Calendar_Controller_Alarm::hasUpdates($_event, $event)
2451             ) {
2452                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) 
2453                     Tinebase_Core::getLogger()->DEBUG(__METHOD__ . '::' . __LINE__ . "no status change -> do nothing");
2454                 return $updatedAttender;
2455             }
2456             
2457             $updatedAttender->status              = $_attender->status;
2458             $updatedAttender->displaycontainer_id = isset($_attender->displaycontainer_id) ? $_attender->displaycontainer_id : $updatedAttender->displaycontainer_id;
2459             $updatedAttender->transp              = isset($_attender->transp) ? $_attender->transp : Calendar_Model_Event::TRANSP_OPAQUE;
2460             
2461             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
2462                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2463                     . " update attender status to {$_attender->status} for {$currentAttender->user_type} {$currentAttender->user_id}");
2464                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2465                     . ' set alarm_ack_time / alarm_snooze_time: ' . $updatedAttender->alarm_ack_time . ' / ' . $updatedAttender->alarm_snooze_time);
2466             }
2467             
2468             $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
2469             
2470             $updatedAttender = $this->_backend->updateAttendee($updatedAttender);
2471             if ($_event->alarms instanceof Tinebase_Record_RecordSet) {
2472                 foreach($_event->alarms as $alarm) {
2473                     $this->_inspectAlarmSet($event, $alarm);
2474                 }
2475                 
2476                 Tinebase_Alarm::getInstance()->setAlarmsOfRecord($_event);
2477             }
2478
2479             $event->attendee->removeRecord($currentAttender);
2480             $event->attendee->addRecord($updatedAttender);
2481             
2482             $this->_increaseDisplayContainerContentSequence($updatedAttender, $event);
2483
2484             Tinebase_Record_PersistentObserver::getInstance()->fireEvent(new Calendar_Event_InspectEvent(array(
2485                 'observable' => $event
2486             )));
2487
2488             $this->_touch($event, true);
2489
2490             Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
2491         } catch (Exception $e) {
2492             Tinebase_TransactionManager::getInstance()->rollBack();
2493             throw $e;
2494         }
2495         
2496         // send notifications
2497         if ($currentAttender->status != $updatedAttender->status && $this->_sendNotifications && $_event->mute != 1) {
2498             $updatedEvent = $this->get($event->getId());
2499             $this->doSendNotifications($updatedEvent, Tinebase_Core::getUser(), 'changed', $event);
2500         }
2501         
2502         return $updatedAttender;
2503     }
2504     
2505     /**
2506      * saves all attendee of given event
2507      * 
2508      * NOTE: This function is executed in a create/update context. As such the user
2509      *       has edit/update the event and can do anything besides status settings of attendee
2510      * 
2511      * @todo add support for resources
2512      * 
2513      * @param Calendar_Model_Event $_event
2514      * @param Calendar_Model_Event $_currentEvent
2515      * @param bool                 $_isRescheduled event got rescheduled reset all attendee status
2516      */
2517     protected function _saveAttendee($_event, $_currentEvent = NULL, $_isRescheduled = FALSE)
2518     {
2519         if (! $_event->attendee instanceof Tinebase_Record_RecordSet) {
2520             $_event->attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender');
2521         }
2522         
2523         Calendar_Model_Attender::resolveEmailOnlyAttendee($_event);
2524         
2525         $_event->attendee->cal_event_id = $_event->getId();
2526         
2527         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " About to save attendee for event {$_event->id} ");
2528         
2529         $currentAttendee = $_currentEvent->attendee;
2530         
2531         $diff = $currentAttendee->getMigration($_event->attendee->getArrayOfIds());
2532
2533         $calendar = Tinebase_Container::getInstance()->getContainerById($_event->container_id);
2534         
2535         // delete attendee
2536         $this->_backend->deleteAttendee($diff['toDeleteIds']);
2537         foreach ($diff['toDeleteIds'] as $deleteAttenderId) {
2538             $idx = $currentAttendee->getIndexById($deleteAttenderId);
2539             if ($idx !== FALSE) {
2540                 $currentAttenderToDelete = $currentAttendee[$idx];
2541                 $this->_increaseDisplayContainerContentSequence($currentAttenderToDelete, $_event, Tinebase_Model_ContainerContent::ACTION_DELETE);
2542             }
2543         }
2544         
2545         // create/update attendee
2546         foreach ($_event->attendee as $attender) {
2547             $attenderId = $attender->getId();
2548             $idx = ($attenderId) ? $currentAttendee->getIndexById($attenderId) : FALSE;
2549             
2550             if ($idx !== FALSE) {
2551                 $currentAttender = $currentAttendee[$idx];
2552                 $this->_updateAttender($attender, $currentAttender, $_event, $_isRescheduled, $calendar);
2553             } else {
2554                 $this->_createAttender($attender, $_event, FALSE, $calendar);
2555             }
2556         }
2557     }
2558
2559     /**
2560      * creates a new attender
2561      * 
2562      * @param Calendar_Model_Attender  $attender
2563      * @param Tinebase_Model_Container $_calendar
2564      * @param boolean $preserveStatus
2565      * @param Tinebase_Model_Container $calendar
2566      */
2567     protected function _createAttender(Calendar_Model_Attender $attender, Calendar_Model_Event $event, $preserveStatus = FALSE, Tinebase_Model_Container $calendar = NULL)
2568     {
2569         // apply defaults
2570         $attender->user_type         = isset($attender->user_type) ? $attender->user_type : Calendar_Model_Attender::USERTYPE_USER;
2571         $attender->cal_event_id      =  $event->getId();
2572         $calendar = ($calendar) ? $calendar : Tinebase_Container::getInstance()->getContainerById($event->container_id);
2573         
2574         $userAccountId = $attender->getUserAccountId();
2575         
2576         // generate auth key
2577         if (! $attender->status_authkey) {
2578             $attender->status_authkey = Tinebase_Record_Abstract::generateUID();
2579         }
2580         
2581         // attach to display calendar if attender has/is a useraccount
2582         if ($userAccountId) {
2583             if ($calendar->type == Tinebase_Model_Container::TYPE_PERSONAL && Tinebase_Container::getInstance()->hasGrant($userAccountId, $calendar, Tinebase_Model_Grants::GRANT_ADMIN)) {
2584                 // if attender has admin grant to (is owner of) personal physical container, this phys. cal also gets displ. cal
2585                 $attender->displaycontainer_id = $calendar->getId();
2586             } else if ($attender->displaycontainer_id && $userAccountId == Tinebase_Core::getUser()->getId() && Tinebase_Container::getInstance()->hasGrant($userAccountId, $attender->displaycontainer_id, Tinebase_Model_Grants::GRANT_ADMIN)) {
2587                 // allow user to set his own displ. cal
2588                 $attender->displaycontainer_id = $attender->displaycontainer_id;
2589             } else {
2590                 $displayCalId = self::getDefaultDisplayContainerId($userAccountId);
2591                 $attender->displaycontainer_id = $displayCalId;
2592             }
2593
2594         } else if ($attender->user_type === Calendar_Model_Attender::USERTYPE_RESOURCE) {
2595             $resource = Calendar_Controller_Resource::getInstance()->get($attender->user_id);
2596             $attender->displaycontainer_id = $resource->container_id;
2597         }
2598         
2599         if ($attender->displaycontainer_id) {
2600             // check if user is allowed to set status
2601             if (! $preserveStatus && ! Tinebase_Core::getUser()->hasGrant($attender->displaycontainer_id, Tinebase_Model_Grants::GRANT_EDIT)) {
2602                 if ($attender->user_type === Calendar_Model_Attender::USERTYPE_RESOURCE) {
2603                     //If resource has an default status use this
2604                     $attender->status = isset($resource->status) ? $resource->status : Calendar_Model_Attender::STATUS_NEEDSACTION;
2605                 } else {
2606                     $attender->status = Calendar_Model_Attender::STATUS_NEEDSACTION;
2607                 }
2608             }
2609         }
2610
2611         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . " New attender: " . print_r($attender->toArray(), TRUE));
2612
2613         Tinebase_Timemachine_ModificationLog::getInstance()->setRecordMetaData($attender, 'create');
2614         $this->_backend->createAttendee($attender);
2615         $this->_increaseDisplayContainerContentSequence($attender, $event, Tinebase_Model_ContainerContent::ACTION_CREATE);
2616     }
2617     
2618         
2619     /**
2620      * returns the default calendar
2621      * 
2622      * @return Tinebase_Model_Container
2623      */
2624     public function getDefaultCalendar()
2625     {
2626         return Tinebase_Container::getInstance()->getDefaultContainer($this->_applicationName, NULL, Calendar_Preference::DEFAULTCALENDAR);
2627     }
2628     
2629     /**
2630      * returns default displayContainer id of given attendee
2631      *
2632      * @param string $userAccountId
2633      */
2634     public static function getDefaultDisplayContainerId($userAccountId)
2635     {
2636         $userAccountId = Tinebase_Model_User::convertUserIdToInt($userAccountId);
2637         $displayCalId = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::DEFAULTCALENDAR, $userAccountId);
2638         
2639         try {
2640             // assert that displaycal is of type personal
2641             $container = Tinebase_Container::getInstance()->getContainerById($displayCalId);
2642             if ($container->type != Tinebase_Model_Container::TYPE_PERSONAL) {
2643                 $displayCalId = NULL;
2644             }
2645         } catch (Exception $e) {
2646             $displayCalId = NULL;
2647         }
2648         
2649         if (! isset($displayCalId)) {
2650             $containers = Tinebase_Container::getInstance()->getPersonalContainer($userAccountId, 'Calendar_Model_Event', $userAccountId, 0, true);
2651             if ($containers->count() > 0) {
2652                 $displayCalId = $containers->getFirstRecord()->getId();
2653             }
2654         }
2655         
2656         return $displayCalId;
2657     }
2658     
2659     /**
2660      * increases content sequence of attender display container
2661      * 
2662      * @param Calendar_Model_Attender $attender
2663      * @param Calendar_Model_Event $event
2664      * @param string $action
2665      */
2666     protected function _increaseDisplayContainerContentSequence($attender, $event, $action = Tinebase_Model_ContainerContent::ACTION_UPDATE)
2667     {
2668         if ($event->container_id === $attender->displaycontainer_id || empty($attender->displaycontainer_id)) {
2669             // no need to increase sequence
2670             return;
2671         }
2672         
2673         Tinebase_Container::getInstance()->increaseContentSequence($attender->displaycontainer_id, $action, $event->getId());
2674     }
2675     
2676     /**
2677      * updates an attender
2678      * 
2679      * @param Calendar_Model_Attender  $attender
2680      * @param Calendar_Model_Attender  $currentAttender
2681      * @param Calendar_Model_Event     $event
2682      * @param bool                     $isRescheduled event got rescheduled reset all attendee status
2683      * @param Tinebase_Model_Container $calendar
2684      */
2685     protected function _updateAttender($attender, $currentAttender, $event, $isRescheduled, $calendar = NULL)
2686     {
2687         $userAccountId = $currentAttender->getUserAccountId();
2688
2689         // update display calendar if attender has/is a useraccount
2690         if ($userAccountId) {
2691             if ($calendar->type == Tinebase_Model_Container::TYPE_PERSONAL && Tinebase_Container::getInstance()->hasGrant($userAccountId, $calendar, Tinebase_Model_Grants::GRANT_ADMIN)) {
2692                 // if attender has admin grant to personal physical container, this phys. cal also gets displ. cal
2693                 $attender->displaycontainer_id = $calendar->getId();
2694             } else if ($userAccountId == Tinebase_Core::getUser()->getId() && Tinebase_Container::getInstance()->hasGrant($userAccountId, $attender->displaycontainer_id, Tinebase_Model_Grants::GRANT_ADMIN)) {
2695                 // allow user to set his own displ. cal
2696                 $attender->displaycontainer_id = $attender->displaycontainer_id;
2697             } else {
2698                 $attender->displaycontainer_id = $currentAttender->displaycontainer_id;
2699             }
2700         }
2701
2702         // reset status if user has no right and authkey is wrong
2703         if ($attender->displaycontainer_id) {
2704             if (! Tinebase_Core::getUser()->hasGrant($attender->displaycontainer_id, Tinebase_Model_Grants::GRANT_EDIT)
2705                     && $attender->status_authkey != $currentAttender->status_authkey) {
2706
2707                 if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__
2708                     . ' Wrong authkey, resetting status (' . $attender->status . ' -> ' . $currentAttender->status . ')');
2709                 $attender->status = $currentAttender->status;
2710             }
2711         }
2712
2713         // reset all status but calUser on reschedule except resources (Resources might have a configured default value)
2714         if ($isRescheduled && !$attender->isSame($this->getCalendarUser())) {
2715             if ($attender->user_type === Calendar_Model_Attender::USERTYPE_RESOURCE) {
2716                 //If resource has a default status reset to this
2717                 $resource = Calendar_Controller_Resource::getInstance()->get($attender->user_id);
2718                 $attender->status = isset($resource->status) ? $resource->status : Calendar_Model_Attender::STATUS_NEEDSACTION;
2719             } else {
2720                 $attender->status = Calendar_Model_Attender::STATUS_NEEDSACTION;
2721             }
2722             $attender->transp = null;
2723         }
2724
2725         // preserve old authkey
2726         $attender->status_authkey = $currentAttender->status_authkey;
2727
2728         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
2729             . " Updating attender: " . print_r($attender->toArray(), TRUE));
2730
2731
2732         Tinebase_Timemachine_ModificationLog::getInstance()->setRecordMetaData($attender, 'update', $currentAttender);
2733         Tinebase_Timemachine_ModificationLog::getInstance()->writeModLog($attender, $currentAttender, get_class($attender), $this->_getBackendType(), $attender->getId());
2734         $this->_backend->updateAttendee($attender);
2735         
2736         if ($attender->displaycontainer_id !== $currentAttender->displaycontainer_id) {
2737             $this->_increaseDisplayContainerContentSequence($currentAttender, $event, Tinebase_Model_ContainerContent::ACTION_DELETE);
2738             $this->_increaseDisplayContainerContentSequence($attender, $event, Tinebase_Model_ContainerContent::ACTION_CREATE);
2739         } else {
2740             $this->_increaseDisplayContainerContentSequence($attender, $event);
2741         }
2742     }
2743     
2744     /**
2745      * event handler for group updates
2746      * 
2747      * @param Tinebase_Model_Group $_group
2748      * @return void
2749      */
2750     public function onUpdateGroup($_groupId)
2751     {
2752         $doContainerACLChecks = $this->doContainerACLChecks(FALSE);
2753         
2754         $filter = new Calendar_Model_EventFilter(array(
2755             array('field' => 'attender', 'operator' => 'equals', 'value' => array(
2756                 'user_type' => Calendar_Model_Attender::USERTYPE_GROUP,
2757                 'user_id'   => $_groupId
2758             )),
2759             array('field' => 'period', 'operator' => 'within', 'value' => array(
2760                 'from'  => Tinebase_DateTime::now()->get(Tinebase_Record_Abstract::ISO8601LONG),
2761                 'until' => Tinebase_DateTime::now()->addYear(100)->get(Tinebase_Record_Abstract::ISO8601LONG))
2762             )
2763         ));
2764         $events = $this->search($filter, new Tinebase_Model_Pagination(), FALSE, FALSE);
2765         
2766         foreach($events as $event) {
2767             try {
2768                 if (! $event->rrule) {
2769                     // update non recurring futrue events
2770                     Calendar_Model_Attender::resolveGroupMembers($event->attendee);
2771                     $this->update($event);
2772                 } else {
2773                     // update thisandfuture for recurring events
2774                     $nextOccurrence = Calendar_Model_Rrule::computeNextOccurrence($event, $this->getRecurExceptions($event), Tinebase_DateTime::now());
2775                     Calendar_Model_Attender::resolveGroupMembers($nextOccurrence->attendee);
2776                     
2777                     if ($nextOccurrence->dtstart != $event->dtstart) {
2778                         $this->createRecurException($nextOccurrence, FALSE, TRUE);
2779                     } else {
2780                         $this->update($nextOccurrence);
2781                     }
2782                 }
2783             } catch (Exception $e) {
2784                 Tinebase_Core::getLogger()->NOTICE(__METHOD__ . '::' . __LINE__ . " could not update attendee");
2785             }
2786         }
2787         
2788         $this->doContainerACLChecks($doContainerACLChecks);
2789     }
2790     
2791     /****************************** alarm functions ************************/
2792     
2793     /**
2794      * send an alarm
2795      *
2796      * @param  Tinebase_Model_Alarm $_alarm
2797      * @return void
2798      * 
2799      * NOTE: the given alarm is raw and has not passed _inspectAlarmGet
2800      *  
2801      * @todo throw exception on error
2802      */
2803     public function sendAlarm(Tinebase_Model_Alarm $_alarm) 
2804     {
2805         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " About to send alarm " . print_r($_alarm->toArray(), TRUE));
2806         
2807         $doContainerACLChecks = $this->doContainerACLChecks(FALSE);
2808
2809         try {
2810             $event = $this->get($_alarm->record_id);
2811             $event->alarms = new Tinebase_Record_RecordSet('Tinebase_Model_Alarm', array($_alarm));
2812             $this->_inspectAlarmGet($event);
2813         } catch (Exception $e) {
2814             $this->doContainerACLChecks($doContainerACLChecks);
2815             throw($e);
2816         }
2817
2818         $this->doContainerACLChecks($doContainerACLChecks);
2819
2820         if ($event->rrule) {
2821             $recurid = $_alarm->getOption('recurid');
2822             
2823             // adopts the (referenced) alarm and sets alarm time to next occurance
2824             parent::_inspectAlarmSet($event, $_alarm);
2825             $this->adoptAlarmTime($event, $_alarm, 'instance');
2826             
2827             // sent_status might have changed in adoptAlarmTime()
2828             if ($_alarm->sent_status !== Tinebase_Model_Alarm::STATUS_PENDING) {
2829                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
2830                     . ' Not sending alarm for event at ' . $event->dtstart->toString() . ' with status ' . $_alarm->sent_status);
2831                 return;
2832             }
2833             
2834             if ($recurid) {
2835                 // NOTE: In case of recuring events $event is always the baseEvent,
2836                 //       so we might need to adopt event time to recur instance.
2837                 $diff = $event->dtstart->diff($event->dtend);
2838                 
2839                 $event->dtstart = new Tinebase_DateTime(substr($recurid, -19));
2840                 
2841                 $event->dtend = clone $event->dtstart;
2842                 $event->dtend->add($diff);
2843             }
2844             
2845             if ($event->exdate && in_array($event->dtstart, $event->exdate)) {
2846                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
2847                     . " Not sending alarm because instance at " . $event->dtstart->toString() . ' is an exception.');
2848                 return;
2849             }
2850         }
2851         
2852         Calendar_Controller_EventNotifications::getInstance()->doSendNotifications($event, Tinebase_Core::getUser(), 'alarm', NULL, array('alarm' => $_alarm));
2853     }
2854     
2855     /**
2856      * send notifications 
2857      * 
2858      * @param Tinebase_Record_Interface  $_event
2859      * @param Tinebase_Model_FullUser    $_updater
2860      * @param String                     $_action
2861      * @param Tinebase_Record_Interface  $_oldEvent
2862      * @param Array                      $_additionalData
2863      */
2864     public function doSendNotifications(Tinebase_Record_Interface $_event, Tinebase_Model_FullUser $_updater, $_action, Tinebase_Record_Interface $_oldEvent = NULL, array $_additionalData = array())
2865     {
2866         Tinebase_ActionQueue::getInstance()->queueAction('Calendar.sendEventNotifications', 
2867             $_event, 
2868             $_updater,
2869             $_action, 
2870             $_oldEvent ? $_oldEvent : NULL
2871         );
2872     }
2873
2874     public function compareCalendars($cal1, $cal2, $from, $until)
2875     {
2876         $matchingEvents = new Tinebase_Record_RecordSet('Calendar_Model_Event');
2877         $changedEvents = new Tinebase_Record_RecordSet('Calendar_Model_Event');
2878         $missingEventsInCal1 = new Tinebase_Record_RecordSet('Calendar_Model_Event');
2879         $missingEventsInCal2 = new Tinebase_Record_RecordSet('Calendar_Model_Event');
2880         $cal2EventIdsAlreadyProcessed = array();
2881         
2882         while ($from->isEarlier($until)) {
2883     
2884             $endWeek = $from->getClone()->addWeek(1);
2885             
2886             if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
2887                     . ' Comparing period ' . $from . ' - ' . $endWeek);
2888     
2889             // get all events from cal1+cal2 for the week
2890             $cal1Events = $this->_getEventsForPeriodAndCalendar($cal1, $from, $endWeek);
2891             $cal1EventsClone = clone $cal1Events;
2892             $cal2Events = $this->_getEventsForPeriodAndCalendar($cal2, $from, $endWeek);
2893             $cal2EventsClone = clone $cal2Events;
2894             
2895             $from->addWeek(1);
2896             if (count($cal1Events) == 0 && count($cal2Events) == 0) {
2897                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2898                         . ' No events found');
2899                 continue;
2900             }
2901     
2902             foreach ($cal1Events as $event) {
2903                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2904                     . ' Checking event "' . $event->summary . '" ' . $event->dtstart . ' - ' . $event->dtend);
2905                 
2906                 if ($event->container_id != $cal1) {
2907                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2908                             . ' Event is in another calendar - skip');
2909                     $cal1Events->removeRecord($event);
2910                     continue;
2911                 }
2912                 
2913                 $summaryMatch = $cal2Events->filter('summary', $event->summary);
2914                 if (count($summaryMatch) > 0) {
2915                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2916                         . " Found " . count($summaryMatch) . ' events with matching summaries');
2917                     
2918                     $dtStartMatch = $summaryMatch->filter('dtstart', $event->dtstart);
2919                     if (count($dtStartMatch) > 0) {
2920                         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2921                             . " Found " . count($summaryMatch) . ' events with matching dtstarts and summaries');
2922                         
2923                         $matchingEvents->merge($dtStartMatch);
2924                         // remove from cal1+cal2
2925                         $cal1Events->removeRecord($event);
2926                         $cal2Events->removeRecords($dtStartMatch);
2927                         $cal2EventIdsAlreadyProcessed = array_merge($cal2EventIdsAlreadyProcessed, $dtStartMatch->getArrayOfIds());
2928                     } else {
2929                         $changedEvents->merge($summaryMatch);
2930                         $cal1Events->removeRecord($event);
2931                         $cal2Events->removeRecords($summaryMatch);
2932                         $cal2EventIdsAlreadyProcessed = array_merge($cal2EventIdsAlreadyProcessed, $summaryMatch->getArrayOfIds());
2933                     }
2934                 }
2935             }
2936             
2937             // add missing events
2938             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2939                 . " Found " . count($cal1Events) . ' events missing in cal2');
2940             $missingEventsInCal2->merge($cal1Events);
2941             
2942             // compare cal2 -> cal1 and add events as missing from cal1 that we did not detect before
2943             foreach ($cal2EventsClone as $event) {
2944                 if (in_array($event->getId(), $cal2EventIdsAlreadyProcessed)) {
2945                     continue;
2946                 }
2947                 if ($event->container_id != $cal2) {
2948                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2949                             . ' Event is in another calendar - skip');
2950                     continue;
2951                 }
2952                 
2953                 $missingEventsInCal1->addRecord($event);
2954             }
2955         }
2956         
2957         $result = array(
2958             'matching'      => $matchingEvents,
2959             'changed'       => $changedEvents,
2960             'missingInCal1' => $missingEventsInCal1,
2961             'missingInCal2' => $missingEventsInCal2,
2962         );
2963         return $result;
2964     }
2965     
2966     protected function _getEventsForPeriodAndCalendar($calendarId, $from, $until)
2967     {
2968         $filter = new Calendar_Model_EventFilter(array(
2969             array('field' => 'period', 'operator' => 'within', 'value' =>
2970                 array("from" => $from, "until" => $until)
2971             ),
2972             array('field' => 'container_id', 'operator' => 'equals', 'value' => $calendarId),
2973         ));
2974     
2975         $events = Calendar_Controller_Event::getInstance()->search($filter);
2976         Calendar_Model_Rrule::mergeAndRemoveNonMatchingRecurrences($events, $filter);
2977         return $events;
2978     }
2979     
2980     /**
2981      * add calendar owner as attendee if not already set
2982      * 
2983      * @param string $calendarId
2984      * @param Tinebase_DateTime $from
2985      * @param Tinebase_DateTime $until
2986      * @param boolean $dry run
2987      * 
2988      * @return number of updated events
2989      */
2990     public function repairAttendee($calendarId, $from, $until, $dry = false)
2991     {
2992         $container = Tinebase_Container::getInstance()->getContainerById($calendarId);
2993         if ($container->type !== Tinebase_Model_Container::TYPE_PERSONAL) {
2994             throw new Calendar_Exception('Only allowed for personal containers!');
2995         }
2996         if ($container->owner_id !== Tinebase_Core::getUser()->getId()) {
2997             throw new Calendar_Exception('Only allowed for own containers!');
2998         }
2999         
3000         $updateCount = 0;
3001         while ($from->isEarlier($until)) {
3002             $endWeek = $from->getClone()->addWeek(1);
3003             
3004             if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
3005                     . ' Repairing period ' . $from . ' - ' . $endWeek);
3006             
3007             
3008             // TODO we need to detect events with DECLINED/DELETED attendee
3009             $events = $this->_getEventsForPeriodAndCalendar($calendarId, $from, $endWeek);
3010             
3011             $from->addWeek(1);
3012             
3013             if (count($events) == 0) {
3014                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
3015                         . ' No events found');
3016                 continue;
3017             }
3018             
3019             foreach ($events as $event) {
3020                 // add attendee if not already set
3021                 if ($event->isRecurInstance()) {
3022                     // TODO get base event
3023                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
3024                             . ' Skip recur instance ' . $event->toShortString());
3025                     continue;
3026                 }
3027                 
3028                 $ownAttender = Calendar_Model_Attender::getOwnAttender($event->attendee);
3029                 if (! $ownAttender) {
3030                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
3031                             . ' Add missing attender to event ' . $event->toShortString());
3032                     
3033                     $attender = new Calendar_Model_Attender(array(
3034                         'user_type' => Calendar_Model_Attender::USERTYPE_USER,
3035                         'user_id'   => Tinebase_Core::getUser()->contact_id,
3036                         'status'    => Calendar_Model_Attender::STATUS_ACCEPTED
3037                     ));
3038                     $event->attendee->addRecord($attender);
3039                     if (! $dry) {
3040                         $this->update($event);
3041                     }
3042                     $updateCount++;
3043                 }
3044             }
3045         }
3046         
3047         return $updateCount;
3048     }
3049
3050     public function sendTentativeNotifications()
3051     {
3052         $eventNotificationController = Calendar_Controller_EventNotifications::getInstance();
3053         $calConfig = Calendar_Config::getInstance();
3054         if (true !== $calConfig->{Calendar_Config::TENTATIVE_NOTIFICATIONS}
3055                 ->{Calendar_Config::TENTATIVE_NOTIFICATIONS_ENABLED}) {
3056             return;
3057         }
3058
3059         $days = $calConfig->{Calendar_Config::TENTATIVE_NOTIFICATIONS}->{Calendar_Config::TENTATIVE_NOTIFICATIONS_DAYS};
3060         $additionalFilters = $calConfig->{Calendar_Config::TENTATIVE_NOTIFICATIONS}
3061             ->{Calendar_Config::TENTATIVE_NOTIFICATIONS_FILTER};
3062
3063         $filter = array(
3064             array('field' => 'period', 'operator' => 'within', 'value' => array(
3065                 'from'  => Tinebase_DateTime::now(),
3066                 'until' => Tinebase_DateTime::now()->addDay($days)
3067             )),
3068             array('field' => 'status', 'operator' => 'equals', 'value' => Calendar_Model_Event::STATUS_TENTATIVE)
3069         );
3070
3071         if (null !== $additionalFilters) {
3072             $filter = array_merge($filter, $additionalFilters);
3073         }
3074
3075         $filter = new Calendar_Model_EventFilter($filter);
3076         foreach ($this->search($filter) as $event) {
3077             $eventNotificationController->doSendNotifications($event, null, 'tentative');
3078         }
3079     }
3080
3081     /**
3082      * returns active fixed calendars for users (combines config and preference)
3083      *
3084      * @return array
3085      * @throws Tinebase_Exception_NotFound
3086      */
3087     public function getFixedCalendarIds()
3088     {
3089         $fixedCalendars = (array) Calendar_Config::getInstance()->get(Calendar_Config::FIXED_CALENDARS);
3090
3091         // add fixed calendars from user preference
3092         $fixedCalendarsPref = Tinebase_Core::getPreference('Calendar')->getValue(Calendar_Preference::FIXED_CALENDARS);
3093         if (is_array($fixedCalendarsPref)) {
3094             foreach ($fixedCalendarsPref as $container) {
3095                 if (isset($container['id'])) {
3096                     $fixedCalendars[] = $container['id'];
3097                 }
3098             }
3099         }
3100
3101         return $fixedCalendars;
3102     }
3103 }