* When displaying calendar attachments embedded inside an email message, call ical_de...
[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
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                 the_method = icalproperty_get_method(method);
60                 char *title;
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, tt, 0);
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, tt, 0);
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 the component has attendees, iterate through them. */
157         for (p = icalcomponent_get_first_property(cal, ICAL_ATTENDEE_PROPERTY); 
158              (p != NULL); 
159              p = icalcomponent_get_next_property(cal, ICAL_ATTENDEE_PROPERTY)) {
160                 StrBufAppendPrintf(Target, "<dt>");
161                 StrBufAppendPrintf(Target, _("Attendee:"));
162                 StrBufAppendPrintf(Target, "</dt><dd>");
163                 safestrncpy(buf, icalproperty_get_attendee(p), sizeof buf);
164                 if (!strncasecmp(buf, "MAILTO:", 7)) {
165
166                         /** screen name or email address */
167                         strcpy(buf, &buf[7]);
168                         striplt(buf);
169                         StrEscAppend(Target, NULL, buf, 0, 0);
170                         StrBufAppendPrintf(Target, " ");
171
172                         /** participant status */
173                         partstat_as_string(buf, p);
174                         StrEscAppend(Target, NULL, buf, 0, 0);
175                 }
176                 StrBufAppendPrintf(Target, "</dd>\n");
177         }
178
179         /* If the component has subcomponents, recurse through them. */
180         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
181              (c != 0);
182              c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
183                 /* Recursively process subcomponent */
184                 cal_process_object(Target, c, recursion_level+1, msgnum, cal_partnum);
185         }
186
187         /* If this is a REQUEST, display conflicts and buttons */
188         if (the_method == ICAL_METHOD_REQUEST) {
189
190                 /* Check for conflicts */
191                 lprintf(9, "Checking server calendar for conflicts...\n");
192                 serv_printf("ICAL conflicts|%ld|%s|", msgnum, cal_partnum);
193                 serv_getln(buf, sizeof buf);
194                 if (buf[0] == '1') {
195                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
196                                 extract_token(conflict_name, buf, 3, '|', sizeof conflict_name);
197                                 is_update = extract_int(buf, 4);
198
199                                 if (is_update) {
200                                         snprintf(conflict_message, sizeof conflict_message,
201                                                  _("This is an update of '%s' which is already in your calendar."), conflict_name);
202                                 }
203                                 else {
204                                         snprintf(conflict_message, sizeof conflict_message,
205                                                  _("This event would conflict with '%s' which is already in your calendar."), conflict_name);
206                                 }
207
208                                 StrBufAppendPrintf(Target, "<dt>%s",
209                                         (is_update ?
210                                          _("Update:") :
211                                          _("CONFLICT:")
212                                                 )
213                                         );
214                                 StrBufAppendPrintf(Target, "</dt><dd>");
215                                 StrEscAppend(Target, NULL, conflict_message, 0, 0);
216                                 StrBufAppendPrintf(Target, "</dd>\n");
217                         }
218                 }
219                 lprintf(9, "...done.\n");
220
221                 StrBufAppendPrintf(Target, "</dl>");
222
223                 /* Display the Accept/Decline buttons */
224                 StrBufAppendPrintf(Target, "<p id=\"%s_question\">"
225                         "%s "
226                         "&nbsp;&nbsp;&nbsp;<span class=\"button_link\"> "
227                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Accept');\">%s</a>"
228                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
229                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Tentative');\">%s</a>"
230                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
231                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Decline');\">%s</a>"
232                         "</span></p>\n",
233                         divname,
234                         _("How would you like to respond to this invitation?"),
235                         divname, divname, msgnum, cal_partnum, _("Accept"),
236                         divname, divname, msgnum, cal_partnum, _("Tentative"),
237                         divname, divname, msgnum, cal_partnum, _("Decline")
238                         );
239
240         }
241
242         /* If this is a REPLY, display update button */
243         if (the_method == ICAL_METHOD_REPLY) {
244
245                 /* In the future, if we want to validate this object before
246                  * continuing, we can do it this way:
247                  serv_printf("ICAL whatever|%ld|%s|", msgnum, cal_partnum);
248                  serv_getln(buf, sizeof buf);
249                  }
250                 ***********/
251
252                 /* Display the update buttons */
253                 StrBufAppendPrintf(Target, "<p id=\"%s_question\" >"
254                         "%s "
255                         "&nbsp;&nbsp;&nbsp;<span class=\"button_link\"> "
256                         "<a href=\"javascript:HandleRSVP('%s_question','%s_title','%ld','%s','Update');\">%s</a>"
257                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
258                         "<a href=\"javascript:HandleRSVP('%s_question','%s_title','%ld','%s','Ignore');\">%s</a>"
259                         "</span></p>\n",
260                         divname,
261                         _("Click <i>Update</i> to accept this reply and update your calendar."),
262                         divname, divname, msgnum, cal_partnum, _("Update"),
263                         divname, divname, msgnum, cal_partnum, _("Ignore")
264                         );
265         
266         }
267         
268         /* Trailing HTML for the display of this object */
269         if (recursion_level == 0) {
270                 StrBufAppendPrintf(Target, "<p>&nbsp;</p></div>\n");
271         }
272 }
273
274
275 /*
276  * Deserialize a calendar object in a message so it can be displayed.
277  *
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  * \brief accept/decline meeting
302  * Respond to a meeting request
303  */
304 void respond_to_request(void) 
305 {
306         char buf[1024];
307
308         begin_ajax_response();
309
310         serv_printf("ICAL respond|%s|%s|%s|",
311                 bstr("msgnum"),
312                 bstr("cal_partnum"),
313                 bstr("sc")
314         );
315         serv_getln(buf, sizeof buf);
316
317         if (buf[0] == '2') {
318                 wprintf("<img src=\"static/calarea_48x.gif\"><span>");
319                 if (!strcasecmp(bstr("sc"), "accept")) {
320                         wprintf(_("You have accepted this meeting invitation.  "
321                                 "It has been entered into your calendar.")
322                         );
323                 } else if (!strcasecmp(bstr("sc"), "tentative")) {
324                         wprintf(_("You have tentatively accepted this meeting invitation.  "
325                                 "It has been 'pencilled in' to your calendar.")
326                         );
327                 } else if (!strcasecmp(bstr("sc"), "decline")) {
328                         wprintf(_("You have declined this meeting invitation.  "
329                                   "It has <b>not</b> been entered into your calendar.")
330                                 );
331                 }
332                 wprintf(" ");
333                 wprintf(_("A reply has been sent to the meeting organizer."));
334                 wprintf("</span>");
335         } else {
336                 wprintf("<img align=\"center\" src=\"static/error.gif\"><span>");
337                 wprintf("%s\n", &buf[4]);
338                 wprintf("</span>");
339         }
340
341         end_ajax_response();
342 }
343
344
345
346 /**
347  * \brief Handle an incoming RSVP
348  */
349 void handle_rsvp(void) 
350 {
351         char buf[1024];
352
353         begin_ajax_response();
354
355         serv_printf("ICAL handle_rsvp|%s|%s|%s|",
356                 bstr("msgnum"),
357                 bstr("cal_partnum"),
358                 bstr("sc")
359         );
360         serv_getln(buf, sizeof buf);
361
362         if (buf[0] == '2') {
363                 wprintf("<img src=\"static/calarea_48x.gif\"><span>");
364                 if (!strcasecmp(bstr("sc"), "update")) {
365                         wprintf(_("Your calendar has been updated to reflect this RSVP."));
366                 } else if (!strcasecmp(bstr("sc"), "ignore")) {
367                         wprintf(_("You have chosen to ignore this RSVP. "
368                                   "Your calendar has <b>not</b> been updated.")
369                                 );
370                 }
371                 wprintf("</span>");
372         } else {
373                 wprintf("<img src=\"static/error.gif\"><span> %s\n", &buf[4]);
374                 wprintf("</span>");
375         }
376
377         end_ajax_response();
378 }
379
380
381
382
383 /*
384  * free memory allocated using libical
385  */
386 void delete_cal(void *vCal)
387 {
388         disp_cal *Cal = (disp_cal*) vCal;
389         icalcomponent_free(Cal->cal);
390         free(Cal->from);
391         free(Cal);
392 }
393
394 /*
395  * This is the meat-and-bones of the first part of our two-phase calendar display.
396  * As we encounter calendar items in messages being read from the server, we break out
397  * any iCalendar objects and store them in a hash table.  Later on, the second phase will
398  * use this hash table to render the calendar for display.
399  */
400 void display_individual_cal(icalcomponent *cal, long msgnum, char *from, int unread, struct calview *calv)
401 {
402         icalproperty *ps = NULL;
403         struct icaltimetype dtstart, dtend;
404         struct icaldurationtype dur;
405         wcsession *WCC = WC;
406         disp_cal *Cal;
407         size_t len;
408         time_t final_recurrence = 0;
409         icalcomponent *cptr = NULL;
410
411         /* recur variables */
412         icalproperty *rrule = NULL;
413         struct icalrecurrencetype recur;
414         icalrecur_iterator *ritr = NULL;
415         struct icaltimetype next;
416         int num_recur = 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         int stop_rr = 0;
502         while (next = icalrecur_iterator_next(ritr), ((!icaltime_is_null_time(next))&&(!stop_rr)) ) {
503                 ++num_recur;
504                 if (num_recur > 1) {            /* Skip the first one.  We already did it at the root. */
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                         icalcomponent *cptr;
518                         if (icalcomponent_isa(Cal->cal) == ICAL_VEVENT_COMPONENT) {
519                                 cptr = Cal->cal;
520                         }
521                         else {
522                                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
523                         }
524                         if (cptr) {
525                                 ps = icalcomponent_get_first_property(cptr, ICAL_DTSTART_PROPERTY);
526                                 if (ps != NULL) {
527                                         icalcomponent_remove_property(cptr, ps);
528                                         ps = icalproperty_new_dtstart(next);
529                                         icalcomponent_add_property(cptr, ps);
530         
531                                         Cal->event_start = icaltime_as_timet(next);
532                                         final_recurrence = Cal->event_start;
533                                 }
534
535                                 ps = icalcomponent_get_first_property(cptr, ICAL_DTEND_PROPERTY);
536                                 if (ps != NULL) {
537                                         icalcomponent_remove_property(cptr, ps);
538         
539                                         /* Make a new dtend */
540                                         ps = icalproperty_new_dtend(icaltime_add(next, dur));
541                 
542                                         /* and stick it somewhere */
543                                         icalcomponent_add_property(cptr, ps);
544                                 }
545
546                         }
547
548                         /* Dezonify and decapsulate at the very last moment */
549                         ical_dezonify(Cal->cal);
550                         if (icalcomponent_isa(Cal->cal) != ICAL_VEVENT_COMPONENT) {
551                                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
552                                 if (cptr) {
553                                         cptr = icalcomponent_new_clone(cptr);
554                                         icalcomponent_free(Cal->cal);
555                                         Cal->cal = cptr;
556                                 }
557                         }
558
559                         if ( (Cal->event_start > calv->lower_bound)
560                            && (Cal->event_start < calv->upper_bound) ) {
561                                 Put(WCC->disp_cal_items, 
562                                         (char*) &Cal->event_start,
563                                         sizeof(Cal->event_start), 
564                                         Cal, 
565                                         delete_cal
566                                 );
567                         }
568                         else {
569                                 delete_cal(Cal);
570                         }
571
572                         /* If an upper bound is set, stop when we go out of scope */
573                         if (final_recurrence > calv->upper_bound) stop_rr = 1;
574                 }
575         }
576         icalrecur_iterator_free(ritr);
577         /* lprintf(9, "Performed %d recurrences; final one is %s", num_recur, ctime(&final_recurrence)); */
578
579 }
580
581
582
583 /*
584  * Display a task by itself (for editing)
585  */
586 void display_edit_individual_task(icalcomponent *supplied_vtodo, long msgnum, char *from,
587                         int unread, struct calview *calv)
588 {
589         icalcomponent *vtodo;
590         icalproperty *p;
591         struct icaltimetype IcalTime;
592         time_t now;
593         int created_new_vtodo = 0;
594         icalproperty_status todoStatus;
595
596         now = time(NULL);
597
598         if (supplied_vtodo != NULL) {
599                 vtodo = supplied_vtodo;
600
601                 /**
602                  * If we're looking at a fully encapsulated VCALENDAR
603                  * rather than a VTODO component, attempt to use the first
604                  * relevant VTODO subcomponent.  If there is none, the
605                  * NULL returned by icalcomponent_get_first_component() will
606                  * tell the next iteration of this function to create a
607                  * new one.
608                  */
609                 if (icalcomponent_isa(vtodo) == ICAL_VCALENDAR_COMPONENT) {
610                         display_edit_individual_task(
611                                 icalcomponent_get_first_component(
612                                         vtodo, ICAL_VTODO_COMPONENT
613                                         ), 
614                                 msgnum, from, unread, calv
615                                 );
616                         return;
617                 }
618         }
619         else {
620                 vtodo = icalcomponent_new(ICAL_VTODO_COMPONENT);
621                 created_new_vtodo = 1;
622         }
623         
624         // TODO: Can we take all this and move it into a template?      
625         output_headers(1, 1, 1, 0, 0, 0);
626         wprintf("<!-- start task edit form -->");
627         p = icalcomponent_get_first_property(vtodo, ICAL_SUMMARY_PROPERTY);
628         // Get summary early for title
629         wprintf("<div class=\"box\">\n");
630         wprintf("<div class=\"boxlabel\">");
631         wprintf(_("Edit task"));
632         wprintf("- ");
633         if (p != NULL) {
634                 escputs((char *)icalproperty_get_comment(p));
635         }
636         wprintf("</div>");
637         
638         wprintf("<div class=\"boxcontent\">\n");
639         wprintf("<FORM METHOD=\"POST\" action=\"save_task\">\n");
640         wprintf("<div style=\"display: none;\">\n       ");
641         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
642         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgnum\" VALUE=\"%ld\">\n",
643                 msgnum);
644         wprintf("</div>");
645         wprintf("<table class=\"calendar_background\"><tr><td>");
646         wprintf("<TABLE STYLE=\"border: none;\">\n");
647
648         wprintf("<TR><TD>");
649         wprintf(_("Summary:"));
650         wprintf("</TD><TD>"
651                 "<INPUT TYPE=\"text\" NAME=\"summary\" "
652                 "MAXLENGTH=\"64\" SIZE=\"64\" VALUE=\"");
653         p = icalcomponent_get_first_property(vtodo, ICAL_SUMMARY_PROPERTY);
654         if (p != NULL) {
655                 escputs((char *)icalproperty_get_comment(p));
656         }
657         wprintf("\"></TD></TR>\n");
658
659         wprintf("<TR><TD>");
660         wprintf(_("Start date:"));
661         wprintf("</TD><TD>");
662         p = icalcomponent_get_first_property(vtodo, ICAL_DTSTART_PROPERTY);
663         wprintf("<INPUT TYPE=\"CHECKBOX\" NAME=\"nodtstart\" ID=\"nodtstart\" VALUE=\"NODTSTART\" ");
664         if (p == NULL) {
665                 wprintf("CHECKED=\"CHECKED\"");
666         }
667         wprintf(">");
668         wprintf(_("No date"));
669         
670         wprintf(" ");
671         wprintf(_("or"));
672         wprintf(" ");
673         if (p != NULL) {
674                 IcalTime = icalproperty_get_dtstart(p);
675         }
676         else
677                 IcalTime = icaltime_current_time_with_zone(get_default_icaltimezone());
678         display_icaltimetype_as_webform(&IcalTime, "dtstart", 0);
679         wprintf("</TD></TR>\n");
680
681         wprintf("<TR><TD>");
682         wprintf(_("Due date:"));
683         wprintf("</TD><TD>");
684         p = icalcomponent_get_first_property(vtodo, ICAL_DUE_PROPERTY);
685         wprintf("<INPUT TYPE=\"CHECKBOX\" NAME=\"nodue\" ID=\"nodue\" VALUE=\"NODUE\"");
686         if (p == NULL) {
687                 wprintf("CHECKED=\"CHECKED\"");
688         }
689         wprintf(">");
690         wprintf(_("No date"));
691         wprintf(" ");
692         wprintf(_("or"));
693         wprintf(" ");
694         if (p != NULL) {
695                 IcalTime = icalproperty_get_due(p);
696         }
697         else
698                 IcalTime = icaltime_current_time_with_zone(get_default_icaltimezone());
699         display_icaltimetype_as_webform(&IcalTime, "due", 0);
700                 
701         wprintf("</TD></TR>\n");
702         todoStatus = icalcomponent_get_status(vtodo);
703         wprintf("<TR><TD>\n");
704         wprintf(_("Completed:"));
705         wprintf("</TD><TD>");
706         wprintf("<INPUT TYPE=\"CHECKBOX\" NAME=\"status\" VALUE=\"COMPLETED\"");
707         if (todoStatus == ICAL_STATUS_COMPLETED) {
708                 wprintf(" CHECKED=\"CHECKED\"");
709         } 
710         wprintf(" >");
711         wprintf("</TD></TR>");
712         // start category field
713         p = icalcomponent_get_first_property(vtodo, ICAL_CATEGORIES_PROPERTY);
714         wprintf("<TR><TD>");
715         wprintf(_("Category:"));
716         wprintf("</TD><TD>");
717         wprintf("<INPUT TYPE=\"text\" NAME=\"category\" MAXLENGTH=\"32\" SIZE=\"32\" VALUE=\"");
718         if (p != NULL) {
719                 escputs((char *)icalproperty_get_categories(p));
720         }
721         wprintf("\">");
722         wprintf("</TD></TR>\n   ");
723         // end category field
724         wprintf("<TR><TD>");
725         wprintf(_("Description:"));
726         wprintf("</TD><TD>");
727         wprintf("<TEXTAREA NAME=\"description\" "
728                 "ROWS=\"10\" COLS=\"80\">\n"
729                 );
730         p = icalcomponent_get_first_property(vtodo, ICAL_DESCRIPTION_PROPERTY);
731         if (p != NULL) {
732                 escputs((char *)icalproperty_get_comment(p));
733         }
734         wprintf("</TEXTAREA></TD></TR></TABLE>\n");
735
736         wprintf("<SPAN STYLE=\"text-align: center;\">"
737                 "<INPUT TYPE=\"submit\" NAME=\"save_button\" VALUE=\"%s\">"
738                 "&nbsp;&nbsp;"
739                 "<INPUT TYPE=\"submit\" NAME=\"delete_button\" VALUE=\"%s\">\n"
740                 "&nbsp;&nbsp;"
741                 "<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">\n"
742                 "</SPAN>\n",
743                 _("Save"),
744                 _("Delete"),
745                 _("Cancel")
746                 );
747         wprintf("</td></tr></table>");
748         wprintf("</FORM>\n");
749         wprintf("</div></div></div>\n");
750         wprintf("<!-- end task edit form -->");
751         wDumpContent(1);
752
753         if (created_new_vtodo) {
754                 icalcomponent_free(vtodo);
755         }
756 }
757
758 /*
759  * \brief Save an edited task
760  * \param supplied_vtodo the task to save
761  * \param msgnum number of the mesage in our db
762  */
763 void save_individual_task(icalcomponent *supplied_vtodo, long msgnum, char* from, int unread,
764                                 struct calview *calv)
765 {
766         char buf[SIZ];
767         int delete_existing = 0;
768         icalproperty *prop;
769         icalcomponent *vtodo, *encaps;
770         int created_new_vtodo = 0;
771         int i;
772         int sequence = 0;
773         struct icaltimetype t;
774
775         if (supplied_vtodo != NULL) {
776                 vtodo = supplied_vtodo;
777                 /**
778                  * If we're looking at a fully encapsulated VCALENDAR
779                  * rather than a VTODO component, attempt to use the first
780                  * relevant VTODO subcomponent.  If there is none, the
781                  * NULL returned by icalcomponent_get_first_component() will
782                  * tell the next iteration of this function to create a
783                  * new one.
784                  */
785                 if (icalcomponent_isa(vtodo) == ICAL_VCALENDAR_COMPONENT) {
786                         save_individual_task(
787                                 icalcomponent_get_first_component(
788                                         vtodo, ICAL_VTODO_COMPONENT), 
789                                 msgnum, from, unread, calv
790                                 );
791                         return;
792                 }
793         }
794         else {
795                 vtodo = icalcomponent_new(ICAL_VTODO_COMPONENT);
796                 created_new_vtodo = 1;
797         }
798
799         if (havebstr("save_button")) {
800
801                 /** Replace values in the component with ones from the form */
802
803                 while (prop = icalcomponent_get_first_property(vtodo,
804                                                                ICAL_SUMMARY_PROPERTY), prop != NULL) {
805                         icalcomponent_remove_property(vtodo, prop);
806                         icalproperty_free(prop);
807                 }
808                 if (havebstr("summary")) {
809
810                         icalcomponent_add_property(vtodo,
811                                                    icalproperty_new_summary(bstr("summary")));
812                 } else {
813                         icalcomponent_add_property(vtodo,
814                                                    icalproperty_new_summary("Untitled Task"));
815                 }
816         
817                 while (prop = icalcomponent_get_first_property(vtodo,
818                                                                ICAL_DESCRIPTION_PROPERTY), prop != NULL) {
819                         icalcomponent_remove_property(vtodo, prop);
820                         icalproperty_free(prop);
821                 }
822                 if (havebstr("description")) {
823                         icalcomponent_add_property(vtodo,
824                                                    icalproperty_new_description(bstr("description")));
825                 }
826         
827                 while (prop = icalcomponent_get_first_property(vtodo,
828                                                                ICAL_DTSTART_PROPERTY), prop != NULL) {
829                         icalcomponent_remove_property(vtodo, prop);
830                         icalproperty_free(prop);
831                 }
832                 if (IsEmptyStr(bstr("nodtstart"))) {
833                         icaltime_from_webform(&t, "dtstart");
834                         icalcomponent_add_property(vtodo,
835                                                    icalproperty_new_dtstart(t)
836                                 );
837                 }
838                 while(prop = icalcomponent_get_first_property(vtodo,
839                                                               ICAL_STATUS_PROPERTY), prop != NULL) {
840                         icalcomponent_remove_property(vtodo,prop);
841                         icalproperty_free(prop);
842                 }
843                 if (havebstr("status")) {
844                         icalproperty_status taskStatus = icalproperty_string_to_status(
845                                 bstr("status"));
846                         icalcomponent_set_status(vtodo, taskStatus);
847                 }
848                 while (prop = icalcomponent_get_first_property(vtodo,
849                                                                ICAL_CATEGORIES_PROPERTY), prop != NULL) {
850                         icalcomponent_remove_property(vtodo,prop);
851                         icalproperty_free(prop);
852                 }
853                 if (!IsEmptyStr(bstr("category"))) {
854                         prop = icalproperty_new_categories(bstr("category"));
855                         icalcomponent_add_property(vtodo,prop);
856                 }
857                 while (prop = icalcomponent_get_first_property(vtodo,
858                                                                ICAL_DUE_PROPERTY), prop != NULL) {
859                         icalcomponent_remove_property(vtodo, prop);
860                         icalproperty_free(prop);
861                 }
862                 if (IsEmptyStr(bstr("nodue"))) {
863                         icaltime_from_webform(&t, "due");
864                         icalcomponent_add_property(vtodo,
865                                                    icalproperty_new_due(t)
866                                 );
867                 }
868                 /** Give this task a UID if it doesn't have one. */
869                 lprintf(9, "Give this task a UID if it doesn't have one.\n");
870                 if (icalcomponent_get_first_property(vtodo,
871                                                      ICAL_UID_PROPERTY) == NULL) {
872                         generate_uuid(buf);
873                         icalcomponent_add_property(vtodo,
874                                                    icalproperty_new_uid(buf)
875                                 );
876                 }
877
878                 /** Increment the sequence ID */
879                 lprintf(9, "Increment the sequence ID\n");
880                 while (prop = icalcomponent_get_first_property(vtodo,
881                                                                ICAL_SEQUENCE_PROPERTY), (prop != NULL) ) {
882                         i = icalproperty_get_sequence(prop);
883                         lprintf(9, "Sequence was %d\n", i);
884                         if (i > sequence) sequence = i;
885                         icalcomponent_remove_property(vtodo, prop);
886                         icalproperty_free(prop);
887                 }
888                 ++sequence;
889                 lprintf(9, "New sequence is %d.  Adding...\n", sequence);
890                 icalcomponent_add_property(vtodo,
891                                            icalproperty_new_sequence(sequence)
892                         );
893
894                 /**
895                  * Encapsulate event into full VCALENDAR component.  Clone it first,
896                  * for two reasons: one, it's easier to just free the whole thing
897                  * when we're done instead of unbundling, but more importantly, we
898                  * can't encapsulate something that may already be encapsulated
899                  * somewhere else.
900                  */
901                 lprintf(9, "Encapsulating into a full VCALENDAR component\n");
902                 encaps = ical_encapsulate_subcomponent(icalcomponent_new_clone(vtodo));
903
904                 /* Serialize it and save it to the message base */
905                 serv_puts("ENT0 1|||4");
906                 serv_getln(buf, sizeof buf);
907                 if (buf[0] == '4') {
908                         serv_puts("Content-type: text/calendar");
909                         serv_puts("");
910                         serv_puts(icalcomponent_as_ical_string(encaps));
911                         serv_puts("000");
912
913                         /**
914                          * Probably not necessary; the server will see the UID
915                          * of the object and delete the old one anyway, but
916                          * just in case...
917                          */
918                         delete_existing = 1;
919                 }
920                 icalcomponent_free(encaps);
921         }
922
923         /**
924          * If the user clicked 'Delete' then explicitly delete the message.
925          */
926         if (havebstr("delete_button")) {
927                 delete_existing = 1;
928         }
929
930         if ( (delete_existing) && (msgnum > 0L) ) {
931                 serv_printf("DELE %ld", lbstr("msgnum"));
932                 serv_getln(buf, sizeof buf);
933         }
934
935         if (created_new_vtodo) {
936                 icalcomponent_free(vtodo);
937         }
938
939         /** Go back to the task list */
940         readloop(readfwd);
941 }
942
943
944
945 /*
946  * Code common to all icalendar display handlers.  Given a message number and a MIME
947  * type, we load the message and hunt for that MIME type.  If found, we load
948  * the relevant part, deserialize it into a libical component, filter it for
949  * the requested object type, and feed it to the specified handler.
950  */
951 void load_ical_object(long msgnum, int unread,
952                            icalcomponent_kind which_kind,
953                            void (*callback)(icalcomponent *, long, char*, int, struct calview *),
954                            struct calview *calv
955         ) 
956 {
957         char buf[1024];
958         char from[128] = "";
959         char mime_partnum[256];
960         char mime_filename[256];
961         char mime_content_type[256];
962         char mime_disposition[256];
963         int mime_length;
964         char relevant_partnum[256];
965         char *relevant_source = NULL;
966         icalcomponent *cal, *c;
967
968         relevant_partnum[0] = '\0';
969         sprintf(buf, "MSG4 %ld", msgnum);       /* we need the mime headers */
970         serv_puts(buf);
971         serv_getln(buf, sizeof buf);
972         if (buf[0] != '1') return;
973
974         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
975                 if (!strncasecmp(buf, "part=", 5)) {
976                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
977                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
978                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
979                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
980                         mime_length = extract_int(&buf[5], 5);
981
982                         if (  (!strcasecmp(mime_content_type, "text/calendar"))
983                               || (!strcasecmp(mime_content_type, "application/ics"))
984                               || (!strcasecmp(mime_content_type, "text/vtodo"))
985                                 ) {
986                                 strcpy(relevant_partnum, mime_partnum);
987                         }
988                 }
989                 else if (!strncasecmp(buf, "from=", 4)) {
990                         extract_token(from, buf, 1, '=', sizeof(from));
991                 }
992         }
993
994         if (!IsEmptyStr(relevant_partnum)) {
995                 relevant_source = load_mimepart(msgnum, relevant_partnum);
996                 if (relevant_source != NULL) {
997
998                         cal = icalcomponent_new_from_string(relevant_source);
999                         if (cal != NULL) {
1000
1001                                 /* A which_kind of (-1) means just load the whole thing */
1002                                 if (which_kind == (-1)) {
1003                                         callback(cal, msgnum, from, unread, calv);
1004                                 }
1005
1006                                 /* Otherwise recurse and hunt */
1007                                 else {
1008
1009                                         /* Simple components of desired type */
1010                                         if (icalcomponent_isa(cal) == which_kind) {
1011                                                 callback(cal, msgnum, from, unread, calv);
1012                                         }
1013         
1014                                         /* Subcomponents of desired type */
1015                                         for (c = icalcomponent_get_first_component(cal, which_kind);
1016                                         (c != 0);
1017                                         c = icalcomponent_get_next_component(cal, which_kind)) {
1018                                                 callback(c, msgnum, from, unread, calv);
1019                                         }
1020
1021                                 }
1022
1023                                 icalcomponent_free(cal);
1024                         }
1025                         free(relevant_source);
1026                 }
1027         }
1028         icalmemory_free_ring();
1029 }
1030
1031 /*
1032  * Display a calendar item
1033  */
1034 void load_calendar_item(message_summary *Msg, int unread, struct calview *c) {
1035         /*load_ical_object(Msg->msgnum, unread, ICAL_VEVENT_COMPONENT, display_individual_cal, c);*/
1036         load_ical_object(Msg->msgnum, unread, (-1), display_individual_cal, c);
1037 }
1038
1039 /*
1040  * Display task view
1041  */
1042 void display_task(message_summary *Msg, int unread) {
1043         load_ical_object(Msg->msgnum, unread, ICAL_VTODO_COMPONENT, display_individual_cal, NULL);
1044 }
1045
1046 /*
1047  * Display the editor component for a task
1048  */
1049 void display_edit_task(void) {
1050         long msgnum = 0L;
1051                         
1052         /* Force change the room if we have to */
1053         if (havebstr("taskrm")) {
1054                 gotoroom((char *)bstr("taskrm"));
1055         }
1056
1057         msgnum = lbstr("msgnum");
1058         if (msgnum > 0L) {
1059                 /* existing task */
1060                 load_ical_object(msgnum, 0,
1061                                       ICAL_VTODO_COMPONENT,
1062                                       display_edit_individual_task,
1063                                       NULL
1064                 );
1065         }
1066         else {
1067                 /* new task */
1068                 display_edit_individual_task(NULL, 0L, "", 0, NULL);
1069         }
1070 }
1071
1072 /*
1073  * save an edited task
1074  */
1075 void save_task(void) {
1076         long msgnum = 0L;
1077         msgnum = lbstr("msgnum");
1078         if (msgnum > 0L) {
1079                 load_ical_object(msgnum, 0, ICAL_VTODO_COMPONENT, save_individual_task, NULL);
1080         }
1081         else {
1082                 save_individual_task(NULL, 0L, "", 0, NULL);
1083         }
1084 }
1085
1086 /*
1087  * display the editor component for an event
1088  */
1089 void display_edit_event(void) {
1090         long msgnum = 0L;
1091
1092         msgnum = lbstr("msgnum");
1093         if (msgnum > 0L) {
1094                 /* existing event */
1095                 load_ical_object(msgnum, 0, ICAL_VEVENT_COMPONENT, display_edit_individual_event, NULL);
1096         }
1097         else {
1098                 /* new event */
1099                 display_edit_individual_event(NULL, 0L, "", 0, NULL);
1100         }
1101 }
1102
1103 /*
1104  * save an edited event
1105  */
1106 void save_event(void) {
1107         long msgnum = 0L;
1108
1109         msgnum = lbstr("msgnum");
1110
1111         if (msgnum > 0L) {
1112                 /* load_ical_object(msgnum, 0, ICAL_VEVENT_COMPONENT, save_individual_event, NULL); */
1113                 load_ical_object(msgnum, 0, (-1), save_individual_event, NULL);
1114         }
1115         else {
1116                 save_individual_event(NULL, 0L, "", 0, NULL);
1117         }
1118 }
1119
1120
1121
1122
1123
1124 /*
1125  * Anonymous request of freebusy data for a user
1126  */
1127 void do_freebusy(const char *req) {
1128         char who[SIZ];
1129         char buf[SIZ];
1130         int len;
1131         long lines;
1132
1133         extract_token(who, req, 1, ' ', sizeof who);
1134         if (!strncasecmp(who, "/freebusy/", 10)) {
1135                 strcpy(who, &who[10]);
1136         }
1137         unescape_input(who);
1138
1139         len = strlen(who);
1140         if ( (!strcasecmp(&who[len-4], ".vcf"))
1141              || (!strcasecmp(&who[len-4], ".ifb"))
1142              || (!strcasecmp(&who[len-4], ".vfb")) ) {
1143                 who[len-4] = 0;
1144         }
1145
1146         lprintf(9, "freebusy requested for <%s>\n", who);
1147         serv_printf("ICAL freebusy|%s", who);
1148         serv_getln(buf, sizeof buf);
1149
1150         if (buf[0] != '1') {
1151                 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
1152                 output_headers(0, 0, 0, 0, 0, 0);
1153                 hprintf("Content-Type: text/plain\r\n");
1154                 wprintf("%s\n", &buf[4]);
1155                 end_burst();
1156                 return;
1157         }
1158
1159         read_server_text(WC->WBuf, &lines);
1160         http_transmit_thing("text/calendar", 0);
1161 }
1162
1163
1164
1165
1166
1167 void 
1168 InitModule_CALENDAR
1169 (void)
1170 {
1171         WebcitAddUrlHandler(HKEY("display_edit_task"), display_edit_task, 0);
1172         WebcitAddUrlHandler(HKEY("save_task"), save_task, 0);
1173         WebcitAddUrlHandler(HKEY("display_edit_event"), display_edit_event, 0);
1174         WebcitAddUrlHandler(HKEY("save_event"), save_event, 0);
1175         WebcitAddUrlHandler(HKEY("respond_to_request"), respond_to_request, 0);
1176         WebcitAddUrlHandler(HKEY("handle_rsvp"), handle_rsvp, 0);
1177 }