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