0010048: config for notifications for past events
[tine20] / tine20 / Calendar / Controller / EventNotifications.php
1 <?php
2 /**
3  * Calendar Event Notifications
4  * 
5  * @package     Calendar
6  * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
7  * @author      Cornelius Weiss <c.weiss@metaways.de>
8  * @copyright   Copyright (c) 2009-2013 Metaways Infosystems GmbH (http://www.metaways.de)
9  */
10
11 /**
12  * Calendar Event Notifications
13  *
14  * @package     Calendar
15  */
16  class Calendar_Controller_EventNotifications
17  {
18      const NOTIFICATION_LEVEL_NONE                      =  0;
19      const NOTIFICATION_LEVEL_INVITE_CANCEL             = 10;
20      const NOTIFICATION_LEVEL_EVENT_RESCHEDULE          = 20;
21      const NOTIFICATION_LEVEL_EVENT_UPDATE              = 30;
22      const NOTIFICATION_LEVEL_ATTENDEE_STATUS_UPDATE    = 40;
23      
24      const INVITATION_ATTACHMENT_MAX_FILESIZE           = 2097152; // 2 MB
25      
26     /**
27      * @var Calendar_Controller_EventNotifications
28      */
29     private static $_instance = NULL;
30     
31     /**
32      * don't clone. Use the singleton.
33      *
34      */
35     private function __clone() 
36     {
37     }
38     
39     /**
40      * the singleton pattern
41      *
42      * @return Calendar_Controller_EventNotifications
43      */
44     public static function getInstance() 
45     {
46         if (self::$_instance === NULL) {
47             self::$_instance = new Calendar_Controller_EventNotifications();
48         }
49         
50         return self::$_instance;
51     }
52     
53     /**
54      * constructor
55      * 
56      */
57     private function __construct()
58     {
59         
60     }
61     
62     /**
63      * get updates of human interest
64      * 
65      * @param  Calendar_Model_Event $_event
66      * @param  Calendar_Model_Event $_oldEvent
67      * @return array
68      */
69     protected function _getUpdates($_event, $_oldEvent)
70     {
71         // check event details
72         $diff = $_event->diff($_oldEvent)->diff;
73         
74         $orderedUpdateFieldOfInterest = array(
75             'dtstart', 'dtend', 'rrule', 'summary', 'location', 'description',
76             'transp', 'priority', 'status', 'class',
77             'url', 'is_all_day_event', 'originator_tz', /*'tags', 'notes',*/
78         );
79         
80         $updates = array();
81         foreach ($orderedUpdateFieldOfInterest as $field) {
82             if ((isset($diff[$field]) || array_key_exists($field, $diff))) {
83                 $updates[$field] = $diff[$field];
84             }
85         }
86         
87         // rrule legacy
88         if ((isset($updates['rrule']) || array_key_exists('rrule', $updates))) {
89             $updates['rrule'] = $_oldEvent->rrule;
90         }
91         
92         // check for organizer update
93         if (Tinebase_Record_Abstract::convertId($_event['organizer'], 'Addressbook_Model_Contact') != 
94             Tinebase_Record_Abstract::convertId($_oldEvent['organizer'], 'Addressbook_Model_Contact')) {
95             
96             $updates['organizer'] = $_event->resolveOrganizer();
97         }
98         
99         // check attendee updates
100         $attendeeMigration = Calendar_Model_Attender::getMigration($_oldEvent->attendee, $_event->attendee);
101         foreach ($attendeeMigration['toUpdate'] as $attendee) {
102             $oldAttendee = Calendar_Model_Attender::getAttendee($_oldEvent->attendee, $attendee);
103             if ($attendee->status == $oldAttendee->status) {
104                 $attendeeMigration['toUpdate']->removeRecord($attendee);
105             }
106         }
107         
108         foreach($attendeeMigration as $action => $migration) {
109             Calendar_Model_Attender::resolveAttendee($migration, FALSE);
110             if (! count($migration)) {
111                 unset($attendeeMigration[$action]);
112             }
113         }
114         
115         if (! empty($attendeeMigration)) {
116             $updates['attendee'] = $attendeeMigration;
117         }
118         
119         return $updates;
120     }
121     
122     /**
123      * send notifications 
124      * 
125      * @param Calendar_Model_Event       $_event
126      * @param Tinebase_Model_FullAccount $_updater
127      * @param Sting                      $_action
128      * @param Calendar_Model_Event       $_oldEvent
129      * @param Tinebase_Model_Alarm       $_alarm
130      * @return void
131      */
132     public function doSendNotifications($_event, $_updater, $_action, $_oldEvent=NULL, $_alarm=NULL)
133     {
134         // we only send notifications to attendee
135         if (! $_event->attendee instanceof Tinebase_Record_RecordSet) {
136             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
137                 . " Event has no attendee");
138             return;
139         }
140
141         if ($_event->dtend === NULL) {
142             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
143                 . " ". print_r($_event->toArray(), TRUE));
144             throw new Tinebase_Exception_UnexpectedValue('no dtend set in event');
145         }
146         
147         if (Tinebase_DateTime::now()->subHour(1)->isLater($_event->dtend)) {
148             if ($_action == 'alarm' || ! ($_event->isRecurException() || $_event->rrule)) {
149                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
150                     . " Skip notifications to past events");
151                 return;
152             }
153         }
154         
155         $notificationPeriodConfig = Calendar_Config::getInstance()->get(Calendar_Config::MAX_NOTIFICATION_PERIOD_FROM);
156         if (Tinebase_DateTime::now()->subWeek($notificationPeriodConfig)->isLater($_event->dtend)) {
157             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
158                 . " Skip notifications to past events (MAX_NOTIFICATION_PERIOD_FROM: " . $notificationPeriodConfig . " week(s))");
159             return;
160         }
161         
162         // lets resolve attendee once as batch to fill cache
163         $attendee = clone $_event->attendee;
164         Calendar_Model_Attender::resolveAttendee($attendee);
165         
166         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
167             . " " . print_r($_event->toArray(), true));
168         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
169             . " Notification action: " . $_action);
170         
171         switch ($_action) {
172             case 'alarm':
173                 foreach($_event->attendee as $attender) {
174                     if (Calendar_Model_Attender::isAlarmForAttendee($attender, $_alarm)) {
175                         $this->sendNotificationToAttender($attender, $_event, $_updater, $_action, self::NOTIFICATION_LEVEL_NONE);
176                     }
177                 }
178                 break;
179             case 'created':
180             case 'deleted':
181                 foreach($_event->attendee as $attender) {
182                     $this->sendNotificationToAttender($attender, $_event, $_updater, $_action, self::NOTIFICATION_LEVEL_INVITE_CANCEL);
183                 }
184                 break;
185             case 'changed':
186                 $attendeeMigration = Calendar_Model_Attender::getMigration($_oldEvent->attendee, $_event->attendee);
187                 
188                 foreach ($attendeeMigration['toCreate'] as $attender) {
189                     $this->sendNotificationToAttender($attender, $_event, $_updater, 'created', self::NOTIFICATION_LEVEL_INVITE_CANCEL);
190                 }
191                 
192                 foreach ($attendeeMigration['toDelete'] as $attender) {
193                     $this->sendNotificationToAttender($attender, $_oldEvent, $_updater, 'deleted', self::NOTIFICATION_LEVEL_INVITE_CANCEL);
194                 }
195                 
196                 // NOTE: toUpdate are all attendee to be notified
197                 if (count($attendeeMigration['toUpdate']) > 0) {
198                     $updates = $this->_getUpdates($_event, $_oldEvent);
199                     
200                     if (empty($updates)) {
201                         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " empty update, nothing to notify about");
202                         return;
203                     }
204                     
205                     // compute change type
206                     if (count(array_intersect(array('dtstart', 'dtend'), array_keys($updates))) > 0) {
207                         $notificationLevel = self::NOTIFICATION_LEVEL_EVENT_RESCHEDULE;
208                     } else if (count(array_diff(array_keys($updates), array('attendee'))) > 0) {
209                         $notificationLevel = self::NOTIFICATION_LEVEL_EVENT_UPDATE;
210                     } else {
211                         $notificationLevel = self::NOTIFICATION_LEVEL_ATTENDEE_STATUS_UPDATE;
212                     }
213                     
214                     // send notifications
215                     foreach ($attendeeMigration['toUpdate'] as $attender) {
216                         $this->sendNotificationToAttender($attender, $_event, $_updater, 'changed', $notificationLevel, $updates);
217                     }
218                 }
219                 
220                 break;
221                 
222             default:
223                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " unknown action '$_action'");
224                 break;
225                 
226         }
227         
228         // SEND REPLY/COUNTER to external organizer
229         if ($_event->organizer && ! $_event->resolveOrganizer()->account_id && count($_event->attendee) == 1) {
230             $updates = array('attendee' => array('toUpdate' => $_event->attendee));
231             $organizer = new Calendar_Model_Attender(array(
232                 'user_type'  => Calendar_Model_Attender::USERTYPE_USER,
233                 'user_id'    => $_event->resolveOrganizer()
234             ));
235             $this->sendNotificationToAttender($organizer, $_event, $_updater, 'changed', self::NOTIFICATION_LEVEL_ATTENDEE_STATUS_UPDATE, $updates);
236         }
237     }
238     
239     /**
240      * send notification to a single attender
241      * 
242      * @param Calendar_Model_Attender    $_attender
243      * @param Calendar_Model_Event       $_event
244      * @param Tinebase_Model_FullAccount $_updater
245      * @param string                     $_action
246      * @param string                     $_notificationLevel
247      * @param array                      $_updates
248      * @return void
249      */
250     public function sendNotificationToAttender($_attender, $_event, $_updater, $_action, $_notificationLevel, $_updates = NULL)
251     {
252         try {
253             $organizer = $_event->resolveOrganizer();
254             $organizerAccountId = $organizer->account_id;
255             $attendee = $_attender->getResolvedUser();
256             $attendeeAccountId = $_attender->getUserAccountId();
257             
258             $prefUserId = $attendeeAccountId ? $attendeeAccountId :
259                           ($organizerAccountId ? $organizerAccountId : 
260                           ($_event->created_by));
261             
262             try {
263                 $prefUser = Tinebase_User::getInstance()->getFullUserById($prefUserId);
264             } catch (Exception $e) {
265                 $prefUser = Tinebase_Core::getUser();
266                 $prefUserId = $prefUser->getId();
267             }
268             
269             // get prefered language, timezone and notification level
270             $locale = Tinebase_Translation::getLocale(Tinebase_Core::getPreference()->getValueForUser(Tinebase_Preference::LOCALE, $prefUserId));
271             $timezone = Tinebase_Core::getPreference()->getValueForUser(Tinebase_Preference::TIMEZONE, $prefUserId);
272             $translate = Tinebase_Translation::getTranslation('Calendar', $locale);
273             $sendLevel        = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::NOTIFICATION_LEVEL, $prefUserId);
274             $sendOnOwnActions = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::SEND_NOTIFICATION_OF_OWN_ACTIONS, $prefUserId);
275             
276             // external (non account) notification
277             if (!$attendeeAccountId) {
278                 // external organizer needs status updates
279                 $sendLevel = $organizer && $_attender->getEmail() == $organizer->getPreferedEmailAddress() ? 40 : 30;
280                 $sendOnOwnActions = false;
281             }
282             
283             // check if user wants this notification NOTE: organizer gets mails unless she set notificationlevel to NONE
284             // NOTE prefUser is organzier for external notifications
285             if (($attendeeAccountId == $_updater->getId() && ! $sendOnOwnActions) || ($sendLevel < $_notificationLevel && ($attendeeAccountId != $organizerAccountId || $sendLevel == self::NOTIFICATION_LEVEL_NONE))) {
286                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
287                     . " Preferred notification level not reached -> skipping notification for {$_attender->getEmail()}");
288                 return;
289             }
290             
291             $method = NULL;
292             $messageSubject = $this->_getSubject($_event, $_notificationLevel, $_action, $_updates, $timezone, $locale, $translate, $method);
293             
294             $view = new Zend_View();
295             $view->setScriptPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'views');
296             
297             $view->translate    = $translate;
298             $view->timezone     = $timezone;
299             
300             $view->event        = $_event;
301             $view->updater      = $_updater;
302             $view->updates      = $_updates;
303             
304             $messageBody = $view->render('eventNotification.php');
305             
306             $calendarPart = null;
307             $attachments = $this->_getAttachments($method, $_event, $_action, $_updater, $calendarPart);
308             
309             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " receiver: '{$_attender->getEmail()}'");
310             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " subject: '$messageSubject'");
311             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " body: $messageBody");
312             
313             $sender = $_action == 'alarm' ? $prefUser : $_updater;
314         
315             Tinebase_Notification::getInstance()->send($sender, array($attendee), $messageSubject, $messageBody, $calendarPart, $attachments);
316         } catch (Exception $e) {
317             Tinebase_Exception::log($e);
318             return;
319         }
320     }
321     
322     /**
323      * get notification subject and method
324      * 
325      * @param Calendar_Model_Event $_event
326      * @param string $_notificationLevel
327      * @param string $_action
328      * @param array $_updates
329      * @param string $timezone
330      * @param Zend_Locale $locale
331      * @param Zend_Translate $translate
332      * @param atring $method
333      * @return string
334      */
335     protected function _getSubject($_event, $_notificationLevel, $_action, $_updates, $timezone, $locale, $translate, &$method)
336     {
337         $startDateString = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_event->dtstart, $timezone, $locale);
338         $endDateString = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_event->dtend, $timezone, $locale);
339         
340         switch ($_action) {
341             case 'alarm':
342                 $messageSubject = sprintf($translate->_('Alarm for event "%1$s" at %2$s'), $_event->summary, $startDateString);
343                 break;
344             case 'created':
345                 $messageSubject = sprintf($translate->_('Event invitation "%1$s" at %2$s'), $_event->summary, $startDateString);
346                 $method = Calendar_Model_iMIP::METHOD_REQUEST;
347                 break;
348             case 'deleted':
349                 $messageSubject = sprintf($translate->_('Event "%1$s" at %2$s has been canceled' ), $_event->summary, $startDateString);
350                 $method = Calendar_Model_iMIP::METHOD_CANCEL;
351                 break;
352             case 'changed':
353                 switch ($_notificationLevel) {
354                     case self::NOTIFICATION_LEVEL_EVENT_RESCHEDULE:
355                         if ((isset($_updates['dtstart']) || array_key_exists('dtstart', $_updates))) {
356                             $oldStartDateString = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_updates['dtstart'], $timezone, $locale);
357                             $messageSubject = sprintf($translate->_('Event "%1$s" has been rescheduled from %2$s to %3$s' ), $_event->summary, $oldStartDateString, $startDateString);
358                             $method = Calendar_Model_iMIP::METHOD_REQUEST;
359                             break;
360                         }
361                         // fallthrough if dtstart didn't change
362                         
363                     case self::NOTIFICATION_LEVEL_EVENT_UPDATE:
364                         $messageSubject = sprintf($translate->_('Event "%1$s" at %2$s has been updated' ), $_event->summary, $startDateString);
365                         $method = Calendar_Model_iMIP::METHOD_REQUEST;
366                         break;
367                         
368                     case self::NOTIFICATION_LEVEL_ATTENDEE_STATUS_UPDATE:
369                         if(! empty($_updates['attendee']) && ! empty($_updates['attendee']['toUpdate']) && count($_updates['attendee']['toUpdate']) == 1) {
370                             // single attendee status update
371                             $attender = $_updates['attendee']['toUpdate']->getFirstRecord();
372                             
373                             switch ($attender->status) {
374                                 case Calendar_Model_Attender::STATUS_ACCEPTED:
375                                     $messageSubject = sprintf($translate->_('%1$s accepted event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
376                                     break;
377                                     
378                                 case Calendar_Model_Attender::STATUS_DECLINED:
379                                     $messageSubject = sprintf($translate->_('%1$s declined event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
380                                     break;
381                                     
382                                 case Calendar_Model_Attender::STATUS_TENTATIVE:
383                                     $messageSubject = sprintf($translate->_('Tentative response from %1$s for event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
384                                     break;
385                                     
386                                 case Calendar_Model_Attender::STATUS_NEEDSACTION:
387                                     $messageSubject = sprintf($translate->_('No response from %1$s for event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
388                                     break;
389                             }
390                         } else {
391                             $messageSubject = sprintf($translate->_('Attendee changes for event "%1$s" at %2$s' ), $_event->summary, $startDateString);
392                         }
393                         
394                         // we don't send iMIP parts to organizers with an account cause event is already up to date
395                         if ($_event->organizer && !$_event->resolveOrganizer()->account_id) {
396                             $method = Calendar_Model_iMIP::METHOD_REPLY;
397                         }
398                         break;
399                 }
400                 break;
401             default:
402                 $messageSubject = 'unknown action';
403                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " unknown action '$_action'");
404                 break;
405         }
406         
407         return $messageSubject;
408     }
409     
410     /**
411      * get notification attachments
412      * 
413      * @param string $method
414      * @param Calendar_Model_Event $_event
415      * @param string $_action
416      * @param Tinebase_Model_FullAccount $_updater
417      * @param Zend_Mime_Part $calendarPart
418      * @return array
419      */
420     protected function _getAttachments($method, $_event, $_action, $_updater, &$calendarPart)
421     {
422         if ($method === NULL) {
423             return array();
424         }
425         
426         $converter = Calendar_Convert_Event_VCalendar_Factory::factory(Calendar_Convert_Event_VCalendar_Factory::CLIENT_GENERIC);
427         $converter->setMethod($method);
428         $vcalendar = $converter->fromTine20Model($_event);
429
430         // in Tine 2.0 non organizers might be given the grant to update events
431         // @see rfc6047 section 2.2.1 & rfc5545 section 3.2.18
432         if ($method != Calendar_Model_iMIP::METHOD_REPLY && $_event->organizer !== $_updater->contact_id) {
433             foreach ($vcalendar->children() as $component) {
434                 if ($component->name == 'VEVENT') {
435                     if (isset($component->{'ORGANIZER'})) {
436                         $component->{'ORGANIZER'}->add('SENT-BY', 'mailto:' . $_updater->accountEmailAddress);
437                     }
438                 }
439             }
440         }
441         
442         // @TODO in Tine 2.0 status updater might not be updater
443         if ($method == Calendar_Model_iMIP::METHOD_REPLY) {
444             foreach ($vcalendar->children() as $component) {
445                 if ($component->name == 'VEVENT') {
446                     $component->{'REQUEST-STATUS'} = '2.0;Success';
447                 }
448             }
449         }
450         
451         $calendarPart           = new Zend_Mime_Part($vcalendar->serialize());
452         $calendarPart->charset  = 'UTF-8';
453         $calendarPart->type     = 'text/calendar; method=' . $method;
454         $calendarPart->encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE;
455         
456         $attachment = new Zend_Mime_Part($vcalendar->serialize());
457         $attachment->type     = 'application/ics';
458         $attachment->encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE;
459         $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
460         $attachment->filename = 'event.ics';
461         
462         $attachments = array($attachment);
463         
464         // add other attachments (only on invitation)
465         if ($_action == 'created') {
466             $eventAttachments = $this->_getEventAttachments($_event);
467             $attachments = array_merge($attachments, $eventAttachments);
468         }
469         
470         return $attachments;
471     }
472     
473     /**
474      * get event attachments
475      * 
476      * @param Calendar_Model_Event $_event
477      * @return array of Zend_Mime_Part
478      */
479     protected function _getEventAttachments($_event)
480     {
481         $attachments = array();
482         foreach ($_event->attachments as $attachment) {
483             if ($attachment->size < self::INVITATION_ATTACHMENT_MAX_FILESIZE) {
484                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
485                     . " Adding attachment " . $attachment->name . ' to invitation mail');
486                 
487                 $path = Tinebase_Model_Tree_Node_Path::STREAMWRAPPERPREFIX
488                     . Tinebase_FileSystem_RecordAttachments::getInstance()->getRecordAttachmentPath($_event)
489                     . '/' . $attachment->name;
490                 
491                 $handle = fopen($path, 'r');
492                 $stream = fopen("php://temp", 'r+');
493                 stream_copy_to_stream($handle, $stream);
494                 rewind($stream);
495
496                 $part              = new Zend_Mime_Part($stream);
497                 $part->encoding    = Zend_Mime::ENCODING_BASE64; // ?
498                 $part->filename    = $attachment->name;
499                 $part->setTypeAndDispositionForAttachment($attachment->contenttype, $attachment->name);
500                 
501                 fclose($handle);
502                 
503                 $attachments[] = $part;
504                 
505             } else {
506                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
507                     . " Not adding attachment " . $attachment->name . ' to invitation mail (size: ' . convertToMegabytes($attachment-size) . ')');
508             }
509         }
510         
511         return $attachments;
512     }
513  }