Mailing list header changes (fuck you Google)
[citadel.git] / webcit / calendar.c
1 /*
2  * Functions which handle calendar objects and their processing/display.
3  *
4  * Copyright (c) 1996-2012 by the citadel.org team
5  *
6  * This program is open source software.  You can redistribute it and/or
7  * modify it under the terms of the GNU General Public License, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include "webcit.h"
16 #include "webserver.h"
17 #include "calendar.h"
18
19 /*
20  * Process a calendar object.  At this point it's already been deserialized by cal_process_attachment()
21  *
22  * cal:                 the calendar object
23  * recursion_level:     Number of times we've recursed into this function
24  * msgnum:              Message number on the Citadel server
25  * cal_partnum:         MIME part number within that message containing the calendar object
26  */
27 void cal_process_object(StrBuf *Target,
28                         icalcomponent *cal,
29                         int recursion_level,
30                         long msgnum,
31                         const char *cal_partnum) 
32 {
33         icalcomponent *c;
34         icalproperty *method = NULL;
35         icalproperty_method the_method = ICAL_METHOD_NONE;
36         icalproperty *p;
37         struct icaltimetype t;
38         time_t tt;
39         char buf[256];
40         char conflict_name[256];
41         char conflict_message[256];
42         int is_update = 0;
43         char divname[32];
44         static int divcount = 0;
45         const char *ch;
46
47         sprintf(divname, "rsvp%04x", ++divcount);
48
49         /* Convert timezones to something easy to display.
50          * It's safe to do this in memory because we're only changing it on the
51          * display side -- when we tell the server to do something with the object,
52          * the server will be working with its original copy in the database.
53          */
54         if ((cal) && (recursion_level == 0)) {
55                 ical_dezonify(cal);
56         }
57
58         /* Leading HTML for the display of this object */
59         if (recursion_level == 0) {
60                 StrBufAppendPrintf(Target, "<div class=\"mimepart\">\n");
61         }
62
63         /* Look for a method */
64         method = icalcomponent_get_first_property(cal, ICAL_METHOD_PROPERTY);
65
66         /* See what we need to do with this */
67         if (method != NULL) {
68                 char *title;
69                 the_method = icalproperty_get_method(method);
70
71                 StrBufAppendPrintf(Target, "<div id=\"%s_title\">", divname);
72                 StrBufAppendPrintf(Target, "<img src=\"static/webcit_icons/essen/32x32/calendar.png\">");
73                 StrBufAppendPrintf(Target, "<span>");
74                 switch(the_method) {
75                 case ICAL_METHOD_REQUEST:
76                         title = _("Meeting invitation");
77                         break;
78                 case ICAL_METHOD_REPLY:
79                         title = _("Attendee's reply to your invitation");
80                         break;
81                 case ICAL_METHOD_PUBLISH:
82                         title = _("Published event");
83                         break;
84                 default:
85                         title = _("This is an unknown type of calendar item.");
86                         break;
87                 }
88                 StrBufAppendPrintf(Target, "</span>");
89
90                 StrBufAppendPrintf(Target, "&nbsp;&nbsp;%s",title);
91                 StrBufAppendPrintf(Target, "</div>");
92         }
93
94         StrBufAppendPrintf(Target, "<dl>");
95         p = icalcomponent_get_first_property(cal, ICAL_SUMMARY_PROPERTY);
96         if (p != NULL) {
97                 StrBufAppendPrintf(Target, "<dt>");
98                 StrBufAppendPrintf(Target, _("Summary:"));
99                 StrBufAppendPrintf(Target, "</dt><dd>");
100                 StrEscAppend(Target, NULL, (char *)icalproperty_get_comment(p), 0, 0);
101                 StrBufAppendPrintf(Target, "</dd>\n");
102         }
103
104         p = icalcomponent_get_first_property(cal, ICAL_LOCATION_PROPERTY);
105         if (p != NULL) {
106                 StrBufAppendPrintf(Target, "<dt>");
107                 StrBufAppendPrintf(Target, _("Location:"));
108                 StrBufAppendPrintf(Target, "</dt><dd>");
109                 StrEscAppend(Target, NULL, (char *)icalproperty_get_comment(p), 0, 0);
110                 StrBufAppendPrintf(Target, "</dd>\n");
111         }
112
113         /*
114          * Only show start/end times if we're actually looking at the VEVENT
115          * component.  Otherwise it shows bogus dates for things like timezone.
116          */
117         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
118
119                 p = icalcomponent_get_first_property(cal, ICAL_DTSTART_PROPERTY);
120                 if (p != NULL) {
121                         t = icalproperty_get_dtstart(p);
122
123                         if (t.is_date) {
124                                 struct tm d_tm;
125                                 char d_str[32];
126                                 memset(&d_tm, 0, sizeof d_tm);
127                                 d_tm.tm_year = t.year - 1900;
128                                 d_tm.tm_mon = t.month - 1;
129                                 d_tm.tm_mday = t.day;
130                                 wc_strftime(d_str, sizeof d_str, "%x", &d_tm);
131                                 StrBufAppendPrintf(Target, "<dt>");
132                                 StrBufAppendPrintf(Target, _("Date:"));
133                                 StrBufAppendPrintf(Target, "</dt><dd>%s</dd>", d_str);
134                         }
135                         else {
136                                 tt = icaltime_as_timet(t);
137                                 webcit_fmt_date(buf, 256, tt, DATEFMT_FULL);
138                                 StrBufAppendPrintf(Target, "<dt>");
139                                 StrBufAppendPrintf(Target, _("Starting date/time:"));
140                                 StrBufAppendPrintf(Target, "</dt><dd>%s</dd>", buf);
141                         }
142                 }
143         
144                 p = icalcomponent_get_first_property(cal, ICAL_DTEND_PROPERTY);
145                 if (p != NULL) {
146                         t = icalproperty_get_dtend(p);
147                         tt = icaltime_as_timet(t);
148                         webcit_fmt_date(buf, 256, tt, DATEFMT_FULL);
149                         StrBufAppendPrintf(Target, "<dt>");
150                         StrBufAppendPrintf(Target, _("Ending date/time:"));
151                         StrBufAppendPrintf(Target, "</dt><dd>%s</dd>", buf);
152                 }
153
154         }
155
156         p = icalcomponent_get_first_property(cal, ICAL_DESCRIPTION_PROPERTY);
157         if (p != NULL) {
158                 StrBufAppendPrintf(Target, "<dt>");
159                 StrBufAppendPrintf(Target, _("Description:"));
160                 StrBufAppendPrintf(Target, "</dt><dd>");
161                 StrEscAppend(Target, NULL, (char *)icalproperty_get_comment(p), 0, 0);
162                 StrBufAppendPrintf(Target, "</dd>\n");
163         }
164
165         if (icalcomponent_get_first_property(cal, ICAL_RRULE_PROPERTY)) {
166                 /* Unusual string syntax used here in order to re-use existing translations */
167                 StrBufAppendPrintf(Target, "<dt>%s:</dt><dd>%s.</dd>\n",
168                         _("Recurrence"),
169                         _("This is a recurring event")
170                 );
171         }
172
173         /* If the component has attendees, iterate through them. */
174         for (p = icalcomponent_get_first_property(cal, ICAL_ATTENDEE_PROPERTY); 
175              (p != NULL); 
176              p = icalcomponent_get_next_property(cal, ICAL_ATTENDEE_PROPERTY)) {
177                 StrBufAppendPrintf(Target, "<dt>");
178                 StrBufAppendPrintf(Target, _("Attendee:"));
179                 StrBufAppendPrintf(Target, "</dt><dd>");
180                 ch = icalproperty_get_attendee(p);
181                 if ((ch != NULL) && !strncasecmp(ch, "MAILTO:", 7)) {
182
183                         /** screen name or email address */
184                         safestrncpy(buf, ch + 7, sizeof(buf));
185                         striplt(buf);
186                         StrEscAppend(Target, NULL, buf, 0, 0);
187                         StrBufAppendPrintf(Target, " ");
188
189                         /** participant status */
190                         partstat_as_string(buf, p);
191                         StrEscAppend(Target, NULL, buf, 0, 0);
192                 }
193                 StrBufAppendPrintf(Target, "</dd>\n");
194         }
195
196         /* If the component has subcomponents, recurse through them. */
197         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
198              (c != 0);
199              c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
200                 /* Recursively process subcomponent */
201                 cal_process_object(Target, c, recursion_level+1, msgnum, cal_partnum);
202         }
203
204         /* If this is a REQUEST, display conflicts and buttons */
205         if (the_method == ICAL_METHOD_REQUEST) {
206
207                 /* Check for conflicts */
208                 syslog(LOG_DEBUG, "Checking server calendar for conflicts...\n");
209                 serv_printf("ICAL conflicts|%ld|%s|", msgnum, cal_partnum);
210                 serv_getln(buf, sizeof buf);
211                 if (buf[0] == '1') {
212                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
213                                 extract_token(conflict_name, buf, 3, '|', sizeof conflict_name);
214                                 is_update = extract_int(buf, 4);
215
216                                 if (is_update) {
217                                         snprintf(conflict_message, sizeof conflict_message,
218                                                  _("This is an update of '%s' which is already in your calendar."), conflict_name);
219                                 }
220                                 else {
221                                         snprintf(conflict_message, sizeof conflict_message,
222                                                  _("This event would conflict with '%s' which is already in your calendar."), conflict_name);
223                                 }
224
225                                 StrBufAppendPrintf(Target, "<dt>%s",
226                                         (is_update ?
227                                          _("Update:") :
228                                          _("CONFLICT:")
229                                                 )
230                                         );
231                                 StrBufAppendPrintf(Target, "</dt><dd>");
232                                 StrEscAppend(Target, NULL, conflict_message, 0, 0);
233                                 StrBufAppendPrintf(Target, "</dd>\n");
234                         }
235                 }
236                 syslog(LOG_DEBUG, "...done.\n");
237
238                 StrBufAppendPrintf(Target, "</dl>");
239
240                 /* Display the Accept/Decline buttons */
241                 StrBufAppendPrintf(Target, "<p id=\"%s_question\">"
242                         "%s "
243                         "&nbsp;&nbsp;&nbsp;<span class=\"button_link\"> "
244                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Accept');\">%s</a>"
245                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
246                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Tentative');\">%s</a>"
247                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
248                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Decline');\">%s</a>"
249                         "</span></p>\n",
250                         divname,
251                         _("How would you like to respond to this invitation?"),
252                         divname, divname, msgnum, cal_partnum, _("Accept"),
253                         divname, divname, msgnum, cal_partnum, _("Tentative"),
254                         divname, divname, msgnum, cal_partnum, _("Decline")
255                         );
256
257         }
258
259         /* If this is a REPLY, display update button */
260         if (the_method == ICAL_METHOD_REPLY) {
261
262                 /* Display the update buttons */
263                 StrBufAppendPrintf(Target, "<p id=\"%s_question\" >"
264                         "%s "
265                         "&nbsp;&nbsp;&nbsp;<span class=\"button_link\"> "
266                         "<a href=\"javascript:HandleRSVP('%s_question','%s_title','%ld','%s','Update');\">%s</a>"
267                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
268                         "<a href=\"javascript:HandleRSVP('%s_question','%s_title','%ld','%s','Ignore');\">%s</a>"
269                         "</span></p>\n",
270                         divname,
271                         _("Click <i>Update</i> to accept this reply and update your calendar."),
272                         divname, divname, msgnum, cal_partnum, _("Update"),
273                         divname, divname, msgnum, cal_partnum, _("Ignore")
274                         );
275         
276         }
277         
278         /* Trailing HTML for the display of this object */
279         if (recursion_level == 0) {
280                 StrBufAppendPrintf(Target, "<p>&nbsp;</p></div>\n");
281         }
282 }
283
284
285 /*
286  * Deserialize a calendar object in a message so it can be displayed.
287  */
288 void cal_process_attachment(wc_mime_attachment *Mime) 
289 {
290         icalcomponent *cal;
291
292         cal = icalcomponent_new_from_string(ChrPtr(Mime->Data));
293         FlushStrBuf(Mime->Data);
294         if (cal == NULL) {
295                 StrBufAppendPrintf(Mime->Data, _("There was an error parsing this calendar item."));
296                 StrBufAppendPrintf(Mime->Data, "<br>\n");
297                 return;
298         }
299
300         cal_process_object(Mime->Data, cal, 0, Mime->msgnum, ChrPtr(Mime->PartNum));
301
302         /* Free the memory we obtained from libical's constructor */
303         icalcomponent_free(cal);
304 }
305
306
307
308
309 /*
310  * Respond to a meeting request - accept/decline meeting
311  */
312 void respond_to_request(void) 
313 {
314         char buf[1024];
315
316         begin_ajax_response();
317
318         serv_printf("ICAL respond|%s|%s|%s|",
319                 bstr("msgnum"),
320                 bstr("cal_partnum"),
321                 bstr("sc")
322         );
323         serv_getln(buf, sizeof buf);
324
325         if (buf[0] == '2') {
326                 wc_printf("<img src=\"static/webcit_icons/essen/32x32/calendar.png\"><span>");
327                 if (!strcasecmp(bstr("sc"), "accept")) {
328                         wc_printf(_("You have accepted this meeting invitation.  "
329                                 "It has been entered into your calendar.")
330                         );
331                 } else if (!strcasecmp(bstr("sc"), "tentative")) {
332                         wc_printf(_("You have tentatively accepted this meeting invitation.  "
333                                 "It has been 'pencilled in' to your calendar.")
334                         );
335                 } else if (!strcasecmp(bstr("sc"), "decline")) {
336                         wc_printf(_("You have declined this meeting invitation.  "
337                                   "It has <b>not</b> been entered into your calendar.")
338                                 );
339                 }
340                 wc_printf(" ");
341                 wc_printf(_("A reply has been sent to the meeting organizer."));
342                 wc_printf("</span>");
343         } else {
344                 wc_printf("<img align=\"center\" src=\"static/webcit_icons/error.gif\"><span>");
345                 wc_printf("%s\n", &buf[4]);
346                 wc_printf("</span>");
347         }
348
349         end_ajax_response();
350 }
351
352
353
354 /*
355  * Handle an incoming RSVP
356  */
357 void handle_rsvp(void) 
358 {
359         char buf[1024];
360
361         begin_ajax_response();
362
363         serv_printf("ICAL handle_rsvp|%s|%s|%s|",
364                 bstr("msgnum"),
365                 bstr("cal_partnum"),
366                 bstr("sc")
367         );
368         serv_getln(buf, sizeof buf);
369
370         if (buf[0] == '2') {
371                 wc_printf("<img src=\"static/webcit_icons/calendar.png\"><span>");
372                 if (!strcasecmp(bstr("sc"), "update")) {
373                         /// Translators: RSVP aka Répondez s'il-vous-plaît Is the term 
374                         /// that the recipient of an ical-invitation should please 
375                         /// answer this request.
376                         wc_printf(_("Your calendar has been updated to reflect this RSVP."));
377                 } else if (!strcasecmp(bstr("sc"), "ignore")) {
378                         wc_printf(_("You have chosen to ignore this RSVP. "
379                                   "Your calendar has <b>not</b> been updated.")
380                                 );
381                 }
382                 wc_printf("</span>");
383         } else {
384                 wc_printf("<img src=\"static/webcit_icons/error.gif\"><span> %s\n", &buf[4]);
385                 wc_printf("</span>");
386         }
387
388         end_ajax_response();
389 }
390
391
392
393
394 /*
395  * free memory allocated using libical
396  */
397 void delete_cal(void *vCal)
398 {
399         disp_cal *Cal = (disp_cal*) vCal;
400         icalcomponent_free(Cal->cal);
401         free(Cal->from);
402         free(Cal);
403 }
404
405 /*
406  * This is the meat-and-bones of the first part of our two-phase calendar display.
407  * As we encounter calendar items in messages being read from the server, we break out
408  * any iCalendar objects and store them in a hash table.  Later on, the second phase will
409  * use this hash table to render the calendar for display.
410  */
411 void display_individual_cal(icalcomponent *event, long msgnum, char *from, int unread, calview *calv)
412 {
413         icalproperty *ps = NULL;
414         struct icaltimetype dtstart, dtend;
415         struct icaldurationtype dur;
416         wcsession *WCC = WC;
417         disp_cal *Cal;
418         size_t len;
419         time_t final_recurrence = 0;
420         icalcomponent *cptr = NULL;
421
422         /* recur variables */
423         icalproperty *rrule = NULL;
424         struct icalrecurrencetype recur;
425         icalrecur_iterator *ritr = NULL;
426         struct icaltimetype next;
427         int num_recur = 0;
428         int stop_rr = 0;
429
430         /* first and foremost, check for bogosity.  bail if we see no DTSTART property */
431
432         if (icalcomponent_get_first_property(icalcomponent_get_first_component(
433                 event, ICAL_VEVENT_COMPONENT), ICAL_DTSTART_PROPERTY) == NULL)
434         {
435                 return;
436         }
437
438         /* ok, chances are we've got a live one here.  let's try to figure out where it goes. */
439
440         dtstart = icaltime_null_time();
441         dtend = icaltime_null_time();
442         
443         if (WCC->disp_cal_items == NULL) {
444                 WCC->disp_cal_items = NewHash(0, Flathash);
445         }
446
447         /* Note: anything we do here, we also have to do below for the recurrences. */
448         Cal = (disp_cal*) malloc(sizeof(disp_cal));
449         memset(Cal, 0, sizeof(disp_cal));
450         Cal->cal = icalcomponent_new_clone(event);
451
452         /* Dezonify and decapsulate at the very last moment */
453         ical_dezonify(Cal->cal);
454         if (icalcomponent_isa(Cal->cal) != ICAL_VEVENT_COMPONENT) {
455                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
456                 if (cptr) {
457                         cptr = icalcomponent_new_clone(cptr);
458                         icalcomponent_free(Cal->cal);
459                         Cal->cal = cptr;
460                 }
461         }
462
463         Cal->unread = unread;
464         len = strlen(from);
465         Cal->from = (char*)malloc(len+ 1);
466         memcpy(Cal->from, from, len + 1);
467         Cal->cal_msgnum = msgnum;
468
469         /* Precalculate the starting date and time of this event, and store it in our top-level
470          * structure.  Later, when we are rendering the calendar, we can just peek at these values
471          * without having to break apart every calendar item.
472          */
473         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTSTART_PROPERTY);
474         if (ps != NULL) {
475                 dtstart = icalproperty_get_dtstart(ps);
476                 Cal->event_start = icaltime_as_timet(dtstart);
477         }
478
479         /* Do the same for the ending date and time.  It makes the day view much easier to render. */
480         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTEND_PROPERTY);
481         if (ps != NULL) {
482                 dtend = icalproperty_get_dtend(ps);
483                 Cal->event_end = icaltime_as_timet(dtend);
484         }
485
486         /* Store it in the hash list. */
487         /* syslog(LOG_DEBUG, "INITIAL: %s", ctime(&Cal->event_start)); */
488         Put(WCC->disp_cal_items, 
489             (char*) &Cal->event_start,
490             sizeof(Cal->event_start), 
491             Cal, 
492             delete_cal);
493
494         /****************************** handle recurring events ******************************/
495
496         if (icaltime_is_null_time(dtstart)) return;     /* Can't recur without a start time */
497
498         if (!icaltime_is_null_time(dtend)) {            /* Need duration for recurrences */
499                 dur = icaltime_subtract(dtend, dtstart);
500         }
501         else {
502                 dur = icaltime_subtract(dtstart, dtstart);
503         }
504
505         /*
506          * Just let libical iterate the recurrence, and keep looping back to the top of this function,
507          * adding new hash entries that all point back to the same msgnum, until either the iteration
508          * stops or some outer bound is reached.  The display code will automatically do the Right Thing.
509          */
510         cptr = event;
511         if (icalcomponent_isa(cptr) != ICAL_VEVENT_COMPONENT) {
512                 cptr = icalcomponent_get_first_component(cptr, ICAL_VEVENT_COMPONENT);
513         }
514         if (!cptr) return;
515         ps = icalcomponent_get_first_property(cptr, ICAL_DTSTART_PROPERTY);
516         if (ps == NULL) return;
517         dtstart = icalproperty_get_dtstart(ps);
518         rrule = icalcomponent_get_first_property(cptr, ICAL_RRULE_PROPERTY);
519         if (!rrule) return;
520         recur = icalproperty_get_rrule(rrule);
521         ritr = icalrecur_iterator_new(recur, dtstart);
522         if (!ritr) return;
523
524         while (next = icalrecur_iterator_next(ritr), ((!icaltime_is_null_time(next))&&(!stop_rr)) ) {
525                 ++num_recur;
526                 if (num_recur > 1) {            /* Skip the first one.  We already did it at the root. */
527                         icalcomponent *cptr;
528
529                         /* Note: anything we do here, we also have to do above for the root event. */
530                         Cal = (disp_cal*) malloc(sizeof(disp_cal));
531                         memset(Cal, 0, sizeof(disp_cal));
532                         Cal->cal = icalcomponent_new_clone(event);
533                         Cal->unread = unread;
534                         len = strlen(from);
535                         Cal->from = (char*)malloc(len+ 1);
536                         memcpy(Cal->from, from, len + 1);
537                         Cal->cal_msgnum = msgnum;
538
539                         if (icalcomponent_isa(Cal->cal) == ICAL_VEVENT_COMPONENT) {
540                                 cptr = Cal->cal;
541                         }
542                         else {
543                                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
544                         }
545                         if (cptr) {
546
547                                 /* Remove any existing DTSTART properties */
548                                 while ( ps = icalcomponent_get_first_property(cptr, ICAL_DTSTART_PROPERTY),
549                                         ps != NULL
550                                 ) {
551                                         icalcomponent_remove_property(cptr, ps);
552                                 }
553
554                                 /* Add our shiny new DTSTART property from the iteration */
555                                 ps = icalproperty_new_dtstart(next);
556                                 icalcomponent_add_property(cptr, ps);
557                                 Cal->event_start = icaltime_as_timet(next);
558                                 final_recurrence = Cal->event_start;
559
560                                 /* Remove any existing DTEND properties */
561                                 while ( ps = icalcomponent_get_first_property(cptr, ICAL_DTEND_PROPERTY),
562                                         (ps != NULL)
563                                 ) {
564                                         icalcomponent_remove_property(cptr, ps);
565                                 }
566
567                                 /* Add our shiny new DTEND property from the iteration */
568                                 ps = icalproperty_new_dtend(icaltime_add(next, dur));
569                                 icalcomponent_add_property(cptr, ps);
570
571                         }
572
573                         /* Dezonify and decapsulate at the very last moment */
574                         ical_dezonify(Cal->cal);
575                         if (icalcomponent_isa(Cal->cal) != ICAL_VEVENT_COMPONENT) {
576                                 cptr = icalcomponent_get_first_component(Cal->cal, ICAL_VEVENT_COMPONENT);
577                                 if (cptr) {
578                                         cptr = icalcomponent_new_clone(cptr);
579                                         icalcomponent_free(Cal->cal);
580                                         Cal->cal = cptr;
581                                 }
582                         }
583
584                         if (    (Cal->event_start > calv->lower_bound)
585                                 && (Cal->event_start < calv->upper_bound)
586                         ) {
587                                 /* syslog(LOG_DEBUG, "REPEATS: %s", ctime(&Cal->event_start)); */
588                                 Put(WCC->disp_cal_items, 
589                                         (char*) &Cal->event_start,
590                                         sizeof(Cal->event_start), 
591                                         Cal, 
592                                         delete_cal
593                                 );
594                         }
595                         else {
596                                 delete_cal(Cal);
597                         }
598
599                         /* If an upper bound is set, stop when we go out of scope */
600                         if (final_recurrence > calv->upper_bound) stop_rr = 1;
601                 }
602         }
603         icalrecur_iterator_free(ritr);
604         /* syslog(LOG_DEBUG, "Performed %d recurrences; final one is %s", num_recur, ctime(&final_recurrence)); */
605 }
606
607
608
609
610
611
612 void process_ical_object(long msgnum, int unread,
613                          char *from, 
614                          char *FlatIcal, 
615                          icalcomponent_kind which_kind,
616                          IcalCallbackFunc CallBack,
617                          calview *calv
618         ) 
619 {
620         icalcomponent *cal, *c;
621
622         cal = icalcomponent_new_from_string(FlatIcal);
623         if (cal != NULL) {
624
625                 /* A which_kind of (-1) means just load the whole thing */
626                 if (which_kind == (-1)) {
627                         CallBack(cal, msgnum, from, unread, calv);
628                 }
629                 
630                 /* Otherwise recurse and hunt */
631                 else {
632                         
633                         /* Simple components of desired type */
634                         if (icalcomponent_isa(cal) == which_kind) {
635                                 CallBack(cal, msgnum, from, unread, calv);
636                         }
637                         
638                         /* Subcomponents of desired type */
639                         for (c = icalcomponent_get_first_component(cal, which_kind);
640                              (c != 0);
641                              c = icalcomponent_get_next_component(cal, which_kind)) {
642                                 CallBack(c, msgnum, from, unread, calv);
643                         }
644                         
645                 }
646                 
647                 icalcomponent_free(cal);
648         }
649 }
650
651 /*
652  * Code common to all icalendar display handlers.  Given a message number and a MIME
653  * type, we load the message and hunt for that MIME type.  If found, we load
654  * the relevant part, deserialize it into a libical component, filter it for
655  * the requested object type, and feed it to the specified handler.
656  */
657 void load_ical_object(long msgnum, int unread,
658                       icalcomponent_kind which_kind,
659                       IcalCallbackFunc CallBack,
660                       calview *calv,
661                       int RenderAsync
662         ) 
663 {
664         StrBuf *Buf;
665         StrBuf *Data = NULL;
666         const char *bptr;
667         int Done = 0;
668         char from[128] = "";
669         char mime_partnum[256];
670         char mime_filename[256];
671         char mime_content_type[256];
672         char mime_disposition[256];
673         char relevant_partnum[256];
674         char *relevant_source = NULL;
675         int phase = 0;                          /* 0 = citadel headers, 1 = mime headers, 2 = body */
676         char msg4_content_type[256] = "";
677         char msg4_content_encoding[256] = "";
678         int msg4_content_length = 0;
679
680         relevant_partnum[0] = '\0';
681         serv_printf("MSG4 %ld", msgnum);        /* we need the mime headers */
682         Buf = NewStrBuf();
683         StrBuf_ServGetln(Buf);
684         if (GetServerStatus(Buf, NULL) != 1) {
685                 FreeStrBuf (&Buf);
686                 return;
687         }
688         while (!Done && (StrBuf_ServGetln(Buf)>=0)) {
689                 if ( (StrLength(Buf)==3) && 
690                      !strcmp(ChrPtr(Buf), "000")) {
691                         Done = 1;
692                         break;
693                 }
694                 bptr = ChrPtr(Buf);
695                 switch (phase) {
696                 case 0:
697                         if (!strncasecmp(bptr, "part=", 5)) {
698                                 extract_token(mime_filename, &bptr[5], 1, '|', sizeof mime_filename);
699                                 extract_token(mime_partnum, &bptr[5], 2, '|', sizeof mime_partnum);
700                                 extract_token(mime_disposition, &bptr[5], 3, '|', sizeof mime_disposition);
701                                 extract_token(mime_content_type, &bptr[5], 4, '|', sizeof mime_content_type);
702                                 /* do we care? mime_length = */extract_int(&bptr[5], 5);
703
704                                 if (  (!strcasecmp(mime_content_type, "text/calendar"))
705                                       || (!strcasecmp(mime_content_type, "application/ics"))
706                                       || (!strcasecmp(mime_content_type, "text/vtodo"))
707                                       || (!strcasecmp(mime_content_type, "text/todo"))
708                                         ) {
709                                         strcpy(relevant_partnum, mime_partnum);
710                                 }
711                         }
712                         else if (!strncasecmp(bptr, "from=", 4)) {
713                                 extract_token(from, bptr, 1, '=', sizeof(from));
714                         }
715                         else if ((phase == 0) && (!strncasecmp(bptr, "text", 4))) {
716                                 phase = 1;
717                         }
718                 break;
719                 case 1:
720                         if (!IsEmptyStr(bptr)) {
721                                 if (!strncasecmp(bptr, "Content-type: ", 14)) {
722                                         safestrncpy(msg4_content_type, &bptr[14], sizeof msg4_content_type);
723                                         striplt(msg4_content_type);
724                                 }
725                                 else if (!strncasecmp(bptr, "Content-transfer-encoding: ", 27)) {
726                                         safestrncpy(msg4_content_encoding, &bptr[27], sizeof msg4_content_encoding);
727                                         striplt(msg4_content_type);
728                                 }
729                                 else if ((!strncasecmp(bptr, "Content-length: ", 16))) {
730                                         msg4_content_length = atoi(&bptr[16]);
731                                 }
732                                 break;
733                         }
734                         else {
735                                 phase++;
736                                 
737                                 if ((msg4_content_length > 0)
738                                     && ( !strcasecmp(msg4_content_encoding, "7bit"))
739                                     && ((!strcasecmp(mime_content_type, "text/calendar"))
740                                         || (!strcasecmp(mime_content_type, "application/ics"))
741                                         || (!strcasecmp(mime_content_type, "text/vtodo"))
742                                         || (!strcasecmp(mime_content_type, "text/todo"))
743                                             )
744                                         ) 
745                                 {
746                                 }
747                         }
748                 case 2:
749                         if (Data == NULL)
750                                 Data = NewStrBufPlain(NULL, msg4_content_length * 2);
751                         if (msg4_content_length > 0) {
752                                 StrBuf_ServGetBLOBBuffered(Data, msg4_content_length);
753                                 phase ++;
754                         }
755                         else {
756                                 StrBufAppendBuf(Data, Buf, 0);
757                                 StrBufAppendBufPlain(Data, "\r\n", 1, 0);
758                         }
759                 case 3:
760                         StrBufAppendBuf(Data, Buf, 0);
761                 }
762         }
763         FreeStrBuf(&Buf);
764
765         /* If MSG4 didn't give us the part we wanted, but we know that we can find it
766          * as one of the other MIME parts, attempt to load it now.
767          */
768         if ((Data == NULL) && (!IsEmptyStr(relevant_partnum))) {
769                 Data = load_mimepart(msgnum, relevant_partnum);
770         }
771
772         if (Data != NULL) {
773                 relevant_source = (char*) ChrPtr(Data);
774                 process_ical_object(msgnum, unread,
775                                     from, 
776                                     relevant_source, 
777                                     which_kind,
778                                     CallBack,
779                                     calv);
780         }
781         FreeStrBuf (&Data);
782
783         icalmemory_free_ring();
784 }
785
786 /*
787  * Display a calendar item
788  */
789 int calendar_LoadMsgFromServer(SharedMessageStatus *Stat, 
790                                void **ViewSpecific, 
791                                message_summary* Msg, 
792                                int is_new, 
793                                int i)
794 {
795         calview *c = (calview*) *ViewSpecific;
796         load_ical_object(Msg->msgnum, is_new, (-1), display_individual_cal, c, 1);
797         return 0;
798 }
799
800 /*
801  * display the editor component for an event
802  */
803 void display_edit_event(void) {
804         long msgnum = 0L;
805
806         msgnum = lbstr("msgnum");
807         if (msgnum > 0L) {
808                 /* existing event */
809                 load_ical_object(msgnum, 0, ICAL_VEVENT_COMPONENT, display_edit_individual_event, NULL, 0);
810         }
811         else {
812                 /* new event */
813                 display_edit_individual_event(NULL, 0L, "", 0, NULL);
814         }
815 }
816
817 /*
818  * save an edited event
819  */
820 void save_event(void) {
821         long msgnum = 0L;
822
823         msgnum = lbstr("msgnum");
824
825         if (msgnum > 0L) {
826                 load_ical_object(msgnum, 0, (-1), save_individual_event, NULL, 0);
827         }
828         else {
829                 save_individual_event(NULL, 0L, "", 0, NULL);
830         }
831 }
832
833
834
835
836
837 /*
838  * Anonymous request of freebusy data for a user
839  */
840 void do_freebusy(void)
841 {
842         const char *req = ChrPtr(WC->Hdr->HR.ReqLine);
843         char who[SIZ];
844         char buf[SIZ];
845         int len;
846         long lines;
847
848         extract_token(who, req, 0, ' ', sizeof who);
849         if (!strncasecmp(who, "/freebusy/", 10)) {
850                 strcpy(who, &who[10]);
851         }
852         unescape_input(who);
853
854         len = strlen(who);
855         if ( (!strcasecmp(&who[len-4], ".vcf"))
856              || (!strcasecmp(&who[len-4], ".ifb"))
857              || (!strcasecmp(&who[len-4], ".vfb")) ) {
858                 who[len-4] = 0;
859         }
860
861         syslog(LOG_INFO, "freebusy requested for <%s>\n", who);
862         serv_printf("ICAL freebusy|%s", who);
863         serv_getln(buf, sizeof buf);
864
865         if (buf[0] != '1') {
866                 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
867                 output_headers(0, 0, 0, 0, 0, 0);
868                 hprintf("Content-Type: text/plain\r\n");
869                 wc_printf("%s\n", &buf[4]);
870                 end_burst();
871                 return;
872         }
873
874         read_server_text(WC->WBuf, &lines);
875         http_transmit_thing("text/calendar", 0);
876 }
877
878
879
880 int calendar_Cleanup(void **ViewSpecific)
881 {
882         calview *c;
883         
884         c = (calview *) *ViewSpecific;
885
886         wDumpContent(1);
887         free (c);
888         *ViewSpecific = NULL;
889
890         return 0;
891 }
892
893 int __calendar_Cleanup(void **ViewSpecific)
894 {
895         calview *c;
896         
897         c = (calview *) *ViewSpecific;
898
899         free (c);
900         *ViewSpecific = NULL;
901
902         return 0;
903 }
904
905
906 void 
907 InitModule_CALENDAR
908 (void)
909 {
910         RegisterReadLoopHandlerset(
911                 VIEW_CALENDAR,
912                 calendar_GetParamsGetServerCall,
913                 NULL,
914                 NULL,
915                 NULL,
916                 calendar_LoadMsgFromServer,
917                 calendar_RenderView_or_Tail,
918                 calendar_Cleanup,
919                 NULL);
920
921         RegisterReadLoopHandlerset(
922                 VIEW_CALBRIEF,
923                 calendar_GetParamsGetServerCall,
924                 NULL,
925                 NULL,
926                 NULL,
927                 calendar_LoadMsgFromServer,
928                 calendar_RenderView_or_Tail,
929                 calendar_Cleanup,
930                 NULL);
931
932
933
934         RegisterPreference("daystart", _("Calendar day view begins at:"), PRF_INT, NULL);
935         RegisterPreference("dayend", _("Calendar day view ends at:"), PRF_INT, NULL);
936         RegisterPreference("weekstart", _("Week starts on:"), PRF_INT, NULL);
937
938         WebcitAddUrlHandler(HKEY("freebusy"), "", 0, do_freebusy, COOKIEUNNEEDED|ANONYMOUS|FORCE_SESSIONCLOSE);
939         WebcitAddUrlHandler(HKEY("display_edit_task"), "", 0, display_edit_task, 0);
940         WebcitAddUrlHandler(HKEY("display_edit_event"), "", 0, display_edit_event, 0);
941         WebcitAddUrlHandler(HKEY("save_event"), "", 0, save_event, 0);
942         WebcitAddUrlHandler(HKEY("respond_to_request"), "", 0, respond_to_request, 0);
943         WebcitAddUrlHandler(HKEY("handle_rsvp"), "", 0, handle_rsvp, 0);
944 }