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