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