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