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