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