0010046: config for disabling external imip
[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 = is_object($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             // we don't send iMIP parts to external attendee if config is active
295             if (Calendar_Config::getInstance()->get(Calendar_Config::DISABLE_EXTERNAL_IMIP) && ! $attendeeAccountId) {
296                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
297                     . " External iMIP is disabled.");
298                 $method = NULL;
299             }
300             
301             $view = new Zend_View();
302             $view->setScriptPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'views');
303             
304             $view->translate    = $translate;
305             $view->timezone     = $timezone;
306             
307             $view->event        = $_event;
308             $view->updater      = $_updater;
309             $view->updates      = $_updates;
310             
311             $messageBody = $view->render('eventNotification.php');
312             
313             $calendarPart = null;
314             $attachments = $this->_getAttachments($method, $_event, $_action, $_updater, $calendarPart);
315             
316             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " receiver: '{$_attender->getEmail()}'");
317             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " subject: '$messageSubject'");
318             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " body: $messageBody");
319             
320             $sender = $_action == 'alarm' ? $prefUser : $_updater;
321         
322             Tinebase_Notification::getInstance()->send($sender, array($attendee), $messageSubject, $messageBody, $calendarPart, $attachments);
323         } catch (Exception $e) {
324             Tinebase_Exception::log($e);
325             return;
326         }
327     }
328     
329     /**
330      * get notification subject and method
331      * 
332      * @param Calendar_Model_Event $_event
333      * @param string $_notificationLevel
334      * @param string $_action
335      * @param array $_updates
336      * @param string $timezone
337      * @param Zend_Locale $locale
338      * @param Zend_Translate $translate
339      * @param atring $method
340      * @return string
341      */
342     protected function _getSubject($_event, $_notificationLevel, $_action, $_updates, $timezone, $locale, $translate, &$method)
343     {
344         $startDateString = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_event->dtstart, $timezone, $locale);
345         $endDateString = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_event->dtend, $timezone, $locale);
346         
347         switch ($_action) {
348             case 'alarm':
349                 $messageSubject = sprintf($translate->_('Alarm for event "%1$s" at %2$s'), $_event->summary, $startDateString);
350                 break;
351             case 'created':
352                 $messageSubject = sprintf($translate->_('Event invitation "%1$s" at %2$s'), $_event->summary, $startDateString);
353                 $method = Calendar_Model_iMIP::METHOD_REQUEST;
354                 break;
355             case 'deleted':
356                 $messageSubject = sprintf($translate->_('Event "%1$s" at %2$s has been canceled' ), $_event->summary, $startDateString);
357                 $method = Calendar_Model_iMIP::METHOD_CANCEL;
358                 break;
359             case 'changed':
360                 switch ($_notificationLevel) {
361                     case self::NOTIFICATION_LEVEL_EVENT_RESCHEDULE:
362                         if ((isset($_updates['dtstart']) || array_key_exists('dtstart', $_updates))) {
363                             $oldStartDateString = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_updates['dtstart'], $timezone, $locale);
364                             $messageSubject = sprintf($translate->_('Event "%1$s" has been rescheduled from %2$s to %3$s' ), $_event->summary, $oldStartDateString, $startDateString);
365                             $method = Calendar_Model_iMIP::METHOD_REQUEST;
366                             break;
367                         }
368                         // fallthrough if dtstart didn't change
369                         
370                     case self::NOTIFICATION_LEVEL_EVENT_UPDATE:
371                         $messageSubject = sprintf($translate->_('Event "%1$s" at %2$s has been updated' ), $_event->summary, $startDateString);
372                         $method = Calendar_Model_iMIP::METHOD_REQUEST;
373                         break;
374                         
375                     case self::NOTIFICATION_LEVEL_ATTENDEE_STATUS_UPDATE:
376                         if(! empty($_updates['attendee']) && ! empty($_updates['attendee']['toUpdate']) && count($_updates['attendee']['toUpdate']) == 1) {
377                             // single attendee status update
378                             $attender = $_updates['attendee']['toUpdate']->getFirstRecord();
379                             
380                             switch ($attender->status) {
381                                 case Calendar_Model_Attender::STATUS_ACCEPTED:
382                                     $messageSubject = sprintf($translate->_('%1$s accepted event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
383                                     break;
384                                     
385                                 case Calendar_Model_Attender::STATUS_DECLINED:
386                                     $messageSubject = sprintf($translate->_('%1$s declined event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
387                                     break;
388                                     
389                                 case Calendar_Model_Attender::STATUS_TENTATIVE:
390                                     $messageSubject = sprintf($translate->_('Tentative response from %1$s for event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
391                                     break;
392                                     
393                                 case Calendar_Model_Attender::STATUS_NEEDSACTION:
394                                     $messageSubject = sprintf($translate->_('No response from %1$s for event "%2$s" at %3$s' ), $attender->getName(), $_event->summary, $startDateString);
395                                     break;
396                             }
397                         } else {
398                             $messageSubject = sprintf($translate->_('Attendee changes for event "%1$s" at %2$s' ), $_event->summary, $startDateString);
399                         }
400                         
401                         // we don't send iMIP parts to organizers with an account cause event is already up to date
402                         if ($_event->organizer && !$_event->resolveOrganizer()->account_id) {
403                             $method = Calendar_Model_iMIP::METHOD_REPLY;
404                         }
405                         break;
406                 }
407                 break;
408             default:
409                 $messageSubject = 'unknown action';
410                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " unknown action '$_action'");
411                 break;
412         }
413         
414         return $messageSubject;
415     }
416     
417     /**
418      * get notification attachments
419      * 
420      * @param string $method
421      * @param Calendar_Model_Event $_event
422      * @param string $_action
423      * @param Tinebase_Model_FullAccount $_updater
424      * @param Zend_Mime_Part $calendarPart
425      * @return array
426      */
427     protected function _getAttachments($method, $_event, $_action, $_updater, &$calendarPart)
428     {
429         if ($method === NULL) {
430             return array();
431         }
432         
433         $converter = Calendar_Convert_Event_VCalendar_Factory::factory(Calendar_Convert_Event_VCalendar_Factory::CLIENT_GENERIC);
434         $converter->setMethod($method);
435         $vcalendar = $converter->fromTine20Model($_event);
436
437         // in Tine 2.0 non organizers might be given the grant to update events
438         // @see rfc6047 section 2.2.1 & rfc5545 section 3.2.18
439         if ($method != Calendar_Model_iMIP::METHOD_REPLY && $_event->organizer !== $_updater->contact_id) {
440             foreach ($vcalendar->children() as $component) {
441                 if ($component->name == 'VEVENT') {
442                     if (isset($component->{'ORGANIZER'})) {
443                         $component->{'ORGANIZER'}->add('SENT-BY', 'mailto:' . $_updater->accountEmailAddress);
444                     }
445                 }
446             }
447         }
448         
449         // @TODO in Tine 2.0 status updater might not be updater
450         if ($method == Calendar_Model_iMIP::METHOD_REPLY) {
451             foreach ($vcalendar->children() as $component) {
452                 if ($component->name == 'VEVENT') {
453                     $component->{'REQUEST-STATUS'} = '2.0;Success';
454                 }
455             }
456         }
457         
458         $calendarPart           = new Zend_Mime_Part($vcalendar->serialize());
459         $calendarPart->charset  = 'UTF-8';
460         $calendarPart->type     = 'text/calendar; method=' . $method;
461         $calendarPart->encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE;
462         
463         $attachment = new Zend_Mime_Part($vcalendar->serialize());
464         $attachment->type     = 'application/ics';
465         $attachment->encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE;
466         $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
467         $attachment->filename = 'event.ics';
468         
469         $attachments = array($attachment);
470         
471         // add other attachments (only on invitation)
472         if ($_action == 'created') {
473             $eventAttachments = $this->_getEventAttachments($_event);
474             $attachments = array_merge($attachments, $eventAttachments);
475         }
476         
477         return $attachments;
478     }
479     
480     /**
481      * get event attachments
482      * 
483      * @param Calendar_Model_Event $_event
484      * @return array of Zend_Mime_Part
485      */
486     protected function _getEventAttachments($_event)
487     {
488         $attachments = array();
489         foreach ($_event->attachments as $attachment) {
490             if ($attachment->size < self::INVITATION_ATTACHMENT_MAX_FILESIZE) {
491                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
492                     . " Adding attachment " . $attachment->name . ' to invitation mail');
493                 
494                 $path = Tinebase_Model_Tree_Node_Path::STREAMWRAPPERPREFIX
495                     . Tinebase_FileSystem_RecordAttachments::getInstance()->getRecordAttachmentPath($_event)
496                     . '/' . $attachment->name;
497                 
498                 $handle = fopen($path, 'r');
499                 $stream = fopen("php://temp", 'r+');
500                 stream_copy_to_stream($handle, $stream);
501                 rewind($stream);
502
503                 $part              = new Zend_Mime_Part($stream);
504                 $part->encoding    = Zend_Mime::ENCODING_BASE64; // ?
505                 $part->filename    = $attachment->name;
506                 $part->setTypeAndDispositionForAttachment($attachment->contenttype, $attachment->name);
507                 
508                 fclose($handle);
509                 
510                 $attachments[] = $part;
511                 
512             } else {
513                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
514                     . " Not adding attachment " . $attachment->name . ' to invitation mail (size: ' . convertToMegabytes($attachment-size) . ')');
515             }
516         }
517         
518         return $attachments;
519     }
520  }