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