0009954: resource manager and email handling
[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         // lets resolve attendee once as batch to fill cache
156         $attendee = clone $_event->attendee;
157         Calendar_Model_Attender::resolveAttendee($attendee);
158         
159         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__
160             . " " . print_r($_event->toArray(), true));
161         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
162             . " Notification action: " . $_action);
163         
164         switch ($_action) {
165             case 'alarm':
166                 foreach($_event->attendee as $attender) {
167                     if (Calendar_Model_Attender::isAlarmForAttendee($attender, $_alarm)) {
168                         $this->sendNotificationToAttender($attender, $_event, $_updater, $_action, self::NOTIFICATION_LEVEL_NONE);
169                     }
170                 }
171                 break;
172             case 'created':
173             case 'deleted':
174                 foreach($_event->attendee as $attender) {
175                     $this->sendNotificationToAttender($attender, $_event, $_updater, $_action, self::NOTIFICATION_LEVEL_INVITE_CANCEL);
176                 }
177                 break;
178             case 'changed':
179                 $attendeeMigration = Calendar_Model_Attender::getMigration($_oldEvent->attendee, $_event->attendee);
180                 
181                 foreach ($attendeeMigration['toCreate'] as $attender) {
182                     $this->sendNotificationToAttender($attender, $_event, $_updater, 'created', self::NOTIFICATION_LEVEL_INVITE_CANCEL);
183                 }
184                 
185                 foreach ($attendeeMigration['toDelete'] as $attender) {
186                     $this->sendNotificationToAttender($attender, $_oldEvent, $_updater, 'deleted', self::NOTIFICATION_LEVEL_INVITE_CANCEL);
187                 }
188                 
189                 // NOTE: toUpdate are all attendee to be notified
190                 if (count($attendeeMigration['toUpdate']) > 0) {
191                     $updates = $this->_getUpdates($_event, $_oldEvent);
192                     
193                     if (empty($updates)) {
194                         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " empty update, nothing to notify about");
195                         return;
196                     }
197                     
198                     // compute change type
199                     if (count(array_intersect(array('dtstart', 'dtend'), array_keys($updates))) > 0) {
200                         $notificationLevel = self::NOTIFICATION_LEVEL_EVENT_RESCHEDULE;
201                     } else if (count(array_diff(array_keys($updates), array('attendee'))) > 0) {
202                         $notificationLevel = self::NOTIFICATION_LEVEL_EVENT_UPDATE;
203                     } else {
204                         $notificationLevel = self::NOTIFICATION_LEVEL_ATTENDEE_STATUS_UPDATE;
205                     }
206                     
207                     // send notifications
208                     foreach ($attendeeMigration['toUpdate'] as $attender) {
209                         $this->sendNotificationToAttender($attender, $_event, $_updater, 'changed', $notificationLevel, $updates);
210                     }
211                 }
212                 
213                 break;
214                 
215             default:
216                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " unknown action '$_action'");
217                 break;
218                 
219         }
220         
221         // SEND REPLY/COUNTER to external organizer
222         if ($_event->organizer && ! $_event->resolveOrganizer()->account_id && count($_event->attendee) == 1) {
223             $updates = array('attendee' => array('toUpdate' => $_event->attendee));
224             $organizer = new Calendar_Model_Attender(array(
225                 'user_type'  => Calendar_Model_Attender::USERTYPE_USER,
226                 'user_id'    => $_event->resolveOrganizer()
227             ));
228             $this->sendNotificationToAttender($organizer, $_event, $_updater, 'changed', self::NOTIFICATION_LEVEL_ATTENDEE_STATUS_UPDATE, $updates);
229         }
230     }
231     
232     /**
233      * send notification to a single attender
234      * 
235      * @param Calendar_Model_Attender    $_attender
236      * @param Calendar_Model_Event       $_event
237      * @param Tinebase_Model_FullAccount $_updater
238      * @param string                     $_action
239      * @param string                     $_notificationLevel
240      * @param array                      $_updates
241      * @return void
242      */
243     public function sendNotificationToAttender($_attender, $_event, $_updater, $_action, $_notificationLevel, $_updates = NULL)
244     {
245         try {
246             $organizer = $_event->resolveOrganizer();
247             $organizerAccountId = $organizer->account_id;
248             $attendee = $_attender->getResolvedUser();
249             $attendeeAccountId = $_attender->getUserAccountId();
250             
251             $prefUserId = $attendeeAccountId ? $attendeeAccountId :
252                           ($organizerAccountId ? $organizerAccountId : 
253                           ($_event->created_by));
254             
255             try {
256                 $prefUser = Tinebase_User::getInstance()->getFullUserById($prefUserId);
257             } catch (Exception $e) {
258                 $prefUser = Tinebase_Core::getUser();
259                 $prefUserId = $prefUser->getId();
260             }
261             
262             // get prefered language, timezone and notification level
263             $locale = Tinebase_Translation::getLocale(Tinebase_Core::getPreference()->getValueForUser(Tinebase_Preference::LOCALE, $prefUserId));
264             $timezone = Tinebase_Core::getPreference()->getValueForUser(Tinebase_Preference::TIMEZONE, $prefUserId);
265             $translate = Tinebase_Translation::getTranslation('Calendar', $locale);
266             $sendLevel        = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::NOTIFICATION_LEVEL, $prefUserId);
267             $sendOnOwnActions = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::SEND_NOTIFICATION_OF_OWN_ACTIONS, $prefUserId);
268             
269             // external (non account) notification
270             if (!$attendeeAccountId) {
271                 // external organizer needs status updates
272                 $sendLevel = $organizer && $_attender->getEmail() == $organizer->getPreferedEmailAddress() ? 40 : 30;
273                 $sendOnOwnActions = false;
274             }
275             
276             // check if user wants this notification NOTE: organizer gets mails unless she set notificationlevel to NONE
277             // NOTE prefUser is organzier for external notifications
278             if (($attendeeAccountId == $_updater->getId() && ! $sendOnOwnActions) || ($sendLevel < $_notificationLevel && ($attendeeAccountId != $organizerAccountId || $sendLevel == self::NOTIFICATION_LEVEL_NONE))) {
279                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
280                     . " Preferred notification level not reached -> skipping notification for {$_attender->getEmail()}");
281                 return;
282             }
283             
284             $method = NULL;
285             $messageSubject = $this->_getSubject($_event, $_notificationLevel, $_action, $_updates, $timezone, $locale, $translate, $method);
286             
287             $view = new Zend_View();
288             $view->setScriptPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'views');
289             
290             $view->translate    = $translate;
291             $view->timezone     = $timezone;
292             
293             $view->event        = $_event;
294             $view->updater      = $_updater;
295             $view->updates      = $_updates;
296             
297             $messageBody = $view->render('eventNotification.php');
298             
299             $calendarPart = null;
300             $attachments = $this->_getAttachments($method, $_event, $_action, $_updater, $calendarPart);
301             
302             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " receiver: '{$_attender->getEmail()}'");
303             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " subject: '$messageSubject'");
304             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " body: $messageBody");
305             
306             $sender = $_action == 'alarm' ? $prefUser : $_updater;
307         
308             Tinebase_Notification::getInstance()->send($sender, array($attendee), $messageSubject, $messageBody, $calendarPart, $attachments);
309         } catch (Exception $e) {
310             Tinebase_Exception::log($e);
311             return;
312         }
313     }
314     
315     /**
316      * get notification subject and method
317      * 
318      * @param Calendar_Model_Event $_event
319      * @param string $_notificationLevel
320      * @param string $_action
321      * @param array $_updates
322      * @param string $timezone
323      * @param Zend_Locale $locale
324      * @param Zend_Translate $translate
325      * @param atring $method
326      * @return string
327      */
328     protected function _getSubject($_event, $_notificationLevel, $_action, $_updates, $timezone, $locale, $translate, &$method)
329     {
330         $startDateString = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_event->dtstart, $timezone, $locale);
331         $endDateString = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_event->dtend, $timezone, $locale);
332         
333         switch ($_action) {
334             case 'alarm':
335                 $messageSubject = sprintf($translate->_('Alarm for event "%1$s" at %2$s'), $_event->summary, $startDateString);
336                 break;
337             case 'created':
338                 $messageSubject = sprintf($translate->_('Event invitation "%1$s" at %2$s'), $_event->summary, $startDateString);
339                 $method = Calendar_Model_iMIP::METHOD_REQUEST;
340                 break;
341             case 'deleted':
342                 $messageSubject = sprintf($translate->_('Event "%1$s" at %2$s has been canceled' ), $_event->summary, $startDateString);
343                 $method = Calendar_Model_iMIP::METHOD_CANCEL;
344                 break;
345             case 'changed':
346                 switch ($_notificationLevel) {
347                     case self::NOTIFICATION_LEVEL_EVENT_RESCHEDULE:
348                         if ((isset($_updates['dtstart']) || array_key_exists('dtstart', $_updates))) {
349                             $oldStartDateString = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_updates['dtstart'], $timezone, $locale);
350                             $messageSubject = sprintf($translate->_('Event "%1$s" has been rescheduled from %2$s to %3$s' ), $_event->summary, $oldStartDateString, $startDateString);
351                             $method = Calendar_Model_iMIP::METHOD_REQUEST;
352                             break;
353                         }
354                         // fallthrough if dtstart didn't change
355                         
356                     case self::NOTIFICATION_LEVEL_EVENT_UPDATE:
357                         $messageSubject = sprintf($translate->_('Event "%1$s" at %2$s has been updated' ), $_event->summary, $startDateString);
358                         $method = Calendar_Model_iMIP::METHOD_REQUEST;
359                         break;
360                         
361                     case self::NOTIFICATION_LEVEL_ATTENDEE_STATUS_UPDATE:
362                         if(! empty($_updates['attendee']) && ! empty($_updates['attendee']['toUpdate']) && count($_updates['attendee']['toUpdate']) == 1) {
363                             // single attendee status update
364                             $attender = $_updates['attendee']['toUpdate']->getFirstRecord();
365                             
366                             switch ($attender->status) {
367                                 case Calendar_Model_Attender::STATUS_ACCEPTED:
368                                     $messageSubject = sprintf($translate->_('%1$s accepted event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
369                                     break;
370                                     
371                                 case Calendar_Model_Attender::STATUS_DECLINED:
372                                     $messageSubject = sprintf($translate->_('%1$s declined event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
373                                     break;
374                                     
375                                 case Calendar_Model_Attender::STATUS_TENTATIVE:
376                                     $messageSubject = sprintf($translate->_('Tentative response from %1$s for event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
377                                     break;
378                                     
379                                 case Calendar_Model_Attender::STATUS_NEEDSACTION:
380                                     $messageSubject = sprintf($translate->_('No response from %1$s for event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
381                                     break;
382                             }
383                         } else {
384                             $messageSubject = sprintf($translate->_('Attendee changes for event "%1$s" at %2$s' ), $_event->summary, $startDateString);
385                         }
386                         
387                         // we don't send iMIP parts to organizers with an account cause event is already up to date
388                         if ($_event->organizer && !$_event->resolveOrganizer()->account_id) {
389                             $method = Calendar_Model_iMIP::METHOD_REPLY;
390                         }
391                         break;
392                 }
393                 break;
394             default:
395                 $messageSubject = 'unknown action';
396                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " unknown action '$_action'");
397                 break;
398         }
399         
400         return $messageSubject;
401     }
402     
403     /**
404      * get notification attachments
405      * 
406      * @param string $method
407      * @param Calendar_Model_Event $_event
408      * @param string $_action
409      * @param Tinebase_Model_FullAccount $_updater
410      * @param Zend_Mime_Part $calendarPart
411      * @return array
412      */
413     protected function _getAttachments($method, $_event, $_action, $_updater, &$calendarPart)
414     {
415         if ($method === NULL) {
416             return array();
417         }
418         
419         $converter = Calendar_Convert_Event_VCalendar_Factory::factory(Calendar_Convert_Event_VCalendar_Factory::CLIENT_GENERIC);
420         $converter->setMethod($method);
421         $vcalendar = $converter->fromTine20Model($_event);
422
423         // in Tine 2.0 non organizers might be given the grant to update events
424         // @see rfc6047 section 2.2.1 & rfc5545 section 3.2.18
425         if ($method != Calendar_Model_iMIP::METHOD_REPLY && $_event->organizer !== $_updater->contact_id) {
426             foreach ($vcalendar->children() as $component) {
427                 if ($component->name == 'VEVENT') {
428                     if (isset($component->{'ORGANIZER'})) {
429                         $component->{'ORGANIZER'}->add('SENT-BY', 'mailto:' . $_updater->accountEmailAddress);
430                     }
431                 }
432             }
433         }
434         
435         // @TODO in Tine 2.0 status updater might not be updater
436         if ($method == Calendar_Model_iMIP::METHOD_REPLY) {
437             foreach ($vcalendar->children() as $component) {
438                 if ($component->name == 'VEVENT') {
439                     $component->{'REQUEST-STATUS'} = '2.0;Success';
440                 }
441             }
442         }
443         
444         $calendarPart           = new Zend_Mime_Part($vcalendar->serialize());
445         $calendarPart->charset  = 'UTF-8';
446         $calendarPart->type     = 'text/calendar; method=' . $method;
447         $calendarPart->encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE;
448         
449         $attachment = new Zend_Mime_Part($vcalendar->serialize());
450         $attachment->type     = 'application/ics';
451         $attachment->encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE;
452         $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
453         $attachment->filename = 'event.ics';
454         
455         $attachments = array($attachment);
456         
457         // add other attachments (only on invitation)
458         if ($_action == 'created') {
459             $eventAttachments = $this->_getEventAttachments($_event);
460             $attachments = array_merge($attachments, $eventAttachments);
461         }
462         
463         return $attachments;
464     }
465     
466     /**
467      * get event attachments
468      * 
469      * @param Calendar_Model_Event $_event
470      * @return array of Zend_Mime_Part
471      */
472     protected function _getEventAttachments($_event)
473     {
474         $attachments = array();
475         foreach ($_event->attachments as $attachment) {
476             if ($attachment->size < self::INVITATION_ATTACHMENT_MAX_FILESIZE) {
477                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
478                     . " Adding attachment " . $attachment->name . ' to invitation mail');
479                 
480                 $path = Tinebase_Model_Tree_Node_Path::STREAMWRAPPERPREFIX
481                     . Tinebase_FileSystem_RecordAttachments::getInstance()->getRecordAttachmentPath($_event)
482                     . '/' . $attachment->name;
483                 
484                 $handle = fopen($path, 'r');
485                 $stream = fopen("php://temp", 'r+');
486                 stream_copy_to_stream($handle, $stream);
487                 rewind($stream);
488
489                 $part              = new Zend_Mime_Part($stream);
490                 $part->encoding    = Zend_Mime::ENCODING_BASE64; // ?
491                 $part->filename    = $attachment->name;
492                 $part->setTypeAndDispositionForAttachment($attachment->contenttype, $attachment->name);
493                 
494                 fclose($handle);
495                 
496                 $attachments[] = $part;
497                 
498             } else {
499                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
500                     . " Not adding attachment " . $attachment->name . ' to invitation mail (size: ' . convertToMegabytes($attachment-size) . ')');
501             }
502         }
503         
504         return $attachments;
505     }
506  }