Completed time range search of recurring events.
[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
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), ps != NULL) {
522                                         icalcomponent_remove_property(cptr, ps);
523                                 }
524
525                                 /* Add our shiny new DTSTART property from the iteration */
526                                 ps = icalproperty_new_dtstart(next);
527                                 icalcomponent_add_property(cptr, ps);
528                                 Cal->event_start = icaltime_as_timet(next);
529                                 final_recurrence = Cal->event_start;
530
531                                 /* Remove any existing DTEND properties */
532                                 while (ps = icalcomponent_get_first_property(cptr, ICAL_DTEND_PROPERTY), (ps != NULL)) {
533                                         icalcomponent_remove_property(cptr, ps);
534                                 }
535
536                                 /* Add our shiny new DTEND property from the iteration */
537                                 ps = icalproperty_new_dtend(icaltime_add(next, dur));
538                                 icalcomponent_add_property(cptr, ps);
539
540                         }
541
542                         /* Dezonify and decapsulate at the very last moment */
543                         ical_dezonify(Cal->cal);
544                         if (icalcomponent_isa(Cal->cal) != ICAL_VEVENT_COMPONENT) {
545                                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
546                                 if (cptr) {
547                                         cptr = icalcomponent_new_clone(cptr);
548                                         icalcomponent_free(Cal->cal);
549                                         Cal->cal = cptr;
550                                 }
551                         }
552
553                         if (    (Cal->event_start > calv->lower_bound)
554                                 && (Cal->event_start < calv->upper_bound)
555                         ) {
556                                 /* syslog(LOG_DEBUG, "REPEATS: %s", ctime(&Cal->event_start)); */
557                                 Put(WCC->disp_cal_items, 
558                                         (char*) &Cal->event_start,
559                                         sizeof(Cal->event_start), 
560                                         Cal, 
561                                         delete_cal
562                                 );
563                         }
564                         else {
565                                 delete_cal(Cal);
566                         }
567
568                         /* If an upper bound is set, stop when we go out of scope */
569                         if (final_recurrence > calv->upper_bound) stop_rr = 1;
570                 }
571         }
572         icalrecur_iterator_free(ritr);
573         /* syslog(LOG_DEBUG, "Performed %d recurrences; final one is %s", num_recur, ctime(&final_recurrence)); */
574 }
575
576
577 void process_ical_object(long msgnum, int unread,
578                          char *from, 
579                          char *FlatIcal, 
580                          icalcomponent_kind which_kind,
581                          IcalCallbackFunc CallBack,
582                          calview *calv
583 ) {
584         icalcomponent *cal, *c;
585
586         cal = icalcomponent_new_from_string(FlatIcal);
587         if (cal != NULL) {
588
589                 /* A which_kind of (-1) means just load the whole thing */
590                 if (which_kind == (-1)) {
591                         CallBack(cal, msgnum, from, unread, calv);
592                 }
593                 
594                 /* Otherwise recurse and hunt */
595                 else {
596                         
597                         /* Simple components of desired type */
598                         if (icalcomponent_isa(cal) == which_kind) {
599                                 CallBack(cal, msgnum, from, unread, calv);
600                         }
601                         
602                         /* Subcomponents of desired type */
603                         for (c = icalcomponent_get_first_component(cal, which_kind);
604                              (c != 0);
605                              c = icalcomponent_get_next_component(cal, which_kind)) {
606                                 CallBack(c, msgnum, from, unread, calv);
607                         }
608                         
609                 }
610                 
611                 icalcomponent_free(cal);
612         }
613 }
614
615 // Code common to all icalendar display handlers.  Given a message number and a MIME
616 // type, we load the message and hunt for that MIME type.  If found, we load
617 // the relevant part, deserialize it into a libical component, filter it for
618 // the requested object type, and feed it to the specified handler.
619 void load_ical_object(long msgnum, int unread,
620                       icalcomponent_kind which_kind,
621                       IcalCallbackFunc CallBack,
622                       calview *calv,
623                       int RenderAsync
624 ) {
625         StrBuf *Buf;
626         StrBuf *Data = NULL;
627         const char *bptr;
628         int Done = 0;
629         char from[128] = "";
630         char mime_partnum[256];
631         char mime_filename[256];
632         char mime_content_type[256];
633         char mime_disposition[256];
634         char relevant_partnum[256];
635         char *relevant_source = NULL;
636         int phase = 0;                          /* 0 = citadel headers, 1 = mime headers, 2 = body */
637         char msg4_content_type[256] = "";
638         char msg4_content_encoding[256] = "";
639         int msg4_content_length = 0;
640
641         relevant_partnum[0] = '\0';
642         serv_printf("MSG4 %ld", msgnum);        /* we need the mime headers */
643         Buf = NewStrBuf();
644         StrBuf_ServGetln(Buf);
645         if (GetServerStatus(Buf, NULL) != 1) {
646                 FreeStrBuf (&Buf);
647                 return;
648         }
649         while (!Done && (StrBuf_ServGetln(Buf)>=0)) {
650                 if ( (StrLength(Buf)==3) && 
651                      !strcmp(ChrPtr(Buf), "000")) {
652                         Done = 1;
653                         break;
654                 }
655                 bptr = ChrPtr(Buf);
656                 switch (phase) {
657                 case 0:
658                         if (!strncasecmp(bptr, "part=", 5)) {
659                                 extract_token(mime_filename, &bptr[5], 1, '|', sizeof mime_filename);
660                                 extract_token(mime_partnum, &bptr[5], 2, '|', sizeof mime_partnum);
661                                 extract_token(mime_disposition, &bptr[5], 3, '|', sizeof mime_disposition);
662                                 extract_token(mime_content_type, &bptr[5], 4, '|', sizeof mime_content_type);
663                                 /* do we care? mime_length = */extract_int(&bptr[5], 5);
664
665                                 if (  (!strcasecmp(mime_content_type, "text/calendar"))
666                                       || (!strcasecmp(mime_content_type, "application/ics"))
667                                       || (!strcasecmp(mime_content_type, "text/vtodo"))
668                                       || (!strcasecmp(mime_content_type, "text/todo"))
669                                 ) {
670                                         strcpy(relevant_partnum, mime_partnum);
671                                 }
672                         }
673                         else if (!strncasecmp(bptr, "from=", 4)) {
674                                 extract_token(from, bptr, 1, '=', sizeof(from));
675                         }
676                         else if ((phase == 0) && (!strncasecmp(bptr, "text", 4))) {
677                                 phase = 1;
678                         }
679                 break;
680                 case 1:
681                         if (!IsEmptyStr(bptr)) {
682                                 if (!strncasecmp(bptr, "Content-type: ", 14)) {
683                                         safestrncpy(msg4_content_type, &bptr[14], sizeof msg4_content_type);
684                                         string_trim(msg4_content_type);
685                                 }
686                                 else if (!strncasecmp(bptr, "Content-transfer-encoding: ", 27)) {
687                                         safestrncpy(msg4_content_encoding, &bptr[27], sizeof msg4_content_encoding);
688                                         string_trim(msg4_content_type);
689                                 }
690                                 else if ((!strncasecmp(bptr, "Content-length: ", 16))) {
691                                         msg4_content_length = atoi(&bptr[16]);
692                                 }
693                                 break;
694                         }
695                         else {
696                                 phase++;
697                                 
698                                 if ((msg4_content_length > 0)
699                                     && ( !strcasecmp(msg4_content_encoding, "7bit"))
700                                     && ((!strcasecmp(mime_content_type, "text/calendar"))
701                                         || (!strcasecmp(mime_content_type, "application/ics"))
702                                         || (!strcasecmp(mime_content_type, "text/vtodo"))
703                                         || (!strcasecmp(mime_content_type, "text/todo"))
704                                             )
705                                         ) 
706                                 {
707                                 }
708                         }
709                 case 2:
710                         if (Data == NULL)
711                                 Data = NewStrBufPlain(NULL, msg4_content_length * 2);
712                         if (msg4_content_length > 0) {
713                                 StrBuf_ServGetBLOBBuffered(Data, msg4_content_length);
714                                 phase ++;
715                         }
716                         else {
717                                 StrBufAppendBuf(Data, Buf, 0);
718                                 StrBufAppendBufPlain(Data, "\r\n", 1, 0);
719                         }
720                 case 3:
721                         StrBufAppendBuf(Data, Buf, 0);
722                 }
723         }
724         FreeStrBuf(&Buf);
725
726         // If MSG4 didn't give us the part we wanted, but we know that we can find it
727         // as one of the other MIME parts, attempt to load it now.
728         if ((Data == NULL) && (!IsEmptyStr(relevant_partnum))) {
729                 Data = load_mimepart(msgnum, relevant_partnum);
730         }
731
732         if (Data != NULL) {
733                 relevant_source = (char*) ChrPtr(Data);
734                 process_ical_object(msgnum, unread,
735                                     from, 
736                                     relevant_source, 
737                                     which_kind,
738                                     CallBack,
739                                     calv);
740         }
741         FreeStrBuf (&Data);
742
743         icalmemory_free_ring();
744 }
745
746
747 // Display a calendar item
748 int calendar_LoadMsgFromServer(SharedMessageStatus *Stat, void **ViewSpecific, message_summary* Msg, int is_new, int i) {
749         calview *c = (calview*) *ViewSpecific;
750         load_ical_object(Msg->msgnum, is_new, (-1), display_individual_cal, c, 1);
751         return 0;
752 }
753
754
755 // display the editor component for an event
756 void display_edit_event(void) {
757         long msgnum = 0L;
758
759         msgnum = lbstr("msgnum");
760         if (msgnum > 0L) {
761                 // existing event
762                 load_ical_object(msgnum, 0, ICAL_VEVENT_COMPONENT, display_edit_individual_event, NULL, 0);
763         }
764         else {
765                 // new event
766                 display_edit_individual_event(NULL, 0L, "", 0, NULL);
767         }
768 }
769
770
771 // save an edited event
772 void save_event(void) {
773         long msgnum = 0L;
774
775         msgnum = lbstr("msgnum");
776
777         if (msgnum > 0L) {
778                 load_ical_object(msgnum, 0, (-1), save_individual_event, NULL, 0);
779         }
780         else {
781                 save_individual_event(NULL, 0L, "", 0, NULL);
782         }
783 }
784
785
786 // Anonymous request of freebusy data for a user
787 void do_freebusy(void) {
788         const char *req = ChrPtr(WC->Hdr->HR.ReqLine);
789         char who[SIZ];
790         char buf[SIZ];
791         int len;
792         long lines;
793
794         extract_token(who, req, 0, ' ', sizeof who);
795         if (!strncasecmp(who, "/freebusy/", 10)) {
796                 strcpy(who, &who[10]);
797         }
798         unescape_input(who);
799
800         len = strlen(who);
801         if ( (!strcasecmp(&who[len-4], ".vcf"))
802              || (!strcasecmp(&who[len-4], ".ifb"))
803              || (!strcasecmp(&who[len-4], ".vfb")) ) {
804                 who[len-4] = 0;
805         }
806
807         syslog(LOG_INFO, "freebusy requested for <%s>\n", who);
808         serv_printf("ICAL freebusy|%s", who);
809         serv_getln(buf, sizeof buf);
810
811         if (buf[0] != '1') {
812                 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
813                 output_headers(0, 0, 0, 0, 0, 0);
814                 hprintf("Content-Type: text/plain\r\n");
815                 wc_printf("%s\n", &buf[4]);
816                 end_burst();
817                 return;
818         }
819
820         read_server_text(WC->WBuf, &lines);
821         http_transmit_thing("text/calendar", 0);
822 }
823
824
825 int calendar_Cleanup(void **ViewSpecific) {
826         calview *c;
827         
828         c = (calview *) *ViewSpecific;
829
830         wDumpContent(1);
831         free (c);
832         *ViewSpecific = NULL;
833
834         return 0;
835 }
836
837
838 int __calendar_Cleanup(void **ViewSpecific) {
839         calview *c;
840         
841         c = (calview *) *ViewSpecific;
842
843         free (c);
844         *ViewSpecific = NULL;
845
846         return 0;
847 }
848
849
850 void 
851 InitModule_CALENDAR
852 (void)
853 {
854         RegisterReadLoopHandlerset(
855                 VIEW_CALENDAR,
856                 calendar_GetParamsGetServerCall,
857                 NULL,
858                 NULL,
859                 NULL,
860                 calendar_LoadMsgFromServer,
861                 calendar_RenderView_or_Tail,
862                 calendar_Cleanup,
863                 NULL);
864
865         RegisterReadLoopHandlerset(
866                 VIEW_CALBRIEF,
867                 calendar_GetParamsGetServerCall,
868                 NULL,
869                 NULL,
870                 NULL,
871                 calendar_LoadMsgFromServer,
872                 calendar_RenderView_or_Tail,
873                 calendar_Cleanup,
874                 NULL);
875
876
877
878         RegisterPreference("daystart", _("Calendar day view begins at:"), PRF_INT, NULL);
879         RegisterPreference("dayend", _("Calendar day view ends at:"), PRF_INT, NULL);
880         RegisterPreference("weekstart", _("Week starts on:"), PRF_INT, NULL);
881
882         WebcitAddUrlHandler(HKEY("freebusy"), "", 0, do_freebusy, COOKIEUNNEEDED|ANONYMOUS|FORCE_SESSIONCLOSE);
883         WebcitAddUrlHandler(HKEY("display_edit_task"), "", 0, display_edit_task, 0);
884         WebcitAddUrlHandler(HKEY("display_edit_event"), "", 0, display_edit_event, 0);
885         WebcitAddUrlHandler(HKEY("save_event"), "", 0, save_event, 0);
886         WebcitAddUrlHandler(HKEY("respond_to_request"), "", 0, respond_to_request, 0);
887         WebcitAddUrlHandler(HKEY("handle_rsvp"), "", 0, handle_rsvp, 0);
888 }