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