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)
12 * Calendar Event Controller
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
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
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.
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
47 * NOTE: the backend always fetches full records for grant calculations.
48 * searching ids only does not hlep with performance
52 class Calendar_Controller_Event extends Tinebase_Controller_Record_Abstract implements Tinebase_Controller_Alarm_Interface
57 * just set is_delete=1 if record is going to be deleted
59 protected $_purgeRecords = FALSE;
66 protected $_sendNotifications = TRUE;
69 * @see Tinebase_Controller_Record_Abstract
73 protected $_resolveCustomFields = TRUE;
76 * @var Calendar_Model_Attender
78 protected $_calendarUser = NULL;
81 * @var Calendar_Controller_Event
83 private static $_instance = NULL;
88 * don't use the constructor. use the singleton
90 private function __construct()
92 $this->_applicationName = 'Calendar';
93 $this->_modelName = 'Calendar_Model_Event';
94 $this->_backend = new Calendar_Backend_Sql();
97 $this->setCalendarUser(new Calendar_Model_Attender(array(
98 'user_type' => Calendar_Model_Attender::USERTYPE_USER,
99 'user_id' => Calendar_Controller_MSEventFacade::getCurrentUserContactId()
104 * don't clone. Use the singleton.
106 private function __clone()
114 * @return Calendar_Controller_Event
116 public static function getInstance()
118 if (self::$_instance === NULL) {
119 self::$_instance = new Calendar_Controller_Event();
121 return self::$_instance;
125 * sets current calendar user
127 * @param Calendar_Model_Attender $_calUser
128 * @return Calendar_Model_Attender oldUser
130 public function setCalendarUser(Calendar_Model_Attender $_calUser)
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');
135 $oldUser = $this->_calendarUser;
136 $this->_calendarUser = $_calUser;
142 * get current calendar user
144 * @return Calendar_Model_Attender
146 public function getCalendarUser()
148 return $this->_calendarUser;
152 * checks if all attendee of given event are not busy for given event
154 * @param Calendar_Model_Event $_event
156 * @throws Calendar_Exception_AttendeeBusy
158 public function checkBusyConflicts($_event)
160 $ignoreUIDs = !empty($_event->uid) ? array($_event->uid) : array();
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");
168 $periods = $this->getBlockingPeriods($_event, array(
169 'from' => $_event->dtstart,
170 'until' => $_event->dtstart->getClone()->addMonth(2)
173 $fbInfo = $this->getFreeBusyInfo($periods, $_event->attendee, $ignoreUIDs);
175 if (count($fbInfo) > 0) {
176 $busyException = new Calendar_Exception_AttendeeBusy();
177 $busyException->setFreeBusyInfo($fbInfo);
179 Calendar_Model_Attender::resolveAttendee($_event->attendee, /* resolve_display_containers = */ false);
180 $busyException->setEvent($_event);
182 throw $busyException;
185 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
186 . " Free/busy check: no conflict found");
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
198 public function create(Tinebase_Record_Interface $_record, $_checkBusyConflicts = FALSE, $skipEvent = false)
201 $db = $this->_backend->getAdapter();
202 $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
204 $this->_inspectEvent($_record, $skipEvent);
206 // we need to resolve groupmembers before free/busy checking
207 Calendar_Model_Attender::resolveGroupMembers($_record->attendee);
209 if ($_checkBusyConflicts) {
210 // ensure that all attendee are free
211 $this->checkBusyConflicts($_record);
214 $sendNotifications = $this->_sendNotifications;
215 $this->_sendNotifications = FALSE;
217 $createdEvent = parent::create($_record);
219 $this->_sendNotifications = $sendNotifications;
221 Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
222 } catch (Exception $e) {
223 Tinebase_TransactionManager::getInstance()->rollBack();
227 // send notifications
228 if ($this->_sendNotifications && $_record->mute != 1) {
229 $this->doSendNotifications($createdEvent, Tinebase_Core::getUser(), 'created');
232 return $createdEvent;
236 * inspect creation of one record (after create)
238 * @param Tinebase_Record_Interface $_createdRecord
239 * @param Tinebase_Record_Interface $_record
242 protected function _inspectAfterCreate($_createdRecord, Tinebase_Record_Interface $_record)
244 $this->_saveAttendee($_record, $_createdRecord);
248 * deletes a recur series
250 * @param Calendar_Model_Event $_recurInstance
253 public function deleteRecurSeries($_recurInstance)
255 $baseEvent = $this->getRecurBaseEvent($_recurInstance);
256 $this->delete($baseEvent->getId());
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
267 public function getAll($_orderBy = 'id', $_orderDirection = 'ASC')
269 throw new Tinebase_Exception_NotImplemented('not implemented');
273 * returns period filter expressing blocking times caused by given event
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)
281 * @return Calendar_Model_EventFilter
283 public function getBlockingPeriods($event, $checkPeriod = array())
285 $eventSet = new Tinebase_Record_RecordSet('Calendar_Model_Event', array($event));
287 if (! empty($event->rrule)) {
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
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);
299 $periodFilters = array();
300 foreach ($eventSet as $candidate) {
301 if ($candidate->transp != Calendar_Model_Event::TRANSP_TRANSP) {
302 $periodFilters[] = array(
304 'operator' => 'within',
306 'from' => $candidate->dtstart,
307 'until' => $candidate->dtend,
313 $filter = new Calendar_Model_EventFilter($periodFilters, Tinebase_Model_Filter_FilterGroup::CONDITION_OR);
319 * returns conflicting periods
321 * @param Calendar_Model_EventFilter $periodCandidates
322 * @param Calendar_Model_EventFilter $conflictCriteria
323 * @param bool $getAll
326 public function getConflictingPeriods($periodCandidates, $conflictCriteria, $getAll=false)
328 $conflictFilter = clone $conflictCriteria;
329 $conflictFilter->addFilterGroup($periodCandidates);
330 $conflictCandidates = $this->search($conflictFilter);
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'];
338 Calendar_Model_Rrule::mergeRecurrenceSet($conflictCandidates, $from, $until);
340 $conflicts = array();
341 foreach ($periodCandidates as $periodFilter) {
342 $period = $periodFilter->getValue();
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'],
363 * @param Tinebase_Record_RecordSet $_records
366 public function mergeFreeBusyInfo(Tinebase_Record_RecordSet $_records)
368 $_records->sort('dtstart');
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;
378 if ($event->dtend->isLater($period['dtend'])) {
379 $period['dtend'] = clone $event->dtend;
383 throw new Tinebase_Exception_UnexpectedValue('record set sort by dtstart did not work!');
388 'dtstart' => $event->dtstart,
389 'dtend' => $event->dtend
397 * returns freebusy information for given period and given attendee
399 * @todo merge overlapping events to one freebusy entry
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
406 public function getFreeBusyInfo($_periods, $_attendee, $_ignoreUIDs = array())
408 $fbInfoSet = new Tinebase_Record_RecordSet('Calendar_Model_FreeBusy');
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);
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
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)
437 $conflictingPeriods = $this->getConflictingPeriods($_periods, $conflictCriteria, true);
441 foreach ($attendee as $attender) {
442 if (! isset($typeMap[$attender['user_type']])) {
443 $typeMap[$attender['user_type']] = array();
445 if (is_object($attender['user_id'])) {
446 $attender['user_id'] = $attender['user_id']->getId();
448 $typeMap[$attender['user_type']][$attender['user_id']] = array();
450 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . ' ' . __LINE__
451 . ' value: ' . print_r($typeMap, true));
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);
459 $processedEvents = array();
461 foreach ($conflictingPeriods as $conflictingPeriod) {
462 $event = $conflictingPeriod['event'];
464 // one event may conflict multiple periods
465 if (in_array($event, $processedEvents)) {
469 $processedEvents[] = $event;
471 // skip events with ignoreUID
472 if (in_array($event->uid, $_ignoreUIDs)) {
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;
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) {
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;
490 if ($attender->user_type == Calendar_Model_Attender::USERTYPE_RESOURCE) {
491 $resource = $resources->getById($attender->user_id);
493 $type = $resource->busy_type;
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,
505 if ($event->{Tinebase_Model_Grants::GRANT_READ}) {
506 $fbInfo->event = clone $event;
507 unset($fbInfo->event->attendee);
510 //$typeMap[$attender->user_type][$attender->user_id][] = $fbInfo;
511 $fbInfoSet->addRecord($fbInfo);
520 * update future constraint exdates of a single event
524 public function setConstraintsExdates($_record)
526 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
527 . ' event has rrule constrains, calculating exdates');
529 $exdates = is_array($_record->exdate) ? $_record->exdate : array();
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));
536 $constrainExdatePeriods = $this->getConflictingPeriods($this->getBlockingPeriods($_record), $constraints);
537 foreach ($constrainExdatePeriods as $constrainExdatePeriod) {
538 $exdates[] = $constrainExdatePeriod['from'];
542 $_record->exdate = array_unique($exdates);
546 * update all future constraints exdates
548 public function updateConstraintsExdates()
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)
556 array('field' => 'rrule_contraints', 'operator' => 'notnull', 'value' => NULL)
560 foreach ($constraintsEventIds as $constraintsEventId) {
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);
576 * get list of records
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
585 public function search(Tinebase_Model_Filter_FilterGroup $_filter = NULL, Tinebase_Model_Pagination $_pagination = NULL, $_getRelations = FALSE, $_onlyIds = FALSE, $_action = 'get')
587 $events = parent::search($_filter, $_pagination, $_getRelations, $_onlyIds, $_action);
589 $this->_freeBusyCleanup($events, $_action);
596 * Returns a set of records identified by their id's
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
602 public function getMultiple($_ids, $_ignoreACL = false)
604 $events = parent::getMultiple($_ids, $_ignoreACL = false);
605 if ($_ignoreACL !== true) {
606 $this->_freeBusyCleanup($events, 'get');
613 * cleanup search results (freebusy)
615 * @param Tinebase_Record_RecordSet $_events
616 * @param string $_action
618 protected function _freeBusyCleanup(Tinebase_Record_RecordSet $_events, $_action)
620 foreach ($_events as $event) {
621 $doFreeBusyCleanup = $event->doFreeBusyCleanup();
622 if ($doFreeBusyCleanup && $_action !== 'get') {
623 $_events->removeRecord($event);
629 * @param Calendar_Model_Event $_event with
630 * attendee to find free timeslot for
631 * dtstart, dtend -> to calculate duration
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
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
644 public function searchFreeTime($_event, $_options)
646 $functionTime = time();
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');
652 if (!isset($_event->dtstart) || !$_event->dtstart instanceof Tinebase_DateTime) {
653 throw new Tinebase_Exception_UnexpectedValue('dtend needs to be set');
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');
660 if (empty($_event->originator_tz)) {
661 $_event->originator_tz = Tinebase_Core::getUserTimezone();
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);
669 $currentFrom = $from->getClone();
670 $currentUntil = $from->getClone()->addDay(6)->setTime(23, 59, 59);
671 if ($currentUntil->isLater($until)) {
672 $currentUntil = clone $until;
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());
678 if (isset($_options['constraints'])) {
679 foreach ($_options['constraints'] as $constraint) {
680 if (!isset($constraint['dtstart']) || !isset($constraint['dtend'])) {
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);
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(
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
706 if (time() - $functionTime > 23) {
707 $exception = new Calendar_Exception_AttendeeBusy();
708 $exception->setEvent(new Calendar_Model_Event(array('dtend' => $currentFrom), true));
712 $currentConstraints = clone $constraints;
713 Calendar_Model_Rrule::mergeRecurrenceSet($currentConstraints, $currentFrom, $currentUntil);
714 $currentConstraints->sort('dtstart');
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);
727 $recurEvent->dtend = $recurEvent->dtstart->getClone()->addSecond($durationSec);
729 if (null === ($recurEvent = Calendar_Model_Rrule::computeNextOccurrence($recurEvent, $exceptions, $event->dtstart))
730 || $recurEvent->dtstart->isLater($event->dtend)) {
734 foreach($remove as $event) {
735 $currentConstraints->removeRecord($event);
739 if ($currentConstraints->count() > 0) {
741 /** @var Calendar_Model_Event $event */
742 foreach ($currentConstraints as $event) {
745 'operator' => 'within',
747 'from' => $event->dtstart,
748 'until' => $event->dtend
753 $busySlots = $this->getFreeBusyInfo(new Calendar_Model_EventFilter($periods, Tinebase_Model_Filter_FilterGroup::CONDITION_OR), $_event->attendee);
754 $busySlots = $this->mergeFreeBusyInfo($busySlots);
756 /** @var Calendar_Model_Event $event */
757 foreach ($currentConstraints as $event) {
758 if ($event->dtend->isEarlierOrEquals($currentFrom)) {
762 if ($_event->is_all_day_event) {
763 $durationSec = (int)$event->dtend->getTimestamp() - (int)$event->dtstart->getTimestamp();
766 $constraintStart = (int)$event->dtstart->getTimestamp();
767 if ($constraintStart < (int)$currentFrom->getTimestamp()) {
768 $constraintStart = (int)$currentFrom->getTimestamp();
770 $constraintEnd = (int)$event->dtend->getTimestamp();
771 if ($constraintEnd > (int)$currentUntil->getTimestamp()) {
772 $constraintEnd = (int)$currentUntil->getTimestamp();
774 $lastBusyEnd = $constraintStart;
776 /** @var Calendar_Model_FreeBusy $busy */
777 foreach ($busySlots as $key => $busy) {
778 $busyStart = (int)$busy['dtstart']->getTimestamp();
779 $busyEnd = (int)$busy['dtend']->getTimestamp();
781 if ($busyEnd < $constraintStart) {
786 if ($busyStart > ($constraintEnd - $durationSec)) {
787 $lastBusyEnd = $busyEnd;
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;
802 $lastBusyEnd = $busyEnd;
804 foreach ($remove as $key) {
805 unset($busySlots[$key]);
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;
822 $currentFrom->addDay(7)->setTime(0, 0, 0);
823 $currentUntil->addDay(7);
824 if ($currentUntil->isLater($until)) {
825 $currentUntil = clone $until;
827 } while ($until->isLater($currentFrom));
829 return new Tinebase_Record_RecordSet('Calendar_Model_Event', array());
832 protected function _tryForFreeSlot(Calendar_Model_Event $_event, $_startSec, $_endSec, $_durationSec, Tinebase_DateTime $_until)
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,
840 $result = new Tinebase_Record_RecordSet('Calendar_Model_Event', array($event));
842 if (!empty($_event->rrule)) {
843 $event->rrule = $_event->rrule;
845 $until = $event->dtstart->getClone()->addMonth(2);
846 if ($until->isLater($_until)) {
849 $periods = $this->getBlockingPeriods($event, array(
850 'from' => $event->dtstart,
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));
858 if ($busySlots->count() > 0) {
859 $result->removeAll();
861 $event->dtstart->subMinute(15);
862 $event->dtend->subMinute(15);
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
879 public function update(Tinebase_Record_Interface $_record, $_checkBusyConflicts = FALSE, $range = Calendar_Model_Event::RANGE_THIS, $skipEvent = false)
881 /** @var Calendar_Model_Event $_record */
883 $db = $this->_backend->getAdapter();
884 $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
886 $sendNotifications = $this->sendNotifications(FALSE);
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));
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})");
896 // we need to resolve groupmembers before free/busy checking
897 Calendar_Model_Attender::resolveGroupMembers($_record->attendee);
898 $this->_inspectEvent($_record, $skipEvent);
900 if ($_checkBusyConflicts) {
901 if ($event->isRescheduled($_record) ||
902 count(array_diff($_record->attendee->user_id, $event->attendee->user_id)) > 0
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 ... ");
908 $this->checkBusyConflicts($_record);
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");
917 parent::update($_record);
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);
929 if ($_record->isRecurException() && in_array($range, array(Calendar_Model_Event::RANGE_ALL, Calendar_Model_Event::RANGE_THISANDFUTURE))) {
930 $this->_updateExdateRange($_record, $range, $event);
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);
941 $updatedEvent = $this->get($event->getId());
943 // send notifications
944 $this->sendNotifications($sendNotifications);
945 if ($this->_sendNotifications && $_record->mute != 1) {
946 $this->doSendNotifications($updatedEvent, Tinebase_Core::getUser(), 'changed', $event);
948 return $updatedEvent;
952 * inspect update of one record (after update)
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)
959 protected function _inspectAfterUpdate($updatedRecord, $record, $currentRecord)
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);
967 * update range of events starting with given recur exception
969 * @param Calendar_Model_Event $exdate
970 * @param string $range
972 protected function _updateExdateRange($exdate, $range, $oldExdate)
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());
977 $baseEvent = $this->getRecurBaseEvent($exdate);
978 /** @var Tinebase_Record_Diff $diff */
979 $diff = $oldExdate->diff($exdate);
981 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
982 . ' Exdate diff: ' . print_r($diff->toArray(), TRUE));
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);
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);
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));
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);
1011 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1012 . ' No upcoming occurrences found.');
1017 protected function _applyDTStartToBaseEventRRULE($_dtstart, $_baseEvent)
1019 /** @var Calendar_Model_Rrule $rrule */
1020 /*$rrule = $_baseEvent->rrule;
1021 if (! $rrule instanceof Calendar_Model_Rrule) {
1022 $rrule = new Calendar_Model_Rrule($rrule);
1025 switch($rrule->freq)
1027 case Calendar_Model_Rrule::FREQ_DAILY
1030 if ($rrule->freq == Calendar_Model_Rrule::FREQ_WEEKLY) {
1034 if ($rrule->freq == Calendar_Model_Rrule::FREQ_MONTHLY) {
1035 if (!empty($rrule->byday)) {
1037 } elseif(!empty($rrule->bymonthday)) {
1042 if ($rrule->freq == Calendar_Model_Rrule::FREQ_YEARLY) {
1043 // bymonthday + bymonth
1046 switch($rrule->byday)
1053 * apply exdate diff to a recordset of events
1055 * @param Calendar_Model_Event $exdate
1056 * @param Tinebase_Record_Diff $diff
1057 * @param Tinebase_Record_RecordSet $events
1059 protected function _applyExdateDiffToRecordSet($exdate, $diff, $events)
1061 // make sure baseEvent gets updated first to circumvent concurrency conflicts
1062 $events->sort('recurdid', 'ASC');
1064 foreach ($events as $event) {
1065 if ($event->getId() === $exdate->getId()) {
1069 $this->_applyDiff($event, $diff, $exdate, FALSE);
1070 $this->update($event);
1075 * merge updates from exdate into event
1077 * @param Calendar_Model_Event $event
1078 * @param Tinebase_Record_Diff $diff
1079 * @param Calendar_Model_Event $exdate
1080 * @param boolean $overwriteMods
1082 * @todo is $overwriteMods needed?
1084 protected function _applyDiff($event, $diff, $exdate, $overwriteMods = TRUE)
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));
1091 $recentChanges = new Tinebase_Record_RecordSet('Tinebase_Model_ModificationLog');
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);
1106 foreach ($attendeeDiff['removed'] as $attenderToRemove) {
1107 $attenderInCurrentSet = Calendar_Model_Attender::getAttendee($event->attendee, $attenderToRemove);
1108 if ($attenderInCurrentSet) {
1109 $event->attendee->removeRecord($attenderInCurrentSet);
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);
1120 $event->attendee = $attendee;
1122 } else if (! in_array($key, $diffIgnore) && ! in_array($key, $changedAttributes)) {
1123 $event->{$key} = $exdate->{$key};
1125 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
1126 . ' Ignore / recently changed: ' . $key);
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);
1136 * update multiple records
1138 * @param Tinebase_Model_Filter_FilterGroup $_filter
1139 * @param array $_data
1140 * @return integer number of updated records
1142 public function updateMultiple($_filter, $_data)
1144 $this->_checkRight('update');
1145 $this->checkFilterACL($_filter, 'update');
1148 $ids = $this->_backend->search($_filter, NULL, TRUE);
1150 foreach ($ids as $eventId) {
1151 $event = $this->get($eventId);
1152 foreach ($_data as $field => $value) {
1153 $event->$field = $value;
1156 $this->update($event);
1163 * Deletes a set of records.
1165 * If one of the records could not be deleted, no record is deleted
1167 * @param array $_ids array of record identifiers
1168 * @param string $range
1170 * @throws Tinebase_Exception_NotFound|Tinebase_Exception
1172 public function delete($_ids, $range = Calendar_Model_Event::RANGE_THIS)
1174 if ($_ids instanceof $this->_modelName) {
1175 $_ids = (array)$_ids->getId();
1178 $records = $this->_backend->getMultiple((array) $_ids);
1180 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1181 . " Deleting " . count($records) . ' with range ' . $range . ' ...');
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);
1189 $db = $this->_backend->getAdapter();
1190 $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
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()) {
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 ");
1208 parent::delete($record);
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);
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);
1230 Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
1231 } catch (Exception $e) {
1232 Tinebase_TransactionManager::getInstance()->rollBack();
1239 * delete range of events starting with given recur exception
1241 * NOTE: if exdate is persistent, it will not be deleted by this function
1242 * but by the original call of delete
1244 * @param Calendar_Model_Event $exdate
1245 * @param string $range
1247 protected function _deleteExdateRange($exdate, $range)
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());
1252 $baseEvent = $this->getRecurBaseEvent($exdate);
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);
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);
1266 $this->createRecurException($nextRegularRecurEvent, TRUE, TRUE);
1272 * updates a recur series
1274 * @param Calendar_Model_Event $_recurInstance
1275 * @param bool $_checkBusyConflicts
1276 * @return Calendar_Model_Event
1278 public function updateRecurSeries($_recurInstance, $_checkBusyConflicts = FALSE)
1280 $baseEvent = $this->getRecurBaseEvent($_recurInstance);
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);
1288 $dtStart->setTimezone(Tinebase_DateTime::TIMEZONE_UTC);
1289 $dtEnd = $_recurInstance->dtEnd;
1290 if (! $dtEnd instanceof Tinebase_DateTime) {
1291 $dtEnd = new Tinebase_DateTime($dtEnd);
1293 $dtEnd->setTimezone(Tinebase_DateTime::TIMEZONE_UTC);
1295 if ($originalDtStart->compare($dtStart) !== 0 ||
1296 (($orgDiff = $baseEvent->dtend->diff($baseEvent->dtstart)) &&
1297 ($newDiff = $dtEnd->diff($dtStart)) &&
1299 $orgDiff->days !== $newDiff->days ||
1300 $orgDiff->h !== $newDiff->h ||
1301 $orgDiff->m !== $newDiff->m ||
1302 $orgDiff->s !== $newDiff->s
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');
1311 // replace baseEvent with adopted instance
1312 $newBaseEvent = clone $_recurInstance;
1313 $newBaseEvent->setId($baseEvent->getId());
1314 unset($newBaseEvent->recurid);
1315 $newBaseEvent->exdate = $baseEvent->exdate;
1317 $this->_applyTimeDiff($newBaseEvent, $_recurInstance, $baseEvent);
1319 return $this->update($newBaseEvent, $_checkBusyConflicts);
1325 * @param Calendar_Model_Event $newEvent
1326 * @param Calendar_Model_Event $fromEvent
1327 * @param Calendar_Model_Event $baseEvent
1329 protected function _applyTimeDiff($newEvent, $fromEvent, $baseEvent = NULL)
1332 $baseEvent = $newEvent;
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));
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;
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'));
1350 $newEvent->dtstart = clone $baseEvent->dtstart;
1351 $newEvent->dtstart->add($dtstartDiff);
1353 $newEvent->dtend = clone $newEvent->dtstart;
1354 $newEvent->dtend->add($eventDuration);
1358 * creates an exception instance of a recurring event
1360 * NOTE: deleting persistent exceptions is done via a normal delete action
1361 * and handled in the deleteInspection
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
1369 * @todo replace $_allFollowing param with $range
1370 * @deprecated replace with create/update/delete
1372 public function createRecurException($_event, $_deleteInstance = FALSE, $_allFollowing = FALSE, $_checkBusyConflicts = FALSE)
1374 $baseEvent = $this->getRecurBaseEvent($_event);
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!');
1383 // // exdates needs to stay in baseEvents container
1384 // if ($_event->container_id != $baseEvent->container_id) {
1385 // throw new Calendar_Exception_ExdateContainer();
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!');
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;
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);
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));
1415 throw new Tinebase_Exception_AccessDenied('Failed to update attendee, status authkey might be missing');
1418 return $this->get($exceptionAttender->cal_event_id);
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!');
1426 // we do notifications ourself
1427 $sendNotifications = $this->sendNotifications(FALSE);
1429 // EDIT for baseEvent is checked above, CREATE, DELETE for recur exceptions is implied with it
1430 $doContainerACLChecks = $this->doContainerACLChecks(FALSE);
1432 $db = $this->_backend->getAdapter();
1433 $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
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);
1440 if ($_allFollowing != TRUE) {
1441 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
1442 . " Adding exdate for: '{$_event->recurid}'");
1444 array_push($exdates, $exdate);
1445 $baseEvent->exdate = $exdates;
1446 $updatedBaseEvent = $this->update($baseEvent, FALSE);
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));
1454 $_event->base_event_id = $baseEvent->getId();
1455 $_event->setId(NULL);
1456 unset($_event->rrule);
1457 unset($_event->exdate);
1459 foreach (array('attendee', 'notes', 'alarms') as $prop) {
1460 if ($_event->{$prop} instanceof Tinebase_Record_RecordSet) {
1461 $_event->{$prop}->setId(NULL);
1465 $originalDtstart = $_event->getOriginalDtStart();
1466 $dtStartHasDiff = $originalDtstart->compare($_event->dtstart) != 0; // php52 compat
1468 if (! $dtStartHasDiff) {
1469 $attendees = $_event->attendee;
1470 unset($_event->attendee);
1472 $note = $_event->notes;
1473 unset($_event->notes);
1474 $persistentExceptionEvent = $this->create($_event, $_checkBusyConflicts);
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);
1488 // @todo save notes and add a update note -> what was updated? -> modlog is also missing
1489 $persistentExceptionEvent = $this->get($persistentExceptionEvent->getId());
1493 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " shorten recur series for/to: '{$_event->recurid}'");
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;
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);
1512 $rrule = Calendar_Model_Rrule::getRruleFromString($baseEvent->rrule);
1513 if (isset($rrule->count)) {
1514 // get all occurences and find the split
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;
1522 $originalDtstart = $_event->getOriginalDtStart();
1523 foreach($recurSet as $idx => $rInstance) {
1524 if ($rInstance->dtstart >= $originalDtstart) break;
1527 $rrule->count = $idx+1;
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;
1532 $baseEvent->rrule = (string) $rrule;
1533 $baseEvent->exdate = $pastExdates;
1535 // NOTE: we don't want implicit attendee updates
1536 //$updatedBaseEvent = $this->update($baseEvent, FALSE);
1537 $this->_inspectEvent($baseEvent);
1538 $updatedBaseEvent = parent::update($baseEvent);
1540 if ($_deleteInstance == TRUE) {
1541 // delete all future persistent events
1542 $this->delete($futurePersistentExceptionEvents->getId());
1544 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " create new recur series for/at: '{$_event->recurid}'");
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);
1553 $_event->dtstart = clone $originalDtstart;
1554 $_event->dtend = clone $originalDtstart;
1555 $_event->dtend->add($eventLength);
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;
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);
1576 $_event->exdate = $futureExdates;
1578 $attendees = $_event->attendee; unset($_event->attendee);
1579 $note = $_event->notes; unset($_event->notes);
1580 $persistentExceptionEvent = $this->create($_event, $_checkBusyConflicts && $dtStartHasDiff);
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);
1589 // @todo save notes and add a update note -> what was updated? -> modlog is also missing
1591 $persistentExceptionEvent = $this->get($persistentExceptionEvent->getId());
1593 foreach($futurePersistentExceptionEvents as $futurePersistentExceptionEvent) {
1594 $this->update($futurePersistentExceptionEvent, FALSE);
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);
1603 $persistentExceptionEvent = $this->update($persistentExceptionEvent, $_checkBusyConflicts);
1608 Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
1610 // restore original notification handling
1611 $this->sendNotifications($sendNotifications);
1612 $notificationAction = $_deleteInstance ? 'deleted' : 'changed';
1613 $notificationEvent = $_deleteInstance ? $_event : $persistentExceptionEvent;
1616 $this->doContainerACLChecks($doContainerACLChecks);
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
1623 if (count($_event->attendee) > 0) {
1624 $_event->attendee->bypassFilters = TRUE;
1626 $_event->created_by = $baseEvent->created_by;
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()}");
1635 return $_deleteInstance ? $updatedBaseEvent : $persistentExceptionEvent;
1640 * @see Tinebase_Controller_Record_Abstract::get()
1642 public function get($_id, $_containerId = NULL, $_getRelatedData = TRUE, $_getDeleted = FALSE)
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]);
1649 $exdates = $exceptions->getOriginalDtStart();
1650 $exdate = array_search($originalDtStart, $exdates);
1652 return $exdate !== false ? $exceptions[$exdate] :
1653 Calendar_Model_Rrule::computeNextOccurrence($baseEvent, $exceptions, $originalDtStart);
1655 return parent::get($_id, $_containerId, $_getRelatedData, $_getDeleted);
1660 * returns base event of a recurring series
1662 * @param Calendar_Model_Event $_event
1663 * @return Calendar_Model_Event
1665 public function getRecurBaseEvent($_event)
1667 $baseEventId = $_event->base_event_id ?: $_event->id;
1669 if (! $baseEventId) {
1670 throw new Tinebase_Exception_NotFound('base event of a recurring series not found');
1673 // make sure we have a 'fully featured' event
1674 return $this->get($baseEventId);
1678 * returns all persistent recur exceptions of recur series
1680 * NOTE: deleted instances are saved in the base events exception property
1681 * NOTE: returns all exceptions regardless of current filters and access restrictions
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
1688 public function getRecurExceptions($_event, $_fakeDeletedInstances = FALSE, $_eventFilter = NULL)
1690 $baseEventId = $_event->base_event_id ?: $_event->id;
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)
1697 if ($_eventFilter instanceof Calendar_Model_EventFilter) {
1698 $exceptionFilter->addFilterGroup($_eventFilter);
1701 $exceptions = $this->_backend->search($exceptionFilter);
1703 if ($_fakeDeletedInstances) {
1704 $baseEvent = $this->getRecurBaseEvent($_event);
1705 $this->fakeDeletedExceptions($baseEvent, $exceptions);
1708 $exceptions->exdate = NULL;
1709 $exceptions->rrule = NULL;
1710 $exceptions->rrule_until = NULL;
1716 * add exceptions events for deleted instances
1718 * @param Calendar_Model_Event $baseEvent
1719 * @param Tinebase_Record_RecordSet $exceptions
1721 public function fakeDeletedExceptions($baseEvent, $exceptions)
1723 $eventLength = $baseEvent->dtstart->diff($baseEvent->dtend);
1725 // compute remaining exdates
1726 $deletedInstanceDtStarts = array_diff(array_unique((array) $baseEvent->exdate), $exceptions->getOriginalDtStart());
1728 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ .
1729 ' Faking ' . count($deletedInstanceDtStarts) . ' deleted exceptions');
1731 foreach((array) $deletedInstanceDtStarts as $deletedInstanceDtStart) {
1732 $fakeEvent = clone $baseEvent;
1733 $fakeEvent->setId(NULL);
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;
1742 $exceptions->addRecord($fakeEvent);
1747 * adopt alarm time to next occurrence for recurring events
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
1754 public function adoptAlarmTime(Tinebase_Record_Abstract $_record, Tinebase_Model_Alarm $_alarm, $_nextBy = 'time')
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));
1762 if ($_nextBy == 'time') {
1763 // NOTE: this also finds instances running right now
1764 $from = Tinebase_DateTime::now();
1767 $recurid = $_alarm->getOption('recurid');
1768 $instanceStart = $recurid ? new Tinebase_DateTime(substr($recurid, -19)) : clone $_record->dtstart;
1769 $eventLength = $_record->dtstart->diff($_record->dtend);
1771 $instanceStart->setTimezone($_record->originator_tz);
1772 $from = $instanceStart->add($eventLength);
1773 $from->setTimezone('UTC');
1777 $exceptions = $this->getRecurExceptions($_record);
1778 $nextOccurrence = Calendar_Model_Rrule::computeNextOccurrence($_record, $exceptions, $from);
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');
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());
1788 // save recurid so we know for which recurrance the alarm is for
1789 $_alarm->setOption('recurid', isset($nextOccurrence) ? $nextOccurrence->recurid : NULL);
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';
1794 $eventStart = $nextOccurrence ? clone $nextOccurrence->dtstart : clone $_record->dtstart;
1796 $eventStart = clone $_record->dtstart;
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);
1805 $_alarm->setOption('minutes_before', $minutesBefore);
1806 $_alarm->alarm_time = $eventStart->subMinute($minutesBefore);
1808 if ($_record->rrule && $_alarm->sent_status == Tinebase_Model_Alarm::STATUS_PENDING && $_alarm->alarm_time < $_alarm->sent_time) {
1809 $this->adoptAlarmTime($_record, $_alarm, 'instance');
1812 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ .
1813 ' alarm: ' . print_r($_alarm->toArray(), true));
1816 /****************************** overwritten functions ************************/
1819 * restore original alarm time of recurring events
1821 * @param Tinebase_Record_Interface $_record
1824 protected function _inspectAlarmGet(Tinebase_Record_Interface $_record)
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'));
1833 parent::_inspectAlarmGet($_record);
1837 * adopt alarm time to next occurance for recurring events
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
1843 * @throws Tinebase_Exception_InvalidArgument
1845 protected function _inspectAlarmSet(Tinebase_Record_Interface $_record, Tinebase_Model_Alarm $_alarm, $_nextBy = 'time')
1847 parent::_inspectAlarmSet($_record, $_alarm);
1848 $this->adoptAlarmTime($_record, $_alarm, 'time');
1852 * inspect update of one record
1854 * @param Tinebase_Record_Interface $_record the update record
1855 * @param Tinebase_Record_Interface $_oldRecord the current persistent record
1858 protected function _inspectBeforeUpdate($_record, $_oldRecord)
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);
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));
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);
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);
1890 $rrule = clone $rrule;
1893 switch($rrule->freq)
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])) {
1901 // check old dtstart matches byday, if not, we abort
1902 if (strtolower($_oldRecord->dtstart->format('D')) !== Calendar_Model_Rrule::$WEEKDAY_MAP[$rrule->byday]) {
1906 $rrule->byday = Calendar_Model_Rrule::$WEEKDAY_MAP_REVERSE[strtolower($_record->dtstart->format('D'))];
1907 $_record->rrule = $rrule;
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)) {
1915 // only do simple rules
1916 if (!empty($rrule->byday) && (strpos(',', $rrule->byday) !== false)) {
1919 if (!empty($rrule->bymonthday) && strpos(',', $rrule->bymonthday) !== false) {
1922 if (!empty($rrule->byday) && !empty($rrule->bymonthday)) {
1926 if (!empty($rrule->byday)) {
1927 $bydayPrefix = intval($rrule->byday);
1928 $byday = substr($rrule->byday, -2);
1930 // if we dont have a quantifier we abort
1931 if ($bydayPrefix === 0) {
1935 // check old dtstart matches byday, if not we abort
1936 if (strtolower($_oldRecord->dtstart->format('D')) !== Calendar_Model_Rrule::$WEEKDAY_MAP[$byday]) {
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) {
1947 if ($dtstartJ - (($bydayPrefix-1)*7) > 6 || $dtstartJ - (($bydayPrefix-1)*7) < 1) {
1952 if ($_record->dtstart->format('j') > 28 || ($bydayPrefix === -1 && $_record->dtstart->format('t') - $_record->dtstart->format('j') < 7)) {
1953 // keep -1 => last X
1956 $prefix = floor(($_record->dtstart->format('j') - 1) / 7) + 1;
1959 $rrule->byday = $prefix . Calendar_Model_Rrule::$WEEKDAY_MAP_REVERSE[strtolower($_record->dtstart->format('D'))];
1960 $_record->rrule = $rrule;
1964 // check old dtstart matches bymonthday, if not we abort
1965 if ($_oldRecord->dtstart->format('j') != $rrule->bymonthday) {
1969 $rrule->bymonthday = $_record->dtstart->format('j');
1970 $_record->rrule = $rrule;
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
1985 $rrule->bymonthday = $_record->dtstart->format('j');
1986 $rrule->bymonth = $_record->dtstart->format('n');
1987 $_record->rrule = $rrule;
1995 * update exdates and recurids if dtstart of an recurevent changes
1997 * @param Calendar_Model_Event $_record
1998 * @param DateInterval $diff
2000 protected function _updateRecurIdOfExdates($_record, $diff)
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)');
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;
2011 $exception->setRecurId($_record->getId());
2012 $this->_backend->update($exception);
2015 $_record->exdate = $exdates;
2019 * inspect before create/update
2021 * @TODO move stuff from other places here
2022 * @param Calendar_Model_Event $_record the record to inspect
2024 protected function _inspectEvent($_record, $skipEvent = false)
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;
2030 $this->_inspectOriginatorTZ($_record);
2032 if ($_record->hasExternalOrganizer()) {
2033 // assert calendarUser as attendee. This is important to keep the event in the loop via its displaycontianer(s)
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) {
2040 $calendarUserId = Tinebase_Core::getUser()->contact_id;
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);
2048 if ($attendee && $container instanceof Tinebase_Model_Container) {
2049 $attendee->displaycontainer_id = $container->getId();
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();
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);
2069 $_record->dtstart->setTime(0,0,0);
2070 $_record->dtend->setTime(23,59,59);
2071 $_record->setTimezone('UTC');
2073 $_record->setRruleUntil();
2075 if ($_record->rrule instanceof Calendar_Model_Rrule) {
2076 $_record->rrule->normalize($_record);
2079 if ($_record->isRecurException()) {
2080 $_record->rrule = NULL;
2081 $_record->rrule_constraints = NULL;
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();
2091 // inspect rrule_constraints
2092 if ($_record->rrule_constraints) {
2093 $this->setConstraintsExdates($_record);
2097 Tinebase_Record_PersistentObserver::getInstance()->fireEvent(new Calendar_Event_InspectEvent(array(
2098 'observable' => $_record
2104 * checks/sets originator timezone
2107 * @throws Tinebase_Exception_Record_Validation
2109 protected function _inspectOriginatorTZ($record)
2111 $record->originator_tz = $record->originator_tz ? $record->originator_tz : Tinebase_Core::getUserTimezone();
2114 new DateTimeZone($record->originator_tz);
2115 } catch (Exception $e) {
2116 throw new Tinebase_Exception_Record_Validation('Bad Timezone: ' . $record->originator_tz);
2121 * inspects delete action
2123 * @param array $_ids
2124 * @return array of ids to actually delete
2126 protected function _inspectDelete(array $_ids) {
2127 $events = $this->_backend->getMultiple($_ids);
2129 foreach ($events as $event) {
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);
2140 $this->_deleteAlarmsForIds($_ids);
2142 return array_unique($_ids);
2146 * redefine required grants for get actions
2148 * @param Tinebase_Model_Filter_FilterGroup $_filter
2149 * @param string $_action get|update
2151 public function checkFilterACL(Tinebase_Model_Filter_FilterGroup $_filter, $_action = 'get')
2153 $hasGrantsFilter = FALSE;
2154 foreach($_filter->getAclFilters() as $aclFilter) {
2155 if ($aclFilter instanceof Calendar_Model_GrantFilter) {
2156 $hasGrantsFilter = TRUE;
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);
2168 parent::checkFilterACL($_filter, $_action);
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,
2180 * check grant for action (CRUD)
2182 * @param Tinebase_Record_Interface $_record
2183 * @param string $_action
2184 * @param boolean $_throw
2185 * @param string $_errorMessage
2186 * @param Tinebase_Record_Interface $_oldRecord
2188 * @throws Tinebase_Exception_AccessDenied
2190 * @todo use this function in other create + update functions
2191 * @todo invent concept for simple adding of grants (plugins?)
2193 protected function _checkGrant($_record, $_action, $_throw = TRUE, $_errorMessage = 'No Permission.', $_oldRecord = NULL)
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()
2207 // NOTE: free/busy is not a read grant!
2208 $hasGrant = $_record->hasGrant(Tinebase_Model_Grants::GRANT_READ);
2210 $_record->doFreeBusyCleanup();
2214 $hasGrant = Tinebase_Core::getUser()->hasGrant($_record->container_id, Tinebase_Model_Grants::GRANT_ADD);
2217 $hasGrant = (bool) $_oldRecord->hasGrant(Tinebase_Model_Grants::GRANT_EDIT);
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);
2225 $hasGrant = (bool) $_record->hasGrant(Tinebase_Model_Grants::GRANT_DELETE);
2228 $hasGrant = (bool) $_record->hasGrant(Tinebase_Model_Grants::GRANT_SYNC);
2231 $hasGrant = (bool) $_record->hasGrant(Tinebase_Model_Grants::GRANT_EXPORT);
2237 throw new Tinebase_Exception_AccessDenied($_errorMessage);
2239 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
2240 . ' No permissions to ' . $_action . ' in container ' . $_record->container_id);
2248 * touches (sets seq, last_modified_time and container content sequence) given event
2253 protected function _touch($_event, $_setModifier = FALSE)
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();
2261 $this->_backend->update($_event);
2263 $this->_increaseContainerContentSequence($_event, Tinebase_Model_ContainerContent::ACTION_UPDATE);
2267 * increase container content sequence
2269 * @param Tinebase_Record_Interface $_record
2270 * @param string $action
2272 protected function _increaseContainerContentSequence(Tinebase_Record_Interface $record, $action = NULL)
2274 parent::_increaseContainerContentSequence($record, $action);
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;
2288 /****************************** attendee functions ************************/
2291 * creates an attender status exception of a recurring event series
2293 * NOTE: Recur exceptions are implicitly created
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
2301 public function attenderStatusCreateRecurException($_recurInstance, $_attender, $_authKey, $_allFollowing = FALSE)
2304 $db = $this->_backend->getAdapter();
2305 $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
2307 $baseEvent = $this->getRecurBaseEvent($_recurInstance);
2308 $baseEventAttendee = Calendar_Model_Attender::getAttendee($baseEvent->attendee, $_attender);
2310 if ($baseEvent->getId() == $_recurInstance->getId()) {
2311 // exception to the first occurence
2312 $_recurInstance->setRecurId($baseEvent->getId());
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!');
2321 // check if we already have a persistent exception for this event
2322 $eventInstance = $this->_backend->getByProperty($_recurInstance->recurid, $_property = 'recurid');
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');
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');
2339 } catch (Tinebase_Exception_NotFound $e) {
2340 // otherwise create it implicilty
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!');
2347 if (! $baseEventAttendee) {
2348 throw new Tinebase_Exception_AccessDenied('not an attendee');
2351 if ($baseEventAttendee->status_authkey != $_authKey) {
2352 throw new Tinebase_Exception_AccessDenied('Attender authkey mismatch');
2355 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " creating recur exception for a exceptional attendee status");
2357 $doContainerAclChecks = $this->doContainerACLChecks(FALSE);
2358 $sendNotifications = $this->sendNotifications(FALSE);
2360 // NOTE: the user might have no edit grants, so let's be carefull
2361 $diff = $baseEvent->dtstart->diff($baseEvent->dtend);
2363 $baseEvent->dtstart = new Tinebase_DateTime(substr($_recurInstance->recurid, -19), 'UTC');
2364 $baseEvent->dtend = clone $baseEvent->dtstart;
2365 $baseEvent->dtend->add($diff);
2367 $baseEvent->base_event_id = $baseEvent->id;
2368 $baseEvent->id = $_recurInstance->id;
2369 $baseEvent->recurid = $_recurInstance->recurid;
2371 $attendee = $baseEvent->attendee;
2372 unset($baseEvent->attendee);
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);
2379 foreach ($attendee as $attender) {
2380 $attender->setId(NULL);
2381 $attender->cal_event_id = $eventInstance->getId();
2383 $attender = $this->_backend->createAttendee($attender);
2384 $eventInstance->attendee->addRecord($attender);
2385 $this->_increaseDisplayContainerContentSequence($attender, $eventInstance, Tinebase_Model_ContainerContent::ACTION_CREATE);
2388 $exceptionAttender = Calendar_Model_Attender::getAttendee($eventInstance->attendee, $_attender);
2391 $exceptionAttender->status = $_attender->status;
2392 $exceptionAttender->transp = $_attender->transp;
2393 $eventInstance->alarms = clone $_recurInstance->alarms;
2394 $eventInstance->alarms->setId(NULL);
2396 $updatedAttender = $this->attenderStatusUpdate($eventInstance, $exceptionAttender, $exceptionAttender->status_authkey);
2398 Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
2399 } catch (Exception $e) {
2400 Tinebase_TransactionManager::getInstance()->rollBack();
2404 return $updatedAttender;
2408 * updates an attender status of a event
2410 * @param Calendar_Model_Event $_event
2411 * @param Calendar_Model_Attender $_attender
2412 * @param string $_authKey
2413 * @return Calendar_Model_Attender updated attender
2415 public function attenderStatusUpdate(Calendar_Model_Event $_event, Calendar_Model_Attender $_attender, $_authKey)
2418 $event = $this->get($_event->getId());
2420 if (! $event->attendee) {
2421 throw new Tinebase_Exception_NotFound('Could not find any attendee of event.');
2424 if (($currentAttender = Calendar_Model_Attender::getAttendee($event->attendee, $_attender)) == null) {
2425 throw new Tinebase_Exception_NotFound('Could not find attender in event.');
2428 $updatedAttender = clone $currentAttender;
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;
2436 Calendar_Controller_Alarm::enforceACL($_event, $event);
2438 $currentAttenderDisplayContainerId = $currentAttender->displaycontainer_id instanceof Tinebase_Model_Container ?
2439 $currentAttender->displaycontainer_id->getId() :
2440 $currentAttender->displaycontainer_id;
2442 $attenderDisplayContainerId = $_attender->displaycontainer_id instanceof Tinebase_Model_Container ?
2443 $_attender->displaycontainer_id->getId() :
2444 $_attender->displaycontainer_id;
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)
2452 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG))
2453 Tinebase_Core::getLogger()->DEBUG(__METHOD__ . '::' . __LINE__ . "no status change -> do nothing");
2454 return $updatedAttender;
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;
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);
2468 $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
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);
2476 Tinebase_Alarm::getInstance()->setAlarmsOfRecord($_event);
2479 $event->attendee->removeRecord($currentAttender);
2480 $event->attendee->addRecord($updatedAttender);
2482 $this->_increaseDisplayContainerContentSequence($updatedAttender, $event);
2484 Tinebase_Record_PersistentObserver::getInstance()->fireEvent(new Calendar_Event_InspectEvent(array(
2485 'observable' => $event
2488 $this->_touch($event, true);
2490 Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
2491 } catch (Exception $e) {
2492 Tinebase_TransactionManager::getInstance()->rollBack();
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);
2502 return $updatedAttender;
2506 * saves all attendee of given event
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
2511 * @todo add support for resources
2513 * @param Calendar_Model_Event $_event
2514 * @param Calendar_Model_Event $_currentEvent
2515 * @param bool $_isRescheduled event got rescheduled reset all attendee status
2517 protected function _saveAttendee($_event, $_currentEvent = NULL, $_isRescheduled = FALSE)
2519 if (! $_event->attendee instanceof Tinebase_Record_RecordSet) {
2520 $_event->attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender');
2523 Calendar_Model_Attender::resolveEmailOnlyAttendee($_event);
2525 $_event->attendee->cal_event_id = $_event->getId();
2527 Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " About to save attendee for event {$_event->id} ");
2529 $currentAttendee = $_currentEvent->attendee;
2531 $diff = $currentAttendee->getMigration($_event->attendee->getArrayOfIds());
2533 $calendar = Tinebase_Container::getInstance()->getContainerById($_event->container_id);
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);
2545 // create/update attendee
2546 foreach ($_event->attendee as $attender) {
2547 $attenderId = $attender->getId();
2548 $idx = ($attenderId) ? $currentAttendee->getIndexById($attenderId) : FALSE;
2550 if ($idx !== FALSE) {
2551 $currentAttender = $currentAttendee[$idx];
2552 $this->_updateAttender($attender, $currentAttender, $_event, $_isRescheduled, $calendar);
2554 $this->_createAttender($attender, $_event, FALSE, $calendar);
2560 * creates a new attender
2562 * @param Calendar_Model_Attender $attender
2563 * @param Tinebase_Model_Container $_calendar
2564 * @param boolean $preserveStatus
2565 * @param Tinebase_Model_Container $calendar
2567 protected function _createAttender(Calendar_Model_Attender $attender, Calendar_Model_Event $event, $preserveStatus = FALSE, Tinebase_Model_Container $calendar = NULL)
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);
2574 $userAccountId = $attender->getUserAccountId();
2576 // generate auth key
2577 if (! $attender->status_authkey) {
2578 $attender->status_authkey = Tinebase_Record_Abstract::generateUID();
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;
2590 $displayCalId = self::getDefaultDisplayContainerId($userAccountId);
2591 $attender->displaycontainer_id = $displayCalId;
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;
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;
2606 $attender->status = Calendar_Model_Attender::STATUS_NEEDSACTION;
2611 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . " New attender: " . print_r($attender->toArray(), TRUE));
2613 Tinebase_Timemachine_ModificationLog::getInstance()->setRecordMetaData($attender, 'create');
2614 $this->_backend->createAttendee($attender);
2615 $this->_increaseDisplayContainerContentSequence($attender, $event, Tinebase_Model_ContainerContent::ACTION_CREATE);
2620 * returns the default calendar
2622 * @return Tinebase_Model_Container
2624 public function getDefaultCalendar()
2626 return Tinebase_Container::getInstance()->getDefaultContainer($this->_applicationName, NULL, Calendar_Preference::DEFAULTCALENDAR);
2630 * returns default displayContainer id of given attendee
2632 * @param string $userAccountId
2634 public static function getDefaultDisplayContainerId($userAccountId)
2636 $userAccountId = Tinebase_Model_User::convertUserIdToInt($userAccountId);
2637 $displayCalId = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::DEFAULTCALENDAR, $userAccountId);
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;
2645 } catch (Exception $e) {
2646 $displayCalId = NULL;
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();
2656 return $displayCalId;
2660 * increases content sequence of attender display container
2662 * @param Calendar_Model_Attender $attender
2663 * @param Calendar_Model_Event $event
2664 * @param string $action
2666 protected function _increaseDisplayContainerContentSequence($attender, $event, $action = Tinebase_Model_ContainerContent::ACTION_UPDATE)
2668 if ($event->container_id === $attender->displaycontainer_id || empty($attender->displaycontainer_id)) {
2669 // no need to increase sequence
2673 Tinebase_Container::getInstance()->increaseContentSequence($attender->displaycontainer_id, $action, $event->getId());
2677 * updates an attender
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
2685 protected function _updateAttender($attender, $currentAttender, $event, $isRescheduled, $calendar = NULL)
2687 $userAccountId = $currentAttender->getUserAccountId();
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;
2698 $attender->displaycontainer_id = $currentAttender->displaycontainer_id;
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) {
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;
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;
2720 $attender->status = Calendar_Model_Attender::STATUS_NEEDSACTION;
2722 $attender->transp = null;
2725 // preserve old authkey
2726 $attender->status_authkey = $currentAttender->status_authkey;
2728 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
2729 . " Updating attender: " . print_r($attender->toArray(), TRUE));
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);
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);
2740 $this->_increaseDisplayContainerContentSequence($attender, $event);
2745 * event handler for group updates
2747 * @param Tinebase_Model_Group $_group
2750 public function onUpdateGroup($_groupId)
2752 $doContainerACLChecks = $this->doContainerACLChecks(FALSE);
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
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))
2764 $events = $this->search($filter, new Tinebase_Model_Pagination(), FALSE, FALSE);
2766 foreach($events as $event) {
2768 if (! $event->rrule) {
2769 // update non recurring futrue events
2770 Calendar_Model_Attender::resolveGroupMembers($event->attendee);
2771 $this->update($event);
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);
2777 if ($nextOccurrence->dtstart != $event->dtstart) {
2778 $this->createRecurException($nextOccurrence, FALSE, TRUE);
2780 $this->update($nextOccurrence);
2783 } catch (Exception $e) {
2784 Tinebase_Core::getLogger()->NOTICE(__METHOD__ . '::' . __LINE__ . " could not update attendee");
2788 $this->doContainerACLChecks($doContainerACLChecks);
2791 /****************************** alarm functions ************************/
2796 * @param Tinebase_Model_Alarm $_alarm
2799 * NOTE: the given alarm is raw and has not passed _inspectAlarmGet
2801 * @todo throw exception on error
2803 public function sendAlarm(Tinebase_Model_Alarm $_alarm)
2805 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " About to send alarm " . print_r($_alarm->toArray(), TRUE));
2807 $doContainerACLChecks = $this->doContainerACLChecks(FALSE);
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);
2818 $this->doContainerACLChecks($doContainerACLChecks);
2820 if ($event->rrule) {
2821 $recurid = $_alarm->getOption('recurid');
2823 // adopts the (referenced) alarm and sets alarm time to next occurance
2824 parent::_inspectAlarmSet($event, $_alarm);
2825 $this->adoptAlarmTime($event, $_alarm, 'instance');
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);
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);
2839 $event->dtstart = new Tinebase_DateTime(substr($recurid, -19));
2841 $event->dtend = clone $event->dtstart;
2842 $event->dtend->add($diff);
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.');
2852 Calendar_Controller_EventNotifications::getInstance()->doSendNotifications($event, Tinebase_Core::getUser(), 'alarm', NULL, array('alarm' => $_alarm));
2856 * send notifications
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
2864 public function doSendNotifications(Tinebase_Record_Interface $_event, Tinebase_Model_FullUser $_updater, $_action, Tinebase_Record_Interface $_oldEvent = NULL, array $_additionalData = array())
2866 Tinebase_ActionQueue::getInstance()->queueAction('Calendar.sendEventNotifications',
2870 $_oldEvent ? $_oldEvent : NULL
2874 public function compareCalendars($cal1, $cal2, $from, $until)
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();
2882 while ($from->isEarlier($until)) {
2884 $endWeek = $from->getClone()->addWeek(1);
2886 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
2887 . ' Comparing period ' . $from . ' - ' . $endWeek);
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;
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');
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);
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);
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');
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');
2923 $matchingEvents->merge($dtStartMatch);
2924 // remove from cal1+cal2
2925 $cal1Events->removeRecord($event);
2926 $cal2Events->removeRecords($dtStartMatch);
2927 $cal2EventIdsAlreadyProcessed = array_merge($cal2EventIdsAlreadyProcessed, $dtStartMatch->getArrayOfIds());
2929 $changedEvents->merge($summaryMatch);
2930 $cal1Events->removeRecord($event);
2931 $cal2Events->removeRecords($summaryMatch);
2932 $cal2EventIdsAlreadyProcessed = array_merge($cal2EventIdsAlreadyProcessed, $summaryMatch->getArrayOfIds());
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);
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)) {
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');
2953 $missingEventsInCal1->addRecord($event);
2958 'matching' => $matchingEvents,
2959 'changed' => $changedEvents,
2960 'missingInCal1' => $missingEventsInCal1,
2961 'missingInCal2' => $missingEventsInCal2,
2966 protected function _getEventsForPeriodAndCalendar($calendarId, $from, $until)
2968 $filter = new Calendar_Model_EventFilter(array(
2969 array('field' => 'period', 'operator' => 'within', 'value' =>
2970 array("from" => $from, "until" => $until)
2972 array('field' => 'container_id', 'operator' => 'equals', 'value' => $calendarId),
2975 $events = Calendar_Controller_Event::getInstance()->search($filter);
2976 Calendar_Model_Rrule::mergeAndRemoveNonMatchingRecurrences($events, $filter);
2981 * add calendar owner as attendee if not already set
2983 * @param string $calendarId
2984 * @param Tinebase_DateTime $from
2985 * @param Tinebase_DateTime $until
2986 * @param boolean $dry run
2988 * @return number of updated events
2990 public function repairAttendee($calendarId, $from, $until, $dry = false)
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!');
2996 if ($container->owner_id !== Tinebase_Core::getUser()->getId()) {
2997 throw new Calendar_Exception('Only allowed for own containers!');
3001 while ($from->isEarlier($until)) {
3002 $endWeek = $from->getClone()->addWeek(1);
3004 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
3005 . ' Repairing period ' . $from . ' - ' . $endWeek);
3008 // TODO we need to detect events with DECLINED/DELETED attendee
3009 $events = $this->_getEventsForPeriodAndCalendar($calendarId, $from, $endWeek);
3013 if (count($events) == 0) {
3014 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
3015 . ' No events found');
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());
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());
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
3038 $event->attendee->addRecord($attender);
3040 $this->update($event);
3047 return $updateCount;
3050 public function sendTentativeNotifications()
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}) {
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};
3064 array('field' => 'period', 'operator' => 'within', 'value' => array(
3065 'from' => Tinebase_DateTime::now(),
3066 'until' => Tinebase_DateTime::now()->addDay($days)
3068 array('field' => 'status', 'operator' => 'equals', 'value' => Calendar_Model_Event::STATUS_TENTATIVE)
3071 if (null !== $additionalFilters) {
3072 $filter = array_merge($filter, $additionalFilters);
3075 $filter = new Calendar_Model_EventFilter($filter);
3076 foreach ($this->search($filter) as $event) {
3077 $eventNotificationController->doSendNotifications($event, null, 'tentative');
3082 * returns active fixed calendars for users (combines config and preference)
3085 * @throws Tinebase_Exception_NotFound
3087 public function getFixedCalendarIds()
3089 $fixedCalendars = (array) Calendar_Config::getInstance()->get(Calendar_Config::FIXED_CALENDARS);
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'];
3101 return $fixedCalendars;