ce49b34558729079dd231829963decab134a7db7
[citadel.git] / webcit / calendar.c
1 // Functions which handle calendar objects and their processing/display.
2 //
3 // Copyright (c) 1996-2022 by the citadel.org team
4 //
5 // This program is open source software.  You can redistribute it and/or
6 // modify it under the terms of the GNU General Public License, version 3.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
12
13 #include "webcit.h"
14 #include "webserver.h"
15 #include "calendar.h"
16
17 // Process a calendar object.  At this point it's already been deserialized by cal_process_attachment()
18 //
19 // cal:                 the calendar object
20 // recursion_level:     Number of times we've recursed into this function
21 // msgnum:              Message number on the Citadel server
22 // cal_partnum:         MIME part number within that message containing the calendar object
23 void cal_process_object(StrBuf *Target,
24                         icalcomponent *cal,
25                         int recursion_level,
26                         long msgnum,
27                         const char *cal_partnum) 
28 {
29         icalcomponent *c;
30         icalproperty *method = NULL;
31         icalproperty_method the_method = ICAL_METHOD_NONE;
32         icalproperty *p;
33         struct icaltimetype t;
34         time_t tt;
35         char buf[256];
36         char conflict_name[256];
37         char conflict_message[256];
38         int is_update = 0;
39         char divname[32];
40         static int divcount = 0;
41         const char *ch;
42
43         sprintf(divname, "rsvp%04x", ++divcount);
44
45         // Convert timezones to something easy to display.
46         // It's safe to do this in memory because we're only changing it on the
47         // display side -- when we tell the server to do something with the object,
48         // the server will be working with its original copy in the database.
49         if ((cal) && (recursion_level == 0)) {
50                 ical_dezonify(cal);
51         }
52
53         // Leading HTML for the display of this object
54         if (recursion_level == 0) {
55                 StrBufAppendPrintf(Target, "<div class=\"mimepart\">\n");
56         }
57
58         // Look for a method
59         method = icalcomponent_get_first_property(cal, ICAL_METHOD_PROPERTY);
60
61         // See what we need to do with this
62         if (method != NULL) {
63                 char *title;
64                 the_method = icalproperty_get_method(method);
65
66                 StrBufAppendPrintf(Target, "<div id=\"%s_title\">", divname);
67                 StrBufAppendPrintf(Target, "<img src=\"static/webcit_icons/essen/32x32/calendar.png\">");
68                 StrBufAppendPrintf(Target, "<span>");
69                 switch(the_method) {
70                 case ICAL_METHOD_REQUEST:
71                         title = _("Meeting invitation");
72                         break;
73                 case ICAL_METHOD_REPLY:
74                         title = _("Attendee's reply to your invitation");
75                         break;
76                 case ICAL_METHOD_PUBLISH:
77                         title = _("Published event");
78                         break;
79                 default:
80                         title = _("This is an unknown type of calendar item.");
81                         break;
82                 }
83                 StrBufAppendPrintf(Target, "</span>");
84
85                 StrBufAppendPrintf(Target, "&nbsp;&nbsp;%s",title);
86                 StrBufAppendPrintf(Target, "</div>");
87         }
88
89         StrBufAppendPrintf(Target, "<dl>");
90         p = icalcomponent_get_first_property(cal, ICAL_SUMMARY_PROPERTY);
91         if (p != NULL) {
92                 StrBufAppendPrintf(Target, "<dt>");
93                 StrBufAppendPrintf(Target, _("Summary:"));
94                 StrBufAppendPrintf(Target, "</dt><dd>");
95                 StrEscAppend(Target, NULL, (char *)icalproperty_get_comment(p), 0, 0);
96                 StrBufAppendPrintf(Target, "</dd>\n");
97         }
98
99         p = icalcomponent_get_first_property(cal, ICAL_LOCATION_PROPERTY);
100         if (p != NULL) {
101                 StrBufAppendPrintf(Target, "<dt>");
102                 StrBufAppendPrintf(Target, _("Location:"));
103                 StrBufAppendPrintf(Target, "</dt><dd>");
104                 StrEscAppend(Target, NULL, (char *)icalproperty_get_comment(p), 0, 0);
105                 StrBufAppendPrintf(Target, "</dd>\n");
106         }
107
108         // Only show start/end times if we're actually looking at the VEVENT
109         // component.  Otherwise it shows bogus dates for things like timezone.
110         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
111
112                 p = icalcomponent_get_first_property(cal, ICAL_DTSTART_PROPERTY);
113                 if (p != NULL) {
114                         t = icalproperty_get_dtstart(p);
115
116                         if (t.is_date) {
117                                 struct tm d_tm;
118                                 char d_str[32];
119                                 memset(&d_tm, 0, sizeof d_tm);
120                                 d_tm.tm_year = t.year - 1900;
121                                 d_tm.tm_mon = t.month - 1;
122                                 d_tm.tm_mday = t.day;
123                                 wc_strftime(d_str, sizeof d_str, "%x", &d_tm);
124                                 StrBufAppendPrintf(Target, "<dt>");
125                                 StrBufAppendPrintf(Target, _("Date:"));
126                                 StrBufAppendPrintf(Target, "</dt><dd>%s</dd>", d_str);
127                         }
128                         else {
129                                 tt = icaltime_as_timet(t);
130                                 webcit_fmt_date(buf, 256, tt, DATEFMT_FULL);
131                                 StrBufAppendPrintf(Target, "<dt>");
132                                 StrBufAppendPrintf(Target, _("Starting date/time:"));
133                                 StrBufAppendPrintf(Target, "</dt><dd>%s</dd>", buf);
134                         }
135                 }
136         
137                 p = icalcomponent_get_first_property(cal, ICAL_DTEND_PROPERTY);
138                 if (p != NULL) {
139                         t = icalproperty_get_dtend(p);
140                         tt = icaltime_as_timet(t);
141                         webcit_fmt_date(buf, 256, tt, DATEFMT_FULL);
142                         StrBufAppendPrintf(Target, "<dt>");
143                         StrBufAppendPrintf(Target, _("Ending date/time:"));
144                         StrBufAppendPrintf(Target, "</dt><dd>%s</dd>", buf);
145                 }
146
147         }
148
149         p = icalcomponent_get_first_property(cal, ICAL_DESCRIPTION_PROPERTY);
150         if (p != NULL) {
151                 StrBufAppendPrintf(Target, "<dt>");
152                 StrBufAppendPrintf(Target, _("Description:"));
153                 StrBufAppendPrintf(Target, "</dt><dd>");
154                 StrEscAppend(Target, NULL, (char *)icalproperty_get_comment(p), 0, 0);
155                 StrBufAppendPrintf(Target, "</dd>\n");
156         }
157
158         if (icalcomponent_get_first_property(cal, ICAL_RRULE_PROPERTY)) {
159                 // Unusual string syntax used here in order to re-use existing translations
160                 StrBufAppendPrintf(Target, "<dt>%s:</dt><dd>%s.</dd>\n",
161                         _("Recurrence"),
162                         _("This is a recurring event")
163                 );
164         }
165
166         // If the component has attendees, iterate through them.
167         for (p = icalcomponent_get_first_property(cal, ICAL_ATTENDEE_PROPERTY); 
168              (p != NULL); 
169              p = icalcomponent_get_next_property(cal, ICAL_ATTENDEE_PROPERTY)) {
170                 StrBufAppendPrintf(Target, "<dt>");
171                 StrBufAppendPrintf(Target, _("Attendee:"));
172                 StrBufAppendPrintf(Target, "</dt><dd>");
173                 ch = icalproperty_get_attendee(p);
174                 if ((ch != NULL) && !strncasecmp(ch, "MAILTO:", 7)) {
175
176                         // screen name or email address
177                         safestrncpy(buf, ch + 7, sizeof(buf));
178                         string_trim(buf);
179                         StrEscAppend(Target, NULL, buf, 0, 0);
180                         StrBufAppendPrintf(Target, " ");
181
182                         // participant status
183                         partstat_as_string(buf, p);
184                         StrEscAppend(Target, NULL, buf, 0, 0);
185                 }
186                 StrBufAppendPrintf(Target, "</dd>\n");
187         }
188
189         // If the component has subcomponents, recurse through them.
190         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
191                 (c != 0);
192                 c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)
193         ) {
194                 // Recursively process subcomponent
195                 cal_process_object(Target, c, recursion_level+1, msgnum, cal_partnum);
196         }
197
198         // If this is a REQUEST, display conflicts and buttons
199         if (the_method == ICAL_METHOD_REQUEST) {
200
201                 // Check for conflicts
202                 syslog(LOG_DEBUG, "Checking server calendar for conflicts...");
203                 serv_printf("ICAL conflicts|%ld|%s|", msgnum, cal_partnum);
204                 serv_getln(buf, sizeof buf);
205                 if (buf[0] == '1') {
206                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
207                                 extract_token(conflict_name, buf, 3, '|', sizeof conflict_name);
208                                 is_update = extract_int(buf, 4);
209
210                                 if (is_update) {
211                                         snprintf(conflict_message, sizeof conflict_message,
212                                                  _("This is an update of '%s' which is already in your calendar."), conflict_name);
213                                 }
214                                 else {
215                                         snprintf(conflict_message, sizeof conflict_message,
216                                                  _("This event would conflict with '%s' which is already in your calendar."), conflict_name);
217                                 }
218
219                                 StrBufAppendPrintf(Target, "<dt>%s",
220                                         (is_update ?
221                                          _("Update:") :
222                                          _("CONFLICT:")
223                                                 )
224                                         );
225                                 StrBufAppendPrintf(Target, "</dt><dd>");
226                                 StrEscAppend(Target, NULL, conflict_message, 0, 0);
227                                 StrBufAppendPrintf(Target, "</dd>\n");
228                         }
229                 }
230                 syslog(LOG_DEBUG, "...done.\n");
231
232                 StrBufAppendPrintf(Target, "</dl>");
233
234                 // Display the Accept/Decline buttons
235                 StrBufAppendPrintf(Target, "<p id=\"%s_question\">"
236                         "%s "
237                         "&nbsp;&nbsp;&nbsp;<span class=\"button_link\"> "
238                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Accept');\">%s</a>"
239                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
240                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Tentative');\">%s</a>"
241                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
242                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Decline');\">%s</a>"
243                         "</span></p>\n",
244                         divname,
245                         _("How would you like to respond to this invitation?"),
246                         divname, divname, msgnum, cal_partnum, _("Accept"),
247                         divname, divname, msgnum, cal_partnum, _("Tentative"),
248                         divname, divname, msgnum, cal_partnum, _("Decline")
249                         );
250
251         }
252
253         // If this is a REPLY, display update button
254         if (the_method == ICAL_METHOD_REPLY) {
255
256                 // Display the update buttons
257                 StrBufAppendPrintf(Target, "<p id=\"%s_question\" >"
258                         "%s "
259                         "&nbsp;&nbsp;&nbsp;<span class=\"button_link\"> "
260                         "<a href=\"javascript:HandleRSVP('%s_question','%s_title','%ld','%s','Update');\">%s</a>"
261                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
262                         "<a href=\"javascript:HandleRSVP('%s_question','%s_title','%ld','%s','Ignore');\">%s</a>"
263                         "</span></p>\n",
264                         divname,
265                         _("Click <i>Update</i> to accept this reply and update your calendar."),
266                         divname, divname, msgnum, cal_partnum, _("Update"),
267                         divname, divname, msgnum, cal_partnum, _("Ignore")
268                         );
269         
270         }
271         
272         // Trailing HTML for the display of this object
273         if (recursion_level == 0) {
274                 StrBufAppendPrintf(Target, "<p>&nbsp;</p></div>\n");
275         }
276 }
277
278
279 // Deserialize a calendar object in a message so it can be displayed.
280 void cal_process_attachment(wc_mime_attachment *Mime) {
281         icalcomponent *cal;
282
283         cal = icalcomponent_new_from_string(ChrPtr(Mime->Data));
284         FlushStrBuf(Mime->Data);
285         if (cal == NULL) {
286                 StrBufAppendPrintf(Mime->Data, _("There was an error parsing this calendar item."));
287                 StrBufAppendPrintf(Mime->Data, "<br>\n");
288                 return;
289         }
290
291         cal_process_object(Mime->Data, cal, 0, Mime->msgnum, ChrPtr(Mime->PartNum));
292
293         // Free the memory we obtained from libical's constructor
294         icalcomponent_free(cal);
295 }
296
297
298 // Respond to a meeting request - accept/decline meeting
299 void respond_to_request(void) {
300         char buf[1024];
301
302         begin_ajax_response();
303
304         serv_printf("ICAL respond|%s|%s|%s|",
305                 bstr("msgnum"),
306                 bstr("cal_partnum"),
307                 bstr("sc")
308         );
309         serv_getln(buf, sizeof buf);
310
311         if (buf[0] == '2') {
312                 wc_printf("<img src=\"static/webcit_icons/essen/32x32/calendar.png\"><span>");
313                 if (!strcasecmp(bstr("sc"), "accept")) {
314                         wc_printf(_("You have accepted this meeting invitation.  "
315                                 "It has been entered into your calendar.")
316                         );
317                 }
318                 else if (!strcasecmp(bstr("sc"), "tentative")) {
319                         wc_printf(_("You have tentatively accepted this meeting invitation.  "
320                                 "It has been 'pencilled in' to your calendar.")
321                         );
322                 }
323                 else if (!strcasecmp(bstr("sc"), "decline")) {
324                         wc_printf(_("You have declined this meeting invitation.  "
325                                   "It has <b>not</b> been entered into your calendar.")
326                                 );
327                 }
328                 wc_printf(" ");
329                 wc_printf(_("A reply has been sent to the meeting organizer."));
330                 wc_printf("</span>");
331         }
332         else {
333                 wc_printf("<img align=\"center\" src=\"static/webcit_icons/error.gif\"><span>");
334                 wc_printf("%s\n", &buf[4]);
335                 wc_printf("</span>");
336         }
337         end_ajax_response();
338 }
339
340
341 // Handle an incoming RSVP
342 void handle_rsvp(void) {
343         char buf[1024];
344
345         begin_ajax_response();
346
347         serv_printf("ICAL handle_rsvp|%s|%s|%s|",
348                 bstr("msgnum"),
349                 bstr("cal_partnum"),
350                 bstr("sc")
351         );
352         serv_getln(buf, sizeof buf);
353
354         if (buf[0] == '2') {
355                 wc_printf("<img src=\"static/webcit_icons/calendar.png\"><span>");
356                 if (!strcasecmp(bstr("sc"), "update")) {
357                         // Translators: RSVP aka Répondez s'il-vous-plaît is the term 
358                         // that the recipient of an ical-invitation should please 
359                         // answer this request.
360                         wc_printf(_("Your calendar has been updated to reflect this RSVP."));
361                 }
362                 else if (!strcasecmp(bstr("sc"), "ignore")) {
363                         wc_printf(_("You have chosen to ignore this RSVP. "
364                                   "Your calendar has <b>not</b> been updated.")
365                         );
366                 }
367                 wc_printf("</span>");
368         }
369         else {
370                 wc_printf("<img src=\"static/webcit_icons/error.gif\"><span> %s\n", &buf[4]);
371                 wc_printf("</span>");
372         }
373
374         end_ajax_response();
375 }
376
377
378 // free memory allocated using libical
379 void delete_cal(void *vCal) {
380         disp_cal *Cal = (disp_cal*) vCal;
381         icalcomponent_free(Cal->cal);
382         free(Cal->from);
383         free(Cal);
384 }
385
386
387 // This is the meat-and-bones of the first part of our two-phase calendar display.
388 // As we encounter calendar items in messages being read from the server, we break out
389 // any iCalendar objects and store them in a hash table.  Later on, the second phase will
390 // use this hash table to render the calendar for display.
391 void display_individual_cal(icalcomponent *event, long msgnum, char *from, int unread, calview *calv) {
392         icalproperty *ps = NULL;
393         struct icaltimetype dtstart, dtend;
394         struct icaldurationtype dur;
395         wcsession *WCC = WC;
396         disp_cal *Cal;
397         size_t len;
398         time_t final_recurrence = 0;
399         icalcomponent *cptr = NULL;
400
401         // recur variables
402         icalproperty *rrule = NULL;
403         struct icalrecurrencetype recur;
404         icalrecur_iterator *ritr = NULL;
405         struct icaltimetype next;
406         int num_recur = 0;
407         int stop_rr = 0;
408
409         // first and foremost, check for bogosity.  bail if we see no DTSTART property
410         if (icalcomponent_get_first_property(icalcomponent_get_first_component(
411                 event, ICAL_VEVENT_COMPONENT), ICAL_DTSTART_PROPERTY) == NULL
412         ) {
413                 return;
414         }
415
416         // ok, chances are we've got a live one here.  let's try to figure out where it goes.
417
418         dtstart = icaltime_null_time();
419         dtend = icaltime_null_time();
420         
421         if (WCC->disp_cal_items == NULL) {
422                 WCC->disp_cal_items = NewHash(0, Flathash);
423         }
424
425         // Note: anything we do here, we also have to do below for the recurrences.
426         Cal = (disp_cal*) malloc(sizeof(disp_cal));
427         memset(Cal, 0, sizeof(disp_cal));
428         Cal->cal = icalcomponent_new_clone(event);
429
430         // Dezonify and decapsulate at the very last moment
431         ical_dezonify(Cal->cal);
432         if (icalcomponent_isa(Cal->cal) != ICAL_VEVENT_COMPONENT) {
433                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
434                 if (cptr) {
435                         cptr = icalcomponent_new_clone(cptr);
436                         icalcomponent_free(Cal->cal);
437                         Cal->cal = cptr;
438                 }
439         }
440
441         Cal->unread = unread;
442         len = strlen(from);
443         Cal->from = (char*)malloc(len+ 1);
444         memcpy(Cal->from, from, len + 1);
445         Cal->cal_msgnum = msgnum;
446
447         // Precalculate the starting date and time of this event, and store it in our top-level
448         // structure.  Later, when we are rendering the calendar, we can just peek at these values
449         // without having to break apart every calendar item.
450         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTSTART_PROPERTY);
451         if (ps != NULL) {
452                 dtstart = icalproperty_get_dtstart(ps);
453                 Cal->event_start = icaltime_as_timet(dtstart);
454         }
455
456         // Do the same for the ending date and time.  It makes the day view much easier to render.
457         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTEND_PROPERTY);
458         if (ps != NULL) {
459                 dtend = icalproperty_get_dtend(ps);
460                 Cal->event_end = icaltime_as_timet(dtend);
461         }
462
463         // Store it in the hash list.
464         // syslog(LOG_DEBUG, "INITIAL: %s", ctime(&Cal->event_start));
465         Put(WCC->disp_cal_items, (char*) &Cal->event_start, sizeof(Cal->event_start), Cal, delete_cal);
466
467         //***************************** handle recurring events ******************************
468
469         if (icaltime_is_null_time(dtstart)) return;     /* Can't recur without a start time */
470
471         if (!icaltime_is_null_time(dtend)) {            /* Need duration for recurrences */
472                 dur = icaltime_subtract(dtend, dtstart);
473         }
474         else {
475                 dur = icaltime_subtract(dtstart, dtstart);
476         }
477
478         /*
479          * Just let libical iterate the recurrence, and keep looping back to the top of this function,
480          * adding new hash entries that all point back to the same msgnum, until either the iteration
481          * stops or some outer bound is reached.  The display code will automatically do the Right Thing.
482          */
483         cptr = event;
484         if (icalcomponent_isa(cptr) != ICAL_VEVENT_COMPONENT) {
485                 cptr = icalcomponent_get_first_component(cptr, ICAL_VEVENT_COMPONENT);
486         }
487         if (!cptr) return;
488         ps = icalcomponent_get_first_property(cptr, ICAL_DTSTART_PROPERTY);
489         if (ps == NULL) return;
490         dtstart = icalproperty_get_dtstart(ps);
491         rrule = icalcomponent_get_first_property(cptr, ICAL_RRULE_PROPERTY);
492         if (!rrule) return;
493         recur = icalproperty_get_rrule(rrule);
494         ritr = icalrecur_iterator_new(recur, dtstart);
495         if (!ritr) return;
496
497         while (next = icalrecur_iterator_next(ritr), ((!icaltime_is_null_time(next))&&(!stop_rr)) ) {
498                 ++num_recur;
499                 if (num_recur > 1) {            /* Skip the first one.  We already did it at the root. */
500                         icalcomponent *cptr;
501
502                         /* Note: anything we do here, we also have to do above for the root event. */
503                         Cal = (disp_cal*) malloc(sizeof(disp_cal));
504                         memset(Cal, 0, sizeof(disp_cal));
505                         Cal->cal = icalcomponent_new_clone(event);
506                         Cal->unread = unread;
507                         len = strlen(from);
508                         Cal->from = (char*)malloc(len+ 1);
509                         memcpy(Cal->from, from, len + 1);
510                         Cal->cal_msgnum = msgnum;
511
512                         if (icalcomponent_isa(Cal->cal) == ICAL_VEVENT_COMPONENT) {
513                                 cptr = Cal->cal;
514                         }
515                         else {
516                                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
517                         }
518                         if (cptr) {
519
520                                 /* Remove any existing DTSTART properties */
521                                 while ( ps = icalcomponent_get_first_property(cptr, ICAL_DTSTART_PROPERTY),
522                                         ps != NULL
523                                 ) {
524                                         icalcomponent_remove_property(cptr, ps);
525                                 }
526
527                                 /* Add our shiny new DTSTART property from the iteration */
528                                 ps = icalproperty_new_dtstart(next);
529                                 icalcomponent_add_property(cptr, ps);
530                                 Cal->event_start = icaltime_as_timet(next);
531                                 final_recurrence = Cal->event_start;
532
533                                 /* Remove any existing DTEND properties */
534                                 while (ps = icalcomponent_get_first_property(cptr, ICAL_DTEND_PROPERTY), (ps != NULL)) {
535                                         icalcomponent_remove_property(cptr, ps);
536                                 }
537
538                                 /* Add our shiny new DTEND property from the iteration */
539                                 ps = icalproperty_new_dtend(icaltime_add(next, dur));
540                                 icalcomponent_add_property(cptr, ps);
541
542                         }
543
544                         /* Dezonify and decapsulate at the very last moment */
545                         ical_dezonify(Cal->cal);
546                         if (icalcomponent_isa(Cal->cal) != ICAL_VEVENT_COMPONENT) {
547                                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
548                                 if (cptr) {
549                                         cptr = icalcomponent_new_clone(cptr);
550                                         icalcomponent_free(Cal->cal);
551                                         Cal->cal = cptr;
552                                 }
553                         }
554
555                         if (    (Cal->event_start > calv->lower_bound)
556                                 && (Cal->event_start < calv->upper_bound)
557                         ) {
558                                 /* syslog(LOG_DEBUG, "REPEATS: %s", ctime(&Cal->event_start)); */
559                                 Put(WCC->disp_cal_items, 
560                                         (char*) &Cal->event_start,
561                                         sizeof(Cal->event_start), 
562                                         Cal, 
563                                         delete_cal
564                                 );
565                         }
566                         else {
567                                 delete_cal(Cal);
568                         }
569
570                         /* If an upper bound is set, stop when we go out of scope */
571                         if (final_recurrence > calv->upper_bound) stop_rr = 1;
572                 }
573         }
574         icalrecur_iterator_free(ritr);
575         /* syslog(LOG_DEBUG, "Performed %d recurrences; final one is %s", num_recur, ctime(&final_recurrence)); */
576 }
577
578
579 void process_ical_object(long msgnum, int unread,
580                          char *from, 
581                          char *FlatIcal, 
582                          icalcomponent_kind which_kind,
583                          IcalCallbackFunc CallBack,
584                          calview *calv
585 ) {
586         icalcomponent *cal, *c;
587
588         cal = icalcomponent_new_from_string(FlatIcal);
589         if (cal != NULL) {
590
591                 /* A which_kind of (-1) means just load the whole thing */
592                 if (which_kind == (-1)) {
593                         CallBack(cal, msgnum, from, unread, calv);
594                 }
595                 
596                 /* Otherwise recurse and hunt */
597                 else {
598                         
599                         /* Simple components of desired type */
600                         if (icalcomponent_isa(cal) == which_kind) {
601                                 CallBack(cal, msgnum, from, unread, calv);
602                         }
603                         
604                         /* Subcomponents of desired type */
605                         for (c = icalcomponent_get_first_component(cal, which_kind);
606                              (c != 0);
607                              c = icalcomponent_get_next_component(cal, which_kind)) {
608                                 CallBack(c, msgnum, from, unread, calv);
609                         }
610                         
611                 }
612                 
613                 icalcomponent_free(cal);
614         }
615 }
616
617 // Code common to all icalendar display handlers.  Given a message number and a MIME
618 // type, we load the message and hunt for that MIME type.  If found, we load
619 // the relevant part, deserialize it into a libical component, filter it for
620 // the requested object type, and feed it to the specified handler.
621 void load_ical_object(long msgnum, int unread,
622                       icalcomponent_kind which_kind,
623                       IcalCallbackFunc CallBack,
624                       calview *calv,
625                       int RenderAsync
626 ) {
627         StrBuf *Buf;
628         StrBuf *Data = NULL;
629         const char *bptr;
630         int Done = 0;
631         char from[128] = "";
632         char mime_partnum[256];
633         char mime_filename[256];
634         char mime_content_type[256];
635         char mime_disposition[256];
636         char relevant_partnum[256];
637         char *relevant_source = NULL;
638         int phase = 0;                          /* 0 = citadel headers, 1 = mime headers, 2 = body */
639         char msg4_content_type[256] = "";
640         char msg4_content_encoding[256] = "";
641         int msg4_content_length = 0;
642
643         relevant_partnum[0] = '\0';
644         serv_printf("MSG4 %ld", msgnum);        /* we need the mime headers */
645         Buf = NewStrBuf();
646         StrBuf_ServGetln(Buf);
647         if (GetServerStatus(Buf, NULL) != 1) {
648                 FreeStrBuf (&Buf);
649                 return;
650         }
651         while (!Done && (StrBuf_ServGetln(Buf)>=0)) {
652                 if ( (StrLength(Buf)==3) && 
653                      !strcmp(ChrPtr(Buf), "000")) {
654                         Done = 1;
655                         break;
656                 }
657                 bptr = ChrPtr(Buf);
658                 switch (phase) {
659                 case 0:
660                         if (!strncasecmp(bptr, "part=", 5)) {
661                                 extract_token(mime_filename, &bptr[5], 1, '|', sizeof mime_filename);
662                                 extract_token(mime_partnum, &bptr[5], 2, '|', sizeof mime_partnum);
663                                 extract_token(mime_disposition, &bptr[5], 3, '|', sizeof mime_disposition);
664                                 extract_token(mime_content_type, &bptr[5], 4, '|', sizeof mime_content_type);
665                                 /* do we care? mime_length = */extract_int(&bptr[5], 5);
666
667                                 if (  (!strcasecmp(mime_content_type, "text/calendar"))
668                                       || (!strcasecmp(mime_content_type, "application/ics"))
669                                       || (!strcasecmp(mime_content_type, "text/vtodo"))
670                                       || (!strcasecmp(mime_content_type, "text/todo"))
671                                 ) {
672                                         strcpy(relevant_partnum, mime_partnum);
673                                 }
674                         }
675                         else if (!strncasecmp(bptr, "from=", 4)) {
676                                 extract_token(from, bptr, 1, '=', sizeof(from));
677                         }
678                         else if ((phase == 0) && (!strncasecmp(bptr, "text", 4))) {
679                                 phase = 1;
680                         }
681                 break;
682                 case 1:
683                         if (!IsEmptyStr(bptr)) {
684                                 if (!strncasecmp(bptr, "Content-type: ", 14)) {
685                                         safestrncpy(msg4_content_type, &bptr[14], sizeof msg4_content_type);
686                                         string_trim(msg4_content_type);
687                                 }
688                                 else if (!strncasecmp(bptr, "Content-transfer-encoding: ", 27)) {
689                                         safestrncpy(msg4_content_encoding, &bptr[27], sizeof msg4_content_encoding);
690                                         string_trim(msg4_content_type);
691                                 }
692                                 else if ((!strncasecmp(bptr, "Content-length: ", 16))) {
693                                         msg4_content_length = atoi(&bptr[16]);
694                                 }
695                                 break;
696                         }
697                         else {
698                                 phase++;
699                                 
700                                 if ((msg4_content_length > 0)
701                                     && ( !strcasecmp(msg4_content_encoding, "7bit"))
702                                     && ((!strcasecmp(mime_content_type, "text/calendar"))
703                                         || (!strcasecmp(mime_content_type, "application/ics"))
704                                         || (!strcasecmp(mime_content_type, "text/vtodo"))
705                                         || (!strcasecmp(mime_content_type, "text/todo"))
706                                             )
707                                         ) 
708                                 {
709                                 }
710                         }
711                 case 2:
712                         if (Data == NULL)
713                                 Data = NewStrBufPlain(NULL, msg4_content_length * 2);
714                         if (msg4_content_length > 0) {
715                                 StrBuf_ServGetBLOBBuffered(Data, msg4_content_length);
716                                 phase ++;
717                         }
718                         else {
719                                 StrBufAppendBuf(Data, Buf, 0);
720                                 StrBufAppendBufPlain(Data, "\r\n", 1, 0);
721                         }
722                 case 3:
723                         StrBufAppendBuf(Data, Buf, 0);
724                 }
725         }
726         FreeStrBuf(&Buf);
727
728         // If MSG4 didn't give us the part we wanted, but we know that we can find it
729         // as one of the other MIME parts, attempt to load it now.
730         if ((Data == NULL) && (!IsEmptyStr(relevant_partnum))) {
731                 Data = load_mimepart(msgnum, relevant_partnum);
732         }
733
734         if (Data != NULL) {
735                 relevant_source = (char*) ChrPtr(Data);
736                 process_ical_object(msgnum, unread,
737                                     from, 
738                                     relevant_source, 
739                                     which_kind,
740                                     CallBack,
741                                     calv);
742         }
743         FreeStrBuf (&Data);
744
745         icalmemory_free_ring();
746 }
747
748
749 // Display a calendar item
750 int calendar_LoadMsgFromServer(SharedMessageStatus *Stat, void **ViewSpecific, message_summary* Msg, int is_new, int i) {
751         calview *c = (calview*) *ViewSpecific;
752         load_ical_object(Msg->msgnum, is_new, (-1), display_individual_cal, c, 1);
753         return 0;
754 }
755
756
757 // display the editor component for an event
758 void display_edit_event(void) {
759         long msgnum = 0L;
760
761         msgnum = lbstr("msgnum");
762         if (msgnum > 0L) {
763                 // existing event
764                 load_ical_object(msgnum, 0, ICAL_VEVENT_COMPONENT, display_edit_individual_event, NULL, 0);
765         }
766         else {
767                 // new event
768                 display_edit_individual_event(NULL, 0L, "", 0, NULL);
769         }
770 }
771
772
773 // save an edited event
774 void save_event(void) {
775         long msgnum = 0L;
776
777         msgnum = lbstr("msgnum");
778
779         if (msgnum > 0L) {
780                 load_ical_object(msgnum, 0, (-1), save_individual_event, NULL, 0);
781         }
782         else {
783                 save_individual_event(NULL, 0L, "", 0, NULL);
784         }
785 }
786
787
788 // Anonymous request of freebusy data for a user
789 void do_freebusy(void) {
790         const char *req = ChrPtr(WC->Hdr->HR.ReqLine);
791         char who[SIZ];
792         char buf[SIZ];
793         int len;
794         long lines;
795
796         extract_token(who, req, 0, ' ', sizeof who);
797         if (!strncasecmp(who, "/freebusy/", 10)) {
798                 strcpy(who, &who[10]);
799         }
800         unescape_input(who);
801
802         len = strlen(who);
803         if ( (!strcasecmp(&who[len-4], ".vcf"))
804              || (!strcasecmp(&who[len-4], ".ifb"))
805              || (!strcasecmp(&who[len-4], ".vfb")) ) {
806                 who[len-4] = 0;
807         }
808
809         syslog(LOG_INFO, "freebusy requested for <%s>\n", who);
810         serv_printf("ICAL freebusy|%s", who);
811         serv_getln(buf, sizeof buf);
812
813         if (buf[0] != '1') {
814                 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
815                 output_headers(0, 0, 0, 0, 0, 0);
816                 hprintf("Content-Type: text/plain\r\n");
817                 wc_printf("%s\n", &buf[4]);
818                 end_burst();
819                 return;
820         }
821
822         read_server_text(WC->WBuf, &lines);
823         http_transmit_thing("text/calendar", 0);
824 }
825
826
827 int calendar_Cleanup(void **ViewSpecific) {
828         calview *c;
829         
830         c = (calview *) *ViewSpecific;
831
832         wDumpContent(1);
833         free (c);
834         *ViewSpecific = NULL;
835
836         return 0;
837 }
838
839
840 int __calendar_Cleanup(void **ViewSpecific) {
841         calview *c;
842         
843         c = (calview *) *ViewSpecific;
844
845         free (c);
846         *ViewSpecific = NULL;
847
848         return 0;
849 }
850
851
852 void 
853 InitModule_CALENDAR
854 (void)
855 {
856         RegisterReadLoopHandlerset(
857                 VIEW_CALENDAR,
858                 calendar_GetParamsGetServerCall,
859                 NULL,
860                 NULL,
861                 NULL,
862                 calendar_LoadMsgFromServer,
863                 calendar_RenderView_or_Tail,
864                 calendar_Cleanup,
865                 NULL);
866
867         RegisterReadLoopHandlerset(
868                 VIEW_CALBRIEF,
869                 calendar_GetParamsGetServerCall,
870                 NULL,
871                 NULL,
872                 NULL,
873                 calendar_LoadMsgFromServer,
874                 calendar_RenderView_or_Tail,
875                 calendar_Cleanup,
876                 NULL);
877
878
879
880         RegisterPreference("daystart", _("Calendar day view begins at:"), PRF_INT, NULL);
881         RegisterPreference("dayend", _("Calendar day view ends at:"), PRF_INT, NULL);
882         RegisterPreference("weekstart", _("Week starts on:"), PRF_INT, NULL);
883
884         WebcitAddUrlHandler(HKEY("freebusy"), "", 0, do_freebusy, COOKIEUNNEEDED|ANONYMOUS|FORCE_SESSIONCLOSE);
885         WebcitAddUrlHandler(HKEY("display_edit_task"), "", 0, display_edit_task, 0);
886         WebcitAddUrlHandler(HKEY("display_edit_event"), "", 0, display_edit_event, 0);
887         WebcitAddUrlHandler(HKEY("save_event"), "", 0, save_event, 0);
888         WebcitAddUrlHandler(HKEY("respond_to_request"), "", 0, respond_to_request, 0);
889         WebcitAddUrlHandler(HKEY("handle_rsvp"), "", 0, handle_rsvp, 0);
890 }