* Did a fairly significant reworking of the calendar
[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 /*@}*/
378 /*-----------------------------------------------------------------------**/
379
380
381
382 /**
383  * \defgroup MsgDisplayHandlers Display handlers for message reading 
384  * \ingroup Calendaring
385  */
386
387 /*@{*/
388
389 int Flathash(const char *str, long len)
390 {
391         if (len != sizeof (int))
392                 return 0;
393         else return *(int*)str;
394 }
395
396
397
398 /**
399  * \brief clean up ical memory
400  * todo this could get trouble with future ical versions 
401  */
402 void delete_cal(void *vCal)
403 {
404         disp_cal *Cal = (disp_cal*) vCal;
405         icalcomponent_free(Cal->cal);
406         free(Cal->from);
407         free(Cal);
408 }
409
410 /*
411  * This is the meat-and-bones of the first part of our two-phase calendar display.
412  * As we encounter calendar items in messages being read from the server, we break out
413  * any iCalendar objects and store them in a hash table.  Later on, the second phase will
414  * use this hash table to render the calendar for display.
415  */
416 void display_individual_cal(icalcomponent *cal, long msgnum, char *from, int unread, struct calview *calv)
417 {
418         icalproperty *ps = NULL;
419         struct icaltimetype dtstart, dtend;
420         struct icaldurationtype dur;
421         struct wcsession *WCC = WC;
422         disp_cal *Cal;
423         size_t len;
424         time_t final_recurrence = 0;
425
426         /* recur variables */
427         icalproperty *rrule = NULL;
428         struct icalrecurrencetype recur;
429         icalrecur_iterator *ritr = NULL;
430         struct icaltimetype next;
431         int num_recur = 0;
432
433         dtstart = icaltime_null_time();
434         dtend = icaltime_null_time();
435         
436         if (WCC->disp_cal_items == NULL)
437                 WCC->disp_cal_items = NewHash(0, Flathash);
438
439         /* Note: anything we do here, we also have to do below for the recurrences. */
440         Cal = (disp_cal*) malloc(sizeof(disp_cal));
441         memset(Cal, 0, sizeof(disp_cal));
442         Cal->cal = icalcomponent_new_clone(cal);
443
444         /* Dezonify and decapsulate at the very last moment */
445         ical_dezonify(Cal->cal);
446         icalcomponent *cptr;
447         if (icalcomponent_isa(Cal->cal) != ICAL_VEVENT_COMPONENT) {
448                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
449                 if (cptr) {
450                         cptr = icalcomponent_new_clone(cptr);
451                         icalcomponent_free(Cal->cal);
452                         Cal->cal = cptr;
453                         lprintf(9, "Deeeeeeeeeeeeeecapsulated!\n");
454                 }
455         }
456
457         Cal->unread = unread;
458         len = strlen(from);
459         Cal->from = (char*)malloc(len+ 1);
460         memcpy(Cal->from, from, len + 1);
461         Cal->cal_msgnum = msgnum;
462
463         /* Precalculate the starting date and time of this event, and store it in our top-level
464          * structure.  Later, when we are rendering the calendar, we can just peek at these values
465          * without having to break apart every calendar item.
466          */
467         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTSTART_PROPERTY);
468         if (ps != NULL) {
469                 dtstart = icalproperty_get_dtstart(ps);
470                 Cal->event_start = icaltime_as_timet(dtstart);
471                 lprintf(9, "\e[31mINITIAL: %s, is_utc=%d, tzid=%s\e[0m\n",
472                         icaltime_as_ical_string(dtstart),
473                         icaltime_is_utc(dtstart),
474                         icaltime_get_tzid(dtstart)
475                 );
476         }
477
478         /* Do the same for the ending date and time.  It makes the day view much easier to render. */
479         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTEND_PROPERTY);
480         if (ps != NULL) {
481                 dtend = icalproperty_get_dtend(ps);
482                 Cal->event_end = icaltime_as_timet(dtend);
483         }
484
485         /* Store it in the hash list. */
486         Put(WCC->disp_cal_items, 
487             (char*) &Cal->event_start,
488             sizeof(Cal->event_start), 
489             Cal, 
490             delete_cal);
491
492         /* handle recurring events */
493
494         if (icaltime_is_null_time(dtstart)) return;     /* Can't recur without a start time */
495
496         if (!icaltime_is_null_time(dtend)) {            /* Need duration for recurrences */
497                 dur = icaltime_subtract(dtend, dtstart);
498         }
499
500         /*
501          * Just let libical iterate the recurrence, and keep looping back to the top of this function,
502          * adding new hash entries that all point back to the same msgnum, until either the iteration
503          * stops or some outer bound is reached.  The display code will automatically do the Right Thing.
504          */
505         rrule = icalcomponent_get_first_property(cal, ICAL_RRULE_PROPERTY);
506         if (!rrule) return;
507         recur = icalproperty_get_rrule(rrule);
508         ritr = icalrecur_iterator_new(recur, dtstart);
509         if (!ritr) return;
510
511         int stop_rr = 0;
512         while (next = icalrecur_iterator_next(ritr), ((!icaltime_is_null_time(next))&&(!stop_rr)) ) {
513                 ++num_recur;
514
515                 if (num_recur > 1) {            /* Skip the first one.  We already did it at the root. */
516
517                         /* Note: anything we do here, we also have to do above for the root event. */
518                         Cal = (disp_cal*) malloc(sizeof(disp_cal));
519                         memset(Cal, 0, sizeof(disp_cal));
520                         Cal->cal = icalcomponent_new_clone(cal);
521                         Cal->unread = unread;
522                         len = strlen(from);
523                         Cal->from = (char*)malloc(len+ 1);
524                         memcpy(Cal->from, from, len + 1);
525                         Cal->cal_msgnum = msgnum;
526         
527                         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTSTART_PROPERTY);
528                         if (ps != NULL) {
529                                 icalcomponent_remove_property(Cal->cal, ps);
530                                 ps = icalproperty_new_dtstart(next);
531                                 icalcomponent_add_property(Cal->cal, ps);
532
533                                 /* Dezonify and decapsulate each recurrence individually, otherwise
534                                  * we slide over by an hour whenever we cross a DST boundary.
535                                  */
536                                 ical_dezonify(Cal->cal);
537                                 icalcomponent *cptr;
538                                 if (icalcomponent_isa(Cal->cal) != ICAL_VEVENT_COMPONENT) {
539                                         cptr = icalcomponent_get_first_component(Cal->cal,
540                                                 ICAL_VEVENT_COMPONENT);
541                                         if (cptr) {
542                                                 cptr = icalcomponent_new_clone(cptr);
543                                                 icalcomponent_free(Cal->cal);
544                                                 Cal->cal = cptr;
545                                                 lprintf(9, "Deeeeeeeeeeeeeecapsulated!\n");
546                                         }
547                                 }
548
549
550                                 /* FIXME the above is broken, why? */
551
552
553
554
555
556
557                                 Cal->event_start = icaltime_as_timet(next);
558                                 lprintf(9, "\e[32mREPEATS: %s, is_utc=%d, tzid=%s\e[0m\n",
559                                         icaltime_as_ical_string(next),
560                                         icaltime_is_utc(next),
561                                         icaltime_get_tzid(next)
562                                 );
563                                 final_recurrence = Cal->event_start;
564                         }
565         
566                         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTEND_PROPERTY);
567                         if (ps != NULL) {
568                                 icalcomponent_remove_property(Cal->cal, ps);
569
570                                 /* Make a new dtend */
571                                 ps = icalproperty_new_dtend(icaltime_add(next, dur));
572         
573                                 /* and stick it somewhere */
574                                 icalcomponent_add_property(Cal->cal, ps);
575                         }
576         
577                         if ( (Cal->event_start > calv->lower_bound)
578                            && (Cal->event_start < calv->upper_bound) ) {
579                                 Put(WCC->disp_cal_items, 
580                                         (char*) &Cal->event_start,
581                                         sizeof(Cal->event_start), 
582                                         Cal, 
583                                         delete_cal
584                                 );
585                         }
586                         else {
587                                 delete_cal(Cal);
588                         }
589
590                         /* If an upper bound is set, stop when we go out of scope */
591                         if (final_recurrence > calv->upper_bound) stop_rr = 1;
592                 }
593         }
594         icalrecur_iterator_free(ritr);
595         /* lprintf(9, "Performed %d recurrences; final one is %s", num_recur, ctime(&final_recurrence)); */
596
597 }
598
599
600
601 /*
602  * Display a task by itself (for editing)
603  */
604 void display_edit_individual_task(icalcomponent *supplied_vtodo, long msgnum, char *from,
605                         int unread, struct calview *calv)
606 {
607         icalcomponent *vtodo;
608         icalproperty *p;
609         struct icaltimetype IcalTime;
610         time_t now;
611         int created_new_vtodo = 0;
612         icalproperty_status todoStatus;
613
614         now = time(NULL);
615
616         if (supplied_vtodo != NULL) {
617                 vtodo = supplied_vtodo;
618
619                 /**
620                  * If we're looking at a fully encapsulated VCALENDAR
621                  * rather than a VTODO component, attempt to use the first
622                  * relevant VTODO subcomponent.  If there is none, the
623                  * NULL returned by icalcomponent_get_first_component() will
624                  * tell the next iteration of this function to create a
625                  * new one.
626                  */
627                 if (icalcomponent_isa(vtodo) == ICAL_VCALENDAR_COMPONENT) {
628                         display_edit_individual_task(
629                                 icalcomponent_get_first_component(
630                                         vtodo, ICAL_VTODO_COMPONENT
631                                         ), 
632                                 msgnum, from, unread, calv
633                                 );
634                         return;
635                 }
636         }
637         else {
638                 vtodo = icalcomponent_new(ICAL_VTODO_COMPONENT);
639                 created_new_vtodo = 1;
640         }
641         
642         // TODO: Can we take all this and move it into a template?      
643         output_headers(1, 1, 1, 0, 0, 0);
644         wprintf("<!-- start task edit form -->");
645         p = icalcomponent_get_first_property(vtodo, ICAL_SUMMARY_PROPERTY);
646         // Get summary early for title
647         wprintf("<div class=\"box\">\n");
648         wprintf("<div class=\"boxlabel\">");
649         wprintf(_("Edit task"));
650         wprintf("- ");
651         if (p != NULL) {
652                 escputs((char *)icalproperty_get_comment(p));
653         }
654         wprintf("</div>");
655         
656         wprintf("<div class=\"boxcontent\">\n");
657         wprintf("<FORM METHOD=\"POST\" action=\"save_task\">\n");
658         wprintf("<div style=\"display: none;\">\n       ");
659         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
660         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgnum\" VALUE=\"%ld\">\n",
661                 msgnum);
662         wprintf("</div>");
663         wprintf("<table class=\"calendar_background\"><tr><td>");
664         wprintf("<TABLE STYLE=\"border: none;\">\n");
665
666         wprintf("<TR><TD>");
667         wprintf(_("Summary:"));
668         wprintf("</TD><TD>"
669                 "<INPUT TYPE=\"text\" NAME=\"summary\" "
670                 "MAXLENGTH=\"64\" SIZE=\"64\" VALUE=\"");
671         p = icalcomponent_get_first_property(vtodo, ICAL_SUMMARY_PROPERTY);
672         if (p != NULL) {
673                 escputs((char *)icalproperty_get_comment(p));
674         }
675         wprintf("\"></TD></TR>\n");
676
677         wprintf("<TR><TD>");
678         wprintf(_("Start date:"));
679         wprintf("</TD><TD>");
680         p = icalcomponent_get_first_property(vtodo, ICAL_DTSTART_PROPERTY);
681         wprintf("<INPUT TYPE=\"CHECKBOX\" NAME=\"nodtstart\" ID=\"nodtstart\" VALUE=\"NODTSTART\" ");
682         if (p == NULL) {
683                 wprintf("CHECKED=\"CHECKED\"");
684         }
685         wprintf(">");
686         wprintf(_("No date"));
687         
688         wprintf(" ");
689         wprintf(_("or"));
690         wprintf(" ");
691         if (p != NULL) {
692                 IcalTime = icalproperty_get_dtstart(p);
693         }
694         else
695                 IcalTime = icaltime_current_time_with_zone(get_default_icaltimezone());
696         display_icaltimetype_as_webform(&IcalTime, "dtstart", 0);
697         wprintf("</TD></TR>\n");
698
699         wprintf("<TR><TD>");
700         wprintf(_("Due date:"));
701         wprintf("</TD><TD>");
702         p = icalcomponent_get_first_property(vtodo, ICAL_DUE_PROPERTY);
703         wprintf("<INPUT TYPE=\"CHECKBOX\" NAME=\"nodue\" ID=\"nodue\" VALUE=\"NODUE\"");
704         if (p == NULL) {
705                 wprintf("CHECKED=\"CHECKED\"");
706         }
707         wprintf(">");
708         wprintf(_("No date"));
709         wprintf(" ");
710         wprintf(_("or"));
711         wprintf(" ");
712         if (p != NULL) {
713                 IcalTime = icalproperty_get_due(p);
714         }
715         else
716                 IcalTime = icaltime_current_time_with_zone(get_default_icaltimezone());
717         display_icaltimetype_as_webform(&IcalTime, "due", 0);
718                 
719         wprintf("</TD></TR>\n");
720         todoStatus = icalcomponent_get_status(vtodo);
721         wprintf("<TR><TD>\n");
722         wprintf(_("Completed:"));
723         wprintf("</TD><TD>");
724         wprintf("<INPUT TYPE=\"CHECKBOX\" NAME=\"status\" VALUE=\"COMPLETED\"");
725         if (todoStatus == ICAL_STATUS_COMPLETED) {
726                 wprintf(" CHECKED=\"CHECKED\"");
727         } 
728         wprintf(" >");
729         wprintf("</TD></TR>");
730         // start category field
731         p = icalcomponent_get_first_property(vtodo, ICAL_CATEGORIES_PROPERTY);
732         wprintf("<TR><TD>");
733         wprintf(_("Category:"));
734         wprintf("</TD><TD>");
735         wprintf("<INPUT TYPE=\"text\" NAME=\"category\" MAXLENGTH=\"32\" SIZE=\"32\" VALUE=\"");
736         if (p != NULL) {
737                 escputs((char *)icalproperty_get_categories(p));
738         }
739         wprintf("\">");
740         wprintf("</TD></TR>\n   ");
741         // end category field
742         wprintf("<TR><TD>");
743         wprintf(_("Description:"));
744         wprintf("</TD><TD>");
745         wprintf("<TEXTAREA NAME=\"description\" "
746                 "ROWS=\"10\" COLS=\"80\">\n"
747                 );
748         p = icalcomponent_get_first_property(vtodo, ICAL_DESCRIPTION_PROPERTY);
749         if (p != NULL) {
750                 escputs((char *)icalproperty_get_comment(p));
751         }
752         wprintf("</TEXTAREA></TD></TR></TABLE>\n");
753
754         wprintf("<SPAN STYLE=\"text-align: center;\">"
755                 "<INPUT TYPE=\"submit\" NAME=\"save_button\" VALUE=\"%s\">"
756                 "&nbsp;&nbsp;"
757                 "<INPUT TYPE=\"submit\" NAME=\"delete_button\" VALUE=\"%s\">\n"
758                 "&nbsp;&nbsp;"
759                 "<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">\n"
760                 "</SPAN>\n",
761                 _("Save"),
762                 _("Delete"),
763                 _("Cancel")
764                 );
765         wprintf("</td></tr></table>");
766         wprintf("</FORM>\n");
767         wprintf("</div></div></div>\n");
768         wprintf("<!-- end task edit form -->");
769         wDumpContent(1);
770
771         if (created_new_vtodo) {
772                 icalcomponent_free(vtodo);
773         }
774 }
775
776 /*
777  * \brief Save an edited task
778  * \param supplied_vtodo the task to save
779  * \param msgnum number of the mesage in our db
780  */
781 void save_individual_task(icalcomponent *supplied_vtodo, long msgnum, char* from, int unread,
782                                 struct calview *calv)
783 {
784         char buf[SIZ];
785         int delete_existing = 0;
786         icalproperty *prop;
787         icalcomponent *vtodo, *encaps;
788         int created_new_vtodo = 0;
789         int i;
790         int sequence = 0;
791         struct icaltimetype t;
792
793         if (supplied_vtodo != NULL) {
794                 vtodo = supplied_vtodo;
795                 /**
796                  * If we're looking at a fully encapsulated VCALENDAR
797                  * rather than a VTODO component, attempt to use the first
798                  * relevant VTODO subcomponent.  If there is none, the
799                  * NULL returned by icalcomponent_get_first_component() will
800                  * tell the next iteration of this function to create a
801                  * new one.
802                  */
803                 if (icalcomponent_isa(vtodo) == ICAL_VCALENDAR_COMPONENT) {
804                         save_individual_task(
805                                 icalcomponent_get_first_component(
806                                         vtodo, ICAL_VTODO_COMPONENT), 
807                                 msgnum, from, unread, calv
808                                 );
809                         return;
810                 }
811         }
812         else {
813                 vtodo = icalcomponent_new(ICAL_VTODO_COMPONENT);
814                 created_new_vtodo = 1;
815         }
816
817         if (havebstr("save_button")) {
818
819                 /** Replace values in the component with ones from the form */
820
821                 while (prop = icalcomponent_get_first_property(vtodo,
822                                                                ICAL_SUMMARY_PROPERTY), prop != NULL) {
823                         icalcomponent_remove_property(vtodo, prop);
824                         icalproperty_free(prop);
825                 }
826                 if (havebstr("summary")) {
827
828                         icalcomponent_add_property(vtodo,
829                                                    icalproperty_new_summary(bstr("summary")));
830                 } else {
831                         icalcomponent_add_property(vtodo,
832                                                    icalproperty_new_summary("Untitled Task"));
833                 }
834         
835                 while (prop = icalcomponent_get_first_property(vtodo,
836                                                                ICAL_DESCRIPTION_PROPERTY), prop != NULL) {
837                         icalcomponent_remove_property(vtodo, prop);
838                         icalproperty_free(prop);
839                 }
840                 if (havebstr("description")) {
841                         icalcomponent_add_property(vtodo,
842                                                    icalproperty_new_description(bstr("description")));
843                 }
844         
845                 while (prop = icalcomponent_get_first_property(vtodo,
846                                                                ICAL_DTSTART_PROPERTY), prop != NULL) {
847                         icalcomponent_remove_property(vtodo, prop);
848                         icalproperty_free(prop);
849                 }
850                 if (IsEmptyStr(bstr("nodtstart"))) {
851                         icaltime_from_webform(&t, "dtstart");
852                         icalcomponent_add_property(vtodo,
853                                                    icalproperty_new_dtstart(t)
854                                 );
855                 }
856                 while(prop = icalcomponent_get_first_property(vtodo,
857                                                               ICAL_STATUS_PROPERTY), prop != NULL) {
858                         icalcomponent_remove_property(vtodo,prop);
859                         icalproperty_free(prop);
860                 }
861                 if (havebstr("status")) {
862                         icalproperty_status taskStatus = icalproperty_string_to_status(
863                                 bstr("status"));
864                         icalcomponent_set_status(vtodo, taskStatus);
865                 }
866                 while (prop = icalcomponent_get_first_property(vtodo,
867                                                                ICAL_CATEGORIES_PROPERTY), prop != NULL) {
868                         icalcomponent_remove_property(vtodo,prop);
869                         icalproperty_free(prop);
870                 }
871                 if (!IsEmptyStr(bstr("category"))) {
872                         prop = icalproperty_new_categories(bstr("category"));
873                         icalcomponent_add_property(vtodo,prop);
874                 }
875                 while (prop = icalcomponent_get_first_property(vtodo,
876                                                                ICAL_DUE_PROPERTY), prop != NULL) {
877                         icalcomponent_remove_property(vtodo, prop);
878                         icalproperty_free(prop);
879                 }
880                 if (IsEmptyStr(bstr("nodue"))) {
881                         icaltime_from_webform(&t, "due");
882                         icalcomponent_add_property(vtodo,
883                                                    icalproperty_new_due(t)
884                                 );
885                 }
886                 /** Give this task a UID if it doesn't have one. */
887                 lprintf(9, "Give this task a UID if it doesn't have one.\n");
888                 if (icalcomponent_get_first_property(vtodo,
889                                                      ICAL_UID_PROPERTY) == NULL) {
890                         generate_uuid(buf);
891                         icalcomponent_add_property(vtodo,
892                                                    icalproperty_new_uid(buf)
893                                 );
894                 }
895
896                 /** Increment the sequence ID */
897                 lprintf(9, "Increment the sequence ID\n");
898                 while (prop = icalcomponent_get_first_property(vtodo,
899                                                                ICAL_SEQUENCE_PROPERTY), (prop != NULL) ) {
900                         i = icalproperty_get_sequence(prop);
901                         lprintf(9, "Sequence was %d\n", i);
902                         if (i > sequence) sequence = i;
903                         icalcomponent_remove_property(vtodo, prop);
904                         icalproperty_free(prop);
905                 }
906                 ++sequence;
907                 lprintf(9, "New sequence is %d.  Adding...\n", sequence);
908                 icalcomponent_add_property(vtodo,
909                                            icalproperty_new_sequence(sequence)
910                         );
911
912                 /**
913                  * Encapsulate event into full VCALENDAR component.  Clone it first,
914                  * for two reasons: one, it's easier to just free the whole thing
915                  * when we're done instead of unbundling, but more importantly, we
916                  * can't encapsulate something that may already be encapsulated
917                  * somewhere else.
918                  */
919                 lprintf(9, "Encapsulating into a full VCALENDAR component\n");
920                 encaps = ical_encapsulate_subcomponent(icalcomponent_new_clone(vtodo));
921
922                 /* Serialize it and save it to the message base */
923                 serv_puts("ENT0 1|||4");
924                 serv_getln(buf, sizeof buf);
925                 if (buf[0] == '4') {
926                         serv_puts("Content-type: text/calendar");
927                         serv_puts("");
928                         serv_puts(icalcomponent_as_ical_string(encaps));
929                         serv_puts("000");
930
931                         /**
932                          * Probably not necessary; the server will see the UID
933                          * of the object and delete the old one anyway, but
934                          * just in case...
935                          */
936                         delete_existing = 1;
937                 }
938                 icalcomponent_free(encaps);
939         }
940
941         /**
942          * If the user clicked 'Delete' then explicitly delete the message.
943          */
944         if (havebstr("delete_button")) {
945                 delete_existing = 1;
946         }
947
948         if ( (delete_existing) && (msgnum > 0L) ) {
949                 serv_printf("DELE %ld", lbstr("msgnum"));
950                 serv_getln(buf, sizeof buf);
951         }
952
953         if (created_new_vtodo) {
954                 icalcomponent_free(vtodo);
955         }
956
957         /** Go back to the task list */
958         readloop("readfwd");
959 }
960
961
962
963 /*
964  * Code common to all icalendar display handlers.  Given a message number and a MIME
965  * type, we load the message and hunt for that MIME type.  If found, we load
966  * the relevant part, deserialize it into a libical component, filter it for
967  * the requested object type, and feed it to the specified handler.
968  */
969 void load_ical_object(long msgnum, int unread,
970                            icalcomponent_kind which_kind,
971                            void (*callback)(icalcomponent *, long, char*, int, struct calview *),
972                            struct calview *calv
973         ) 
974 {
975         char buf[1024];
976         char from[128] = "";
977         char mime_partnum[256];
978         char mime_filename[256];
979         char mime_content_type[256];
980         char mime_disposition[256];
981         int mime_length;
982         char relevant_partnum[256];
983         char *relevant_source = NULL;
984         icalcomponent *cal, *c;
985
986         relevant_partnum[0] = '\0';
987         sprintf(buf, "MSG4 %ld", msgnum);       /* we need the mime headers */
988         serv_puts(buf);
989         serv_getln(buf, sizeof buf);
990         if (buf[0] != '1') return;
991
992         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
993                 if (!strncasecmp(buf, "part=", 5)) {
994                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
995                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
996                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
997                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
998                         mime_length = extract_int(&buf[5], 5);
999
1000                         if (  (!strcasecmp(mime_content_type, "text/calendar"))
1001                               || (!strcasecmp(mime_content_type, "application/ics"))
1002                               || (!strcasecmp(mime_content_type, "text/vtodo"))
1003                                 ) {
1004                                 strcpy(relevant_partnum, mime_partnum);
1005                         }
1006                 }
1007                 else if (!strncasecmp(buf, "from=", 4)) {
1008                         extract_token(from, buf, 1, '=', sizeof(from));
1009                 }
1010         }
1011
1012         if (!IsEmptyStr(relevant_partnum)) {
1013                 relevant_source = load_mimepart(msgnum, relevant_partnum);
1014                 if (relevant_source != NULL) {
1015
1016                         cal = icalcomponent_new_from_string(relevant_source);
1017                         if (cal != NULL) {
1018                                 /* FIXME temp */
1019                                 icalproperty *p;
1020                                 p = icalcomponent_get_first_property(cal, ICAL_DTSTART_PROPERTY);
1021                                 if (p) {
1022                                         lprintf(9, "DTSTART IS %s\n", 
1023                                                 icaltime_as_ical_string(
1024                                                         icalproperty_get_dtstart(p)
1025                                                 )
1026                                         );
1027                                 }
1028                                 /* */
1029
1030
1031                                 /* A which_kind of (-1) means just load the whole thing */
1032                                 if (which_kind == (-1)) {
1033                                         callback(cal, msgnum, from, unread, calv);
1034                                 }
1035
1036                                 /* Otherwise recurse and hunt */
1037                                 else {
1038
1039                                         /* Simple components of desired type */
1040                                         if (icalcomponent_isa(cal) == which_kind) {
1041                                                 callback(cal, msgnum, from, unread, calv);
1042                                         }
1043         
1044                                         /* Subcomponents of desired type */
1045                                         for (c = icalcomponent_get_first_component(cal, which_kind);
1046                                         (c != 0);
1047                                         c = icalcomponent_get_next_component(cal, which_kind)) {
1048                                                 callback(c, msgnum, from, unread, calv);
1049                                         }
1050
1051                                 }
1052
1053                                 icalcomponent_free(cal);
1054                         }
1055                         free(relevant_source);
1056                 }
1057         }
1058         icalmemory_free_ring();
1059 }
1060
1061 /*
1062  * Display a calendar item
1063  */
1064 void load_calendar_item(message_summary *Msg, int unread, struct calview *c) {
1065         /*load_ical_object(Msg->msgnum, unread, ICAL_VEVENT_COMPONENT, display_individual_cal, c);*/
1066         load_ical_object(Msg->msgnum, unread, (-1), display_individual_cal, c);
1067 }
1068
1069 /*
1070  * Display task view
1071  */
1072 void display_task(message_summary *Msg, int unread) {
1073         load_ical_object(Msg->msgnum, unread, ICAL_VTODO_COMPONENT, display_individual_cal, NULL);
1074 }
1075
1076 /*
1077  * Display the editor component for a task
1078  */
1079 void display_edit_task(void) {
1080         long msgnum = 0L;
1081                         
1082         /* Force change the room if we have to */
1083         if (havebstr("taskrm")) {
1084                 gotoroom((char *)bstr("taskrm"));
1085         }
1086
1087         msgnum = lbstr("msgnum");
1088         if (msgnum > 0L) {
1089                 /* existing task */
1090                 load_ical_object(msgnum, 0,
1091                                       ICAL_VTODO_COMPONENT,
1092                                       display_edit_individual_task,
1093                                       NULL
1094                 );
1095         }
1096         else {
1097                 /* new task */
1098                 display_edit_individual_task(NULL, 0L, "", 0, NULL);
1099         }
1100 }
1101
1102 /*
1103  * save an edited task
1104  */
1105 void save_task(void) {
1106         long msgnum = 0L;
1107         msgnum = lbstr("msgnum");
1108         if (msgnum > 0L) {
1109                 load_ical_object(msgnum, 0, ICAL_VTODO_COMPONENT, save_individual_task, NULL);
1110         }
1111         else {
1112                 save_individual_task(NULL, 0L, "", 0, NULL);
1113         }
1114 }
1115
1116 /*
1117  * display the editor component for an event
1118  */
1119 void display_edit_event(void) {
1120         long msgnum = 0L;
1121
1122         msgnum = lbstr("msgnum");
1123         if (msgnum > 0L) {
1124                 /* existing event */
1125                 load_ical_object(msgnum, 0, ICAL_VEVENT_COMPONENT, display_edit_individual_event, NULL);
1126         }
1127         else {
1128                 /* new event */
1129                 display_edit_individual_event(NULL, 0L, "", 0, NULL);
1130         }
1131 }
1132
1133 /*
1134  * save an edited event
1135  */
1136 void save_event(void) {
1137         long msgnum = 0L;
1138
1139         msgnum = lbstr("msgnum");
1140
1141         if (msgnum > 0L) {
1142                 load_ical_object(msgnum, 0, ICAL_VEVENT_COMPONENT, save_individual_event, NULL);
1143         }
1144         else {
1145                 save_individual_event(NULL, 0L, "", 0, NULL);
1146         }
1147 }
1148
1149
1150
1151
1152
1153 /*
1154  * Anonymous request of freebusy data for a user
1155  */
1156 void do_freebusy(const char *req) {
1157         char who[SIZ];
1158         char buf[SIZ];
1159         int len;
1160         long lines;
1161
1162         extract_token(who, req, 1, ' ', sizeof who);
1163         if (!strncasecmp(who, "/freebusy/", 10)) {
1164                 strcpy(who, &who[10]);
1165         }
1166         unescape_input(who);
1167
1168         len = strlen(who);
1169         if ( (!strcasecmp(&who[len-4], ".vcf"))
1170              || (!strcasecmp(&who[len-4], ".ifb"))
1171              || (!strcasecmp(&who[len-4], ".vfb")) ) {
1172                 who[len-4] = 0;
1173         }
1174
1175         lprintf(9, "freebusy requested for <%s>\n", who);
1176         serv_printf("ICAL freebusy|%s", who);
1177         serv_getln(buf, sizeof buf);
1178
1179         if (buf[0] != '1') {
1180                 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
1181                 output_headers(0, 0, 0, 0, 0, 0);
1182                 hprintf("Content-Type: text/plain\r\n");
1183                 wprintf("%s\n", &buf[4]);
1184                 end_burst();
1185                 return;
1186         }
1187
1188         read_server_text(WC->WBuf, &lines);
1189         http_transmit_thing("text/calendar", 0);
1190 }
1191
1192
1193
1194
1195
1196 void 
1197 InitModule_CALENDAR
1198 (void)
1199 {
1200         WebcitAddUrlHandler(HKEY("display_edit_task"), display_edit_task, 0);
1201         WebcitAddUrlHandler(HKEY("save_task"), save_task, 0);
1202         WebcitAddUrlHandler(HKEY("display_edit_event"), display_edit_event, 0);
1203         WebcitAddUrlHandler(HKEY("save_event"), save_event, 0);
1204         WebcitAddUrlHandler(HKEY("respond_to_request"), respond_to_request, 0);
1205         WebcitAddUrlHandler(HKEY("handle_rsvp"), handle_rsvp, 0);
1206 }