]> code.citadel.org Git - citadel.git/blob - citadel/serv_calendar.c
* Began adding a calendaring subcommand to accept a reply to a meeting
[citadel.git] / citadel / serv_calendar.c
1 /* 
2  * $Id$ 
3  *
4  * This module implements iCalendar object processing and the Calendar>
5  * room on a Citadel/UX server.  It handles iCalendar objects using the
6  * iTIP protocol.  See RFCs 2445 and 2446.
7  *
8  */
9
10 #define PRODID "-//Citadel//NONSGML Citadel Calendar//EN"
11
12 #include "sysdep.h"
13 #include <unistd.h>
14 #include <sys/types.h>
15 #include <limits.h>
16 #include <stdio.h>
17 #include <string.h>
18 #ifdef HAVE_STRINGS_H
19 #include <strings.h>
20 #endif
21 #include "serv_calendar.h"
22 #include "citadel.h"
23 #include "server.h"
24 #include "citserver.h"
25 #include "sysdep_decls.h"
26 #include "support.h"
27 #include "config.h"
28 #include "dynloader.h"
29 #include "user_ops.h"
30 #include "room_ops.h"
31 #include "tools.h"
32 #include "msgbase.h"
33 #include "mime_parser.h"
34
35 #ifdef HAVE_ICAL_H
36
37 #include <ical.h>
38
39 struct ical_respond_data {
40         char desired_partnum[SIZ];
41         icalcomponent *cal;
42 };
43
44
45 /*
46  * Write a calendar object into the specified user's calendar room.
47  */
48 void ical_write_to_cal(struct usersupp *u, icalcomponent *cal) {
49         char temp[PATH_MAX];
50         FILE *fp;
51         char *ser;
52
53         strcpy(temp, tmpnam(NULL));
54         ser = icalcomponent_as_ical_string(cal);
55         if (ser == NULL) return;
56
57         /* Make a temp file out of it */
58         fp = fopen(temp, "w");
59         if (fp == NULL) return;
60         fwrite(ser, strlen(ser), 1, fp);
61         fclose(fp);
62
63         /* This handy API function does all the work for us.
64          */
65         CtdlWriteObject(USERCALENDARROOM,       /* which room */
66                         "text/calendar",        /* MIME type */
67                         temp,                   /* temp file */
68                         u,                      /* which user */
69                         0,                      /* not binary */
70                         0,              /* don't delete others of this type */
71                         0);                     /* no flags */
72
73         unlink(temp);
74 }
75
76
77 /*
78  * Add a calendar object to the user's calendar
79  */
80 void ical_add(icalcomponent *cal, int recursion_level) {
81         icalcomponent *c;
82
83         /*
84          * The VEVENT subcomponent is the one we're interested in saving.
85          */
86         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
87         
88                 ical_write_to_cal(&CC->usersupp, cal);
89
90         }
91
92         /* If the component has subcomponents, recurse through them. */
93         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
94             (c != 0);
95             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
96                 /* Recursively process subcomponent */
97                 ical_add(c, recursion_level+1);
98         }
99
100 }
101
102
103
104 /*
105  * Send a reply to a meeting invitation.
106  *
107  * 'request' is the invitation to reply to.
108  * 'action' is the string "accept" or "decline".
109  *
110  * (Sorry about this being more than 80 columns ... there was just
111  * no easy way to break it down sensibly.)
112  */
113 void ical_send_a_reply(icalcomponent *request, char *action) {
114         icalcomponent *the_reply = NULL;
115         icalcomponent *vevent = NULL;
116         icalproperty *attendee = NULL;
117         char attendee_string[SIZ];
118         icalproperty *organizer = NULL;
119         char organizer_string[SIZ];
120         icalproperty *summary = NULL;
121         char summary_string[SIZ];
122         icalproperty *me_attend = NULL;
123         struct recptypes *recp = NULL;
124         icalparameter *partstat = NULL;
125         char *serialized_reply = NULL;
126         char *reply_message_text = NULL;
127         struct CtdlMessage *msg = NULL;
128         struct recptypes *valid = NULL;
129
130         strcpy(organizer_string, "");
131         strcpy(summary_string, "Calendar item");
132
133         if (request == NULL) {
134                 lprintf(3, "ERROR: trying to reply to NULL event?\n");
135                 return;
136         }
137
138         the_reply = icalcomponent_new_clone(request);
139         if (the_reply == NULL) {
140                 lprintf(3, "ERROR: cannot clone request\n");
141                 return;
142         }
143
144         /* Change the method from REQUEST to REPLY */
145         icalcomponent_set_method(the_reply, ICAL_METHOD_REPLY);
146
147         vevent = icalcomponent_get_first_component(the_reply, ICAL_VEVENT_COMPONENT);
148         if (vevent != NULL) {
149                 /* Hunt for attendees, removing ones that aren't us.
150                  * (Actually, remove them all, cloning our own one so we can
151                  * re-insert it later)
152                  */
153                 while (attendee = icalcomponent_get_first_property(vevent,
154                     ICAL_ATTENDEE_PROPERTY), (attendee != NULL)
155                 ) {
156                         if (icalproperty_get_attendee(attendee)) {
157                                 strcpy(attendee_string,
158                                         icalproperty_get_attendee(attendee) );
159                                 if (!strncasecmp(attendee_string, "MAILTO:", 7)) {
160                                         strcpy(attendee_string, &attendee_string[7]);
161                                         striplt(attendee_string);
162                                         recp = validate_recipients(attendee_string);
163                                         if (recp != NULL) {
164                                                 if (!strcasecmp(recp->recp_local, CC->usersupp.fullname)) {
165                                                         if (me_attend) icalproperty_free(me_attend);
166                                                         me_attend = icalproperty_new_clone(attendee);
167                                                 }
168                                                 phree(recp);
169                                         }
170                                 }
171                         }
172                         /* Remove it... */
173                         icalcomponent_remove_property(vevent, attendee);
174                         icalproperty_free(attendee);
175                 }
176
177                 /* We found our own address in the attendee list. */
178                 if (me_attend) {
179                         /* Change the partstat from NEEDS-ACTION to ACCEPT or DECLINE */
180                         icalproperty_remove_parameter(me_attend, ICAL_PARTSTAT_PARAMETER);
181
182                         if (!strcasecmp(action, "accept")) {
183                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_ACCEPTED);
184                         }
185                         else if (!strcasecmp(action, "decline")) {
186                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_DECLINED);
187                         }
188                         else if (!strcasecmp(action, "tentative")) {
189                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_TENTATIVE);
190                         }
191
192                         if (partstat) icalproperty_add_parameter(me_attend, partstat);
193
194                         /* Now insert it back into the vevent. */
195                         icalcomponent_add_property(vevent, me_attend);
196                 }
197
198                 /* Figure out who to send this thing to */
199                 organizer = icalcomponent_get_first_property(vevent, ICAL_ORGANIZER_PROPERTY);
200                 if (organizer != NULL) {
201                         if (icalproperty_get_organizer(organizer)) {
202                                 strcpy(organizer_string,
203                                         icalproperty_get_organizer(organizer) );
204                         }
205                 }
206                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
207                         strcpy(organizer_string, &organizer_string[7]);
208                         striplt(organizer_string);
209                 } else {
210                         strcpy(organizer_string, "");
211                 }
212
213                 /* Extract the summary string -- we'll use it as the
214                  * message subject for the reply
215                  */
216                 summary = icalcomponent_get_first_property(vevent, ICAL_SUMMARY_PROPERTY);
217                 if (summary != NULL) {
218                         if (icalproperty_get_summary(summary)) {
219                                 strcpy(summary_string,
220                                         icalproperty_get_summary(summary) );
221                         }
222                 }
223
224         }
225
226         /* Now generate the reply message and send it out. */
227         serialized_reply = strdoop(icalcomponent_as_ical_string(the_reply));
228         icalcomponent_free(the_reply);  /* don't need this anymore */
229         if (serialized_reply == NULL) return;
230
231         reply_message_text = mallok(strlen(serialized_reply) + SIZ);
232         if (reply_message_text != NULL) {
233                 sprintf(reply_message_text,
234                         "Content-type: text/calendar\r\n\r\n%s\r\n",
235                         serialized_reply
236                 );
237
238                 msg = CtdlMakeMessage(&CC->usersupp, organizer_string,
239                         CC->quickroom.QRname, 0, FMT_RFC822,
240                         "",
241                         summary_string,         /* Use summary for subject */
242                         reply_message_text);
243         
244                 if (msg != NULL) {
245                         valid = validate_recipients(organizer_string);
246                         CtdlSubmitMsg(msg, valid, "");
247                         CtdlFreeMessage(msg);
248                 }
249         }
250         phree(serialized_reply);
251 }
252
253
254
255 /*
256  * Callback function for mime parser that hunts for calendar content types
257  * and turns them into calendar objects
258  */
259 void ical_locate_part(char *name, char *filename, char *partnum, char *disp,
260                 void *content, char *cbtype, size_t length, char *encoding,
261                 void *cbuserdata) {
262
263         struct ical_respond_data *ird = NULL;
264
265         ird = (struct ical_respond_data *) cbuserdata;
266         if (ird->cal != NULL) {
267                 icalcomponent_free(ird->cal);
268                 ird->cal = NULL;
269         }
270         if (strcasecmp(partnum, ird->desired_partnum)) return;
271         ird->cal = icalcomponent_new_from_string(content);
272 }
273
274
275 /*
276  * Respond to a meeting request.
277  */
278 void ical_respond(long msgnum, char *partnum, char *action) {
279         struct CtdlMessage *msg;
280         struct ical_respond_data ird;
281
282         if (
283            (strcasecmp(action, "accept"))
284            && (strcasecmp(action, "decline"))
285         ) {
286                 cprintf("%d Action must be 'accept' or 'decline'\n",
287                         ERROR + ILLEGAL_VALUE
288                 );
289                 return;
290         }
291
292         msg = CtdlFetchMessage(msgnum);
293         if (msg == NULL) {
294                 cprintf("%d Message %ld not found.\n",
295                         ERROR+ILLEGAL_VALUE,
296                         (long)msgnum
297                 );
298                 return;
299         }
300
301         memset(&ird, 0, sizeof ird);
302         strcpy(ird.desired_partnum, partnum);
303         mime_parser(msg->cm_fields['M'],
304                 NULL,
305                 *ical_locate_part,              /* callback function */
306                 NULL, NULL,
307                 (void *) &ird,                  /* user data */
308                 0
309         );
310
311         /* We're done with the incoming message, because we now have a
312          * calendar object in memory.
313          */
314         CtdlFreeMessage(msg);
315
316         /*
317          * Here is the real meat of this function.  Handle the event.
318          */
319         if (ird.cal != NULL) {
320                 /* Save this in the user's calendar if necessary */
321                 if (!strcasecmp(action, "accept")) {
322                         ical_add(ird.cal, 0);
323                 }
324
325                 /* Send a reply if necessary */
326                 if (icalcomponent_get_method(ird.cal) == ICAL_METHOD_REQUEST) {
327                         ical_send_a_reply(ird.cal, action);
328                 }
329
330                 /* Now that we've processed this message, we don't need it
331                  * anymore.  So delete it.
332                  */
333                 CtdlDeleteMessages(CC->quickroom.QRname, msgnum, "");
334
335                 /* Free the memory we allocated and return a response. */
336                 icalcomponent_free(ird.cal);
337                 ird.cal = NULL;
338                 cprintf("%d ok\n", CIT_OK);
339                 return;
340         }
341         else {
342                 cprintf("%d No calendar object found\n", ERROR);
343                 return;
344         }
345
346         /* should never get here */
347 }
348
349
350 /*
351  * Figure out the UID of the calendar event being referred to in a
352  * REPLY object.  This function is recursive.
353  */
354 void ical_learn_uid_of_reply(char *uidbuf, icalcomponent *cal) {
355         icalcomponent *subcomponent;
356         icalproperty *p;
357
358         /* If this object is a REPLY, then extract the UID. */
359         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
360                 p = icalcomponent_get_first_property(cal, ICAL_UID_PROPERTY);
361                 if (p != NULL) {
362                         strcpy(uidbuf, icalproperty_get_comment(p));
363                 }
364         }
365
366         /* Otherwise, recurse through any VEVENT subcomponents.  We do NOT want the
367          * UID of the reply; we want the UID of the invitation being replied to.
368          */
369         for (subcomponent = icalcomponent_get_first_component(cal, ICAL_VEVENT_COMPONENT);
370             subcomponent != NULL;
371             subcomponent = icalcomponent_get_next_component(cal, ICAL_VEVENT_COMPONENT) ) {
372                 ical_learn_uid_of_reply(uidbuf, subcomponent);
373         }
374 }
375
376 void ical_do_FIXME(long msgnum, void *data) {
377         lprintf(9, "Found message <%ld> with correct UID\n", msgnum);
378 }
379
380 /*
381  * Handle an incoming RSVP (object with method==ICAL_METHOD_REPLY) for a
382  * calendar event.  The object has already been deserialized for us; all
383  * we have to do here is hunt for the event in our calendar, merge in the
384  * updated attendee status, and save it again.
385  *
386  * This function returns 0 on success, 1 if the event was not found in the
387  * user's calendar, or 2 if an internal error occurred.
388  */
389 int ical_update_my_calendar_with_reply(icalcomponent *cal) {
390         char uid[SIZ];
391         char hold_rm[ROOMNAMELEN];
392         int replaced_an_event = 0;
393         struct CtdlMessage *template = NULL;
394
395         /* Figure out just what event it is we're dealing with */
396         strcpy(uid, "--==<< InVaLiD uId >>==--");
397         ical_learn_uid_of_reply(uid, cal);
398         lprintf(9, "UID of event being replied to is <%s>\n", uid);
399
400         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
401
402         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
403                 getroom(&CC->quickroom, hold_rm);
404                 lprintf(3, "cannot get user calendar room\n");
405                 return(2);
406         }
407
408         /*
409          * Pound through the user's calendar looking for a message with
410          * the Citadel EUID set to the value we're looking for.  Since
411          * Citadel always sets the message EUID to the vCalendar UID of
412          * the event, this will work.
413          */
414         template = (struct CtdlMessage *)
415                 mallok(sizeof(struct CtdlMessage));
416         memset(template, 0, sizeof(struct CtdlMessage));
417         template->cm_fields['E'] = strdoop(uid);
418         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
419                 template, ical_do_FIXME, NULL);
420         CtdlFreeMessage(template);
421         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
422
423         if (replaced_an_event) {
424                 return(0);
425         }
426         else {
427                 return(1);
428         }
429 }
430
431
432 /*
433  * Handle an incoming RSVP for an event.  (This is the server subcommand part; it
434  * simply extracts the calendar object from the message, deserializes it, and
435  * passes it up to ical_update_my_calendar_with_reply() for processing.
436  */
437 void ical_handle_rsvp(long msgnum, char *partnum, char *action) {
438         struct CtdlMessage *msg;
439         struct ical_respond_data ird;
440         int ret;
441
442         if (
443            (strcasecmp(action, "update"))
444            && (strcasecmp(action, "ignore"))
445         ) {
446                 cprintf("%d Action must be 'update' or 'ignore'\n",
447                         ERROR + ILLEGAL_VALUE
448                 );
449                 return;
450         }
451
452         msg = CtdlFetchMessage(msgnum);
453         if (msg == NULL) {
454                 cprintf("%d Message %ld not found.\n",
455                         ERROR+ILLEGAL_VALUE,
456                         (long)msgnum
457                 );
458                 return;
459         }
460
461         memset(&ird, 0, sizeof ird);
462         strcpy(ird.desired_partnum, partnum);
463         mime_parser(msg->cm_fields['M'],
464                 NULL,
465                 *ical_locate_part,              /* callback function */
466                 NULL, NULL,
467                 (void *) &ird,                  /* user data */
468                 0
469         );
470
471         /* We're done with the incoming message, because we now have a
472          * calendar object in memory.
473          */
474         CtdlFreeMessage(msg);
475
476         /*
477          * Here is the real meat of this function.  Handle the event.
478          */
479         if (ird.cal != NULL) {
480                 /* Update the user's calendar if necessary */
481                 if (!strcasecmp(action, "update")) {
482                         ret = ical_update_my_calendar_with_reply(ird.cal);
483                         if (ret == 0) {
484                                 cprintf("%d Your calendar has been updated with this reply.\n",
485                                         CIT_OK);
486                         }
487                         else if (ret == 1) {
488                                 cprintf("%d This event does not exist in your calendar.\n",
489                                         ERROR + FILE_NOT_FOUND);
490                         }
491                         else {
492                                 cprintf("%d An internal error occurred.\n",
493                                         ERROR + INTERNAL_ERROR);
494                         }
495                 }
496                 else {
497                         cprintf("%d This reply has been ignored.\n", CIT_OK);
498                 }
499
500                 /* Now that we've processed this message, we don't need it
501                  * anymore.  So delete it.  FIXME uncomment this when ready!
502                 CtdlDeleteMessages(CC->quickroom.QRname, msgnum, "");
503                  */
504
505                 /* Free the memory we allocated and return a response. */
506                 icalcomponent_free(ird.cal);
507                 ird.cal = NULL;
508                 return;
509         }
510         else {
511                 cprintf("%d No calendar object found\n", ERROR);
512                 return;
513         }
514
515         /* should never get here */
516 }
517
518
519 /*
520  * Search for a property in both the top level and in a VEVENT subcomponent
521  */
522 icalproperty *ical_ctdl_get_subprop(
523                 icalcomponent *cal,
524                 icalproperty_kind which_prop
525 ) {
526         icalproperty *p;
527         icalcomponent *c;
528
529         p = icalcomponent_get_first_property(cal, which_prop);
530         if (p == NULL) {
531                 c = icalcomponent_get_first_component(cal,
532                                                         ICAL_VEVENT_COMPONENT);
533                 if (c != NULL) {
534                         p = icalcomponent_get_first_property(c, which_prop);
535                 }
536         }
537         return p;
538 }
539
540
541 /*
542  * Check to see if two events overlap.  Returns nonzero if they do.
543  */
544 int ical_ctdl_is_overlap(
545                         struct icaltimetype t1start,
546                         struct icaltimetype t1end,
547                         struct icaltimetype t2start,
548                         struct icaltimetype t2end
549 ) {
550
551         if (icaltime_is_null_time(t1start)) return(0);
552         if (icaltime_is_null_time(t2start)) return(0);
553
554         /* First, check for all-day events */
555         if (t1start.is_date) {
556                 if (!icaltime_compare_date_only(t1start, t2start)) {
557                         return(1);
558                 }
559                 if (!icaltime_is_null_time(t2end)) {
560                         if (!icaltime_compare_date_only(t1start, t2end)) {
561                                 return(1);
562                         }
563                 }
564         }
565
566         if (t2start.is_date) {
567                 if (!icaltime_compare_date_only(t2start, t1start)) {
568                         return(1);
569                 }
570                 if (!icaltime_is_null_time(t1end)) {
571                         if (!icaltime_compare_date_only(t2start, t1end)) {
572                                 return(1);
573                         }
574                 }
575         }
576
577         /* Now check for overlaps using date *and* time. */
578
579         /* First, bail out if either event 1 or event 2 is missing end time. */
580         if (icaltime_is_null_time(t1end)) return(0);
581         if (icaltime_is_null_time(t2end)) return(0);
582
583         /* If event 1 ends before event 2 starts, we're in the clear. */
584         if (icaltime_compare(t1end, t2start) <= 0) return(0);
585
586         /* If event 2 ends before event 1 starts, we're also ok. */
587         if (icaltime_compare(t2end, t1start) <= 0) return(0);
588
589         /* Otherwise, they overlap. */
590         return(1);
591 }
592
593
594
595 /*
596  * Backend for ical_hunt_for_conflicts()
597  */
598 void ical_hunt_for_conflicts_backend(long msgnum, void *data) {
599         icalcomponent *cal;
600         struct CtdlMessage *msg;
601         struct ical_respond_data ird;
602         struct icaltimetype t1start, t1end, t2start, t2end;
603         icalproperty *p;
604         char conflict_event_uid[SIZ];
605         char conflict_event_summary[SIZ];
606         char compare_uid[SIZ];
607
608         cal = (icalcomponent *)data;
609         strcpy(compare_uid, "");
610         strcpy(conflict_event_uid, "");
611         strcpy(conflict_event_summary, "");
612
613         msg = CtdlFetchMessage(msgnum);
614         if (msg == NULL) return;
615         memset(&ird, 0, sizeof ird);
616         strcpy(ird.desired_partnum, "1");       /* hopefully it's always 1 */
617         mime_parser(msg->cm_fields['M'],
618                 NULL,
619                 *ical_locate_part,              /* callback function */
620                 NULL, NULL,
621                 (void *) &ird,                  /* user data */
622                 0
623         );
624         CtdlFreeMessage(msg);
625
626         if (ird.cal == NULL) return;
627
628         t1start = icaltime_null_time();
629         t1end = icaltime_null_time();
630         t2start = icaltime_null_time();
631         t1end = icaltime_null_time();
632
633         /* Now compare cal to ird.cal */
634         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTSTART_PROPERTY);
635         if (p == NULL) return;
636         if (p != NULL) t2start = icalproperty_get_dtstart(p);
637         
638         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTEND_PROPERTY);
639         if (p != NULL) t2end = icalproperty_get_dtend(p);
640
641         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
642         if (p == NULL) return;
643         if (p != NULL) t1start = icalproperty_get_dtstart(p);
644         
645         p = ical_ctdl_get_subprop(cal, ICAL_DTEND_PROPERTY);
646         if (p != NULL) t1end = icalproperty_get_dtend(p);
647         
648         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
649         if (p != NULL) {
650                 strcpy(compare_uid, icalproperty_get_comment(p));
651         }
652
653         p = ical_ctdl_get_subprop(ird.cal, ICAL_UID_PROPERTY);
654         if (p != NULL) {
655                 strcpy(conflict_event_uid, icalproperty_get_comment(p));
656         }
657
658         p = ical_ctdl_get_subprop(ird.cal, ICAL_SUMMARY_PROPERTY);
659         if (p != NULL) {
660                 strcpy(conflict_event_summary, icalproperty_get_comment(p));
661         }
662
663
664         icalcomponent_free(ird.cal);
665
666         if (ical_ctdl_is_overlap(t1start, t1end, t2start, t2end)) {
667                 cprintf("%ld||%s|%s|%d|\n",
668                         msgnum,
669                         conflict_event_uid,
670                         conflict_event_summary,
671                         (       ((strlen(compare_uid)>0)
672                                 &&(!strcasecmp(compare_uid,
673                                 conflict_event_uid))) ? 1 : 0
674                         )
675                 );
676         }
677 }
678
679
680
681 /* 
682  * Phase 2 of "hunt for conflicts" operation.
683  * At this point we have a calendar object which represents the VEVENT that
684  * we're considering adding to the calendar.  Now hunt through the user's
685  * calendar room, and output zero or more existing VEVENTs which conflict
686  * with this one.
687  */
688 void ical_hunt_for_conflicts(icalcomponent *cal) {
689         char hold_rm[ROOMNAMELEN];
690
691         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
692
693         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
694                 getroom(&CC->quickroom, hold_rm);
695                 cprintf("%d You do not have a calendar.\n", ERROR);
696                 return;
697         }
698
699         cprintf("%d Conflicting events:\n", LISTING_FOLLOWS);
700
701         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
702                 NULL,
703                 ical_hunt_for_conflicts_backend,
704                 (void *) cal
705         );
706
707         cprintf("000\n");
708         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
709
710 }
711
712
713
714 /*
715  * Hunt for conflicts (Phase 1 -- retrieve the object and call Phase 2)
716  */
717 void ical_conflicts(long msgnum, char *partnum) {
718         struct CtdlMessage *msg;
719         struct ical_respond_data ird;
720
721         msg = CtdlFetchMessage(msgnum);
722         if (msg == NULL) {
723                 cprintf("%d Message %ld not found.\n",
724                         ERROR+ILLEGAL_VALUE,
725                         (long)msgnum
726                 );
727                 return;
728         }
729
730         memset(&ird, 0, sizeof ird);
731         strcpy(ird.desired_partnum, partnum);
732         mime_parser(msg->cm_fields['M'],
733                 NULL,
734                 *ical_locate_part,              /* callback function */
735                 NULL, NULL,
736                 (void *) &ird,                  /* user data */
737                 0
738         );
739
740         CtdlFreeMessage(msg);
741
742         if (ird.cal != NULL) {
743                 ical_hunt_for_conflicts(ird.cal);
744                 icalcomponent_free(ird.cal);
745                 return;
746         }
747         else {
748                 cprintf("%d No calendar object found\n", ERROR);
749                 return;
750         }
751
752         /* should never get here */
753 }
754
755
756
757
758 /*
759  * All Citadel calendar commands from the client come through here.
760  */
761 void cmd_ical(char *argbuf)
762 {
763         char subcmd[SIZ];
764         long msgnum;
765         char partnum[SIZ];
766         char action[SIZ];
767
768         if (CtdlAccessCheck(ac_logged_in)) return;
769
770         extract(subcmd, argbuf, 0);
771
772         if (!strcmp(subcmd, "test")) {
773                 cprintf("%d This server supports calendaring\n", CIT_OK);
774                 return;
775         }
776
777         else if (!strcmp(subcmd, "respond")) {
778                 msgnum = extract_long(argbuf, 1);
779                 extract(partnum, argbuf, 2);
780                 extract(action, argbuf, 3);
781                 ical_respond(msgnum, partnum, action);
782         }
783
784         else if (!strcmp(subcmd, "handle_rsvp")) {
785                 msgnum = extract_long(argbuf, 1);
786                 extract(partnum, argbuf, 2);
787                 extract(action, argbuf, 3);
788                 ical_handle_rsvp(msgnum, partnum, action);
789         }
790
791         else if (!strcmp(subcmd, "conflicts")) {
792                 msgnum = extract_long(argbuf, 1);
793                 extract(partnum, argbuf, 2);
794                 ical_conflicts(msgnum, partnum);
795         }
796
797         else {
798                 cprintf("%d Invalid subcommand\n", ERROR+CMD_NOT_SUPPORTED);
799                 return;
800         }
801
802         /* should never get here */
803 }
804
805
806
807 /*
808  * We don't know if the calendar room exists so we just create it at login
809  */
810 void ical_create_room(void)
811 {
812         struct quickroom qr;
813         struct visit vbuf;
814
815         /* Create the calendar room if it doesn't already exist */
816         create_room(USERCALENDARROOM, 4, "", 0, 1, 0);
817
818         /* Set expiration policy to manual; otherwise objects will be lost! */
819         if (lgetroom(&qr, USERCALENDARROOM)) {
820                 lprintf(3, "Couldn't get the user calendar room!\n");
821                 return;
822         }
823         qr.QRep.expire_mode = EXPIRE_MANUAL;
824         lputroom(&qr);
825
826         /* Set the view to a calendar view */
827         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
828         vbuf.v_view = 3;        /* 3 = calendar */
829         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
830
831         /* Create the tasks list room if it doesn't already exist */
832         create_room(USERTASKSROOM, 4, "", 0, 1, 0);
833
834         /* Set expiration policy to manual; otherwise objects will be lost! */
835         if (lgetroom(&qr, USERTASKSROOM)) {
836                 lprintf(3, "Couldn't get the user calendar room!\n");
837                 return;
838         }
839         qr.QRep.expire_mode = EXPIRE_MANUAL;
840         lputroom(&qr);
841
842         /* Set the view to a task list view */
843         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
844         vbuf.v_view = 4;        /* 4 = tasks */
845         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
846
847         return;
848 }
849
850
851 /*
852  * ical_send_out_invitations() is called by ical_saving_vevent() when it
853  * finds a VEVENT.   FIXME ... finish implementing.
854  */
855 void ical_send_out_invitations(icalcomponent *cal) {
856         icalcomponent *the_request = NULL;
857         char *serialized_request = NULL;
858         char *request_message_text = NULL;
859         struct CtdlMessage *msg = NULL;
860         struct recptypes *valid = NULL;
861         char attendees_string[SIZ];
862         char this_attendee[SIZ];
863         icalproperty *attendee = NULL;
864         char summary_string[SIZ];
865         icalproperty *summary = NULL;
866         icalcomponent *encaps = NULL;
867
868         if (cal == NULL) {
869                 lprintf(3, "ERROR: trying to reply to NULL event?\n");
870                 return;
871         }
872
873         /* Clone the event */
874         the_request = icalcomponent_new_clone(cal);
875         if (the_request == NULL) {
876                 lprintf(3, "ERROR: cannot clone calendar object\n");
877                 return;
878         }
879
880         /* Extract the summary string -- we'll use it as the
881          * message subject for the request
882          */
883         strcpy(summary_string, "Meeting request");
884         summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
885         if (summary != NULL) {
886                 if (icalproperty_get_summary(summary)) {
887                         strcpy(summary_string,
888                                 icalproperty_get_summary(summary) );
889                 }
890         }
891
892         /* Determine who the recipients of this message are (the attendees) */
893         strcpy(attendees_string, "");
894         for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
895                 if (icalproperty_get_attendee(attendee)) {
896                         strcpy(this_attendee, icalproperty_get_attendee(attendee) );
897                         if (!strncasecmp(this_attendee, "MAILTO:", 7)) {
898                                 strcpy(this_attendee, &this_attendee[7]);
899                                 snprintf(&attendees_string[strlen(attendees_string)],
900                                         sizeof(attendees_string) - strlen(attendees_string),
901                                         "%s, ",
902                                         this_attendee
903                                 );
904                         }
905                 }
906         }
907
908         lprintf(9, "attendees_string: <%s>\n", attendees_string);
909
910         /* Encapsulate the VEVENT component into a complete VCALENDAR */
911         encaps = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
912         if (encaps == NULL) {
913                 lprintf(3, "Error at %s:%d - could not allocate component!\n",
914                         __FILE__, __LINE__);
915                 icalcomponent_free(the_request);
916                 return;
917         }
918
919         /* Set the Product ID */
920         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
921
922         /* Set the Version Number */
923         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
924
925         /* Set the method to REQUEST */
926         icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
927
928         /* FIXME: here we need to insert a VTIMEZONE object. */
929
930         /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
931          * are responsible for "the_request"'s memory -- it will be freed
932          * when we free "encaps".
933          */
934         icalcomponent_add_component(encaps, the_request);
935
936         /* Serialize it */
937         serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
938         icalcomponent_free(encaps);     /* Don't need this anymore. */
939         if (serialized_request == NULL) return;
940
941         request_message_text = mallok(strlen(serialized_request) + SIZ);
942         if (request_message_text != NULL) {
943                 sprintf(request_message_text,
944                         "Content-type: text/calendar\r\n\r\n%s\r\n",
945                         serialized_request
946                 );
947
948                 msg = CtdlMakeMessage(&CC->usersupp,
949                         "",                     /* No single recipient here */
950                         CC->quickroom.QRname, 0, FMT_RFC822,
951                         "",
952                         summary_string,         /* Use summary for subject */
953                         request_message_text);
954         
955                 if (msg != NULL) {
956                         valid = validate_recipients(attendees_string);
957                         CtdlSubmitMsg(msg, valid, "");
958                         CtdlFreeMessage(msg);
959                 }
960         }
961         phree(serialized_request);
962 }
963
964
965 /*
966  * When a calendar object is being saved, determine whether it's a VEVENT
967  * and the user saving it is the organizer.  If so, send out invitations
968  * to any listed attendees.
969  *
970  */
971 void ical_saving_vevent(icalcomponent *cal) {
972         icalcomponent *c;
973         icalproperty *organizer = NULL;
974         char organizer_string[SIZ];
975
976         strcpy(organizer_string, "");
977         /*
978          * The VEVENT subcomponent is the one we're interested in.
979          * Send out invitations if, and only if, this user is the Organizer.
980          */
981         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
982                 organizer = icalcomponent_get_first_property(cal,
983                                                 ICAL_ORGANIZER_PROPERTY);
984                 if (organizer != NULL) {
985                         if (icalproperty_get_organizer(organizer)) {
986                                 strcpy(organizer_string,
987                                         icalproperty_get_organizer(organizer));
988                         }
989                 }
990                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
991                         strcpy(organizer_string, &organizer_string[7]);
992                         striplt(organizer_string);
993                         /*
994                          * If the user saving the event is listed as the
995                          * organizer, then send out invitations.
996                          */
997                         if (CtdlIsMe(organizer_string)) {
998                                 ical_send_out_invitations(cal);
999                         }
1000                 }
1001         }
1002
1003         /* If the component has subcomponents, recurse through them. */
1004         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
1005             (c != NULL);
1006             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
1007                 /* Recursively process subcomponent */
1008                 ical_saving_vevent(c);
1009         }
1010
1011 }
1012
1013
1014
1015 /*
1016  * Back end for ical_obj_beforesave()
1017  * This hunts for the UID of the calendar event.
1018  */
1019 void ical_ctdl_set_extended_msgid(char *name, char *filename, char *partnum,
1020                 char *disp, void *content, char *cbtype, size_t length,
1021                 char *encoding, void *cbuserdata)
1022 {
1023         icalcomponent *cal;
1024         icalproperty *p;
1025
1026         /* If this is a text/calendar object, hunt for the UID and drop it in
1027          * the "user data" pointer for the MIME parser.  When
1028          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1029          * to that string.
1030          */
1031         if (!strcasecmp(cbtype, "text/calendar")) {
1032                 cal = icalcomponent_new_from_string(content);
1033                 if (cal != NULL) {
1034                         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
1035                         if (p != NULL) {
1036                                 strcpy((char *)cbuserdata,
1037                                         icalproperty_get_comment(p)
1038                                 );
1039                         }
1040                         icalcomponent_free(cal);
1041                 }
1042         }
1043 }
1044
1045
1046
1047
1048
1049 /*
1050  * See if we need to prevent the object from being saved (we don't allow
1051  * MIME types other than text/calendar in the Calendar> room).  Also, when
1052  * saving an event to the calendar, set the message's Citadel extended message
1053  * ID to the UID of the object.  This causes our replication checker to
1054  * automatically delete any existing instances of the same object.  (Isn't
1055  * that cool?)
1056  */
1057 int ical_obj_beforesave(struct CtdlMessage *msg)
1058 {
1059         char roomname[ROOMNAMELEN];
1060         char *p;
1061         int a;
1062         char eidbuf[SIZ];
1063
1064         /*
1065          * Only messages with content-type text/calendar
1066          * may be saved to Calendar>.  If the message is bound for
1067          * Calendar> but doesn't have this content-type, throw an error
1068          * so that the message may not be posted.
1069          */
1070
1071         /* First determine if this is our room */
1072         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1073         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1074                 return 0;       /* It's not the Calendar room. */
1075         }
1076
1077         /* Then determine content-type of the message */
1078         
1079         /* It must be an RFC822 message! */
1080         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1081         if (msg->cm_format_type != 4)
1082                 return 1;       /* You tried to save a non-RFC822 message! */
1083         
1084         /* Find the Content-Type: header */
1085         p = msg->cm_fields['M'];
1086         a = strlen(p);
1087         while (--a > 0) {
1088                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1089                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1090                                 strcpy(eidbuf, "");
1091                                 mime_parser(msg->cm_fields['M'],
1092                                         NULL,
1093                                         *ical_ctdl_set_extended_msgid,
1094                                         NULL, NULL,
1095                                         (void *)eidbuf,
1096                                         0
1097                                 );
1098                                 if (strlen(eidbuf) > 0) {
1099                                         if (msg->cm_fields['E'] != NULL) {
1100                                                 phree(msg->cm_fields['E']);
1101                                         }
1102                                         msg->cm_fields['E'] = strdoop(eidbuf);
1103                                 }
1104                                 return 0;
1105                         }
1106                         else {
1107                                 return 1;
1108                         }
1109                 }
1110                 p++;
1111         }
1112         
1113         /* Oops!  No Content-Type in this message!  How'd that happen? */
1114         lprintf(7, "RFC822 message with no Content-Type header!\n");
1115         return 1;
1116 }
1117
1118
1119 /*
1120  * Things we need to do after saving a calendar event.
1121  */
1122 void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
1123                 char *disp, void *content, char *cbtype, size_t length,
1124                 char *encoding, void *cbuserdata)
1125 {
1126         icalcomponent *cal;
1127
1128         /* If this is a text/calendar object, hunt for the UID and drop it in
1129          * the "user data" pointer for the MIME parser.  When
1130          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1131          * to that string.
1132          */
1133         if (!strcasecmp(cbtype, "text/calendar")) {
1134                 cal = icalcomponent_new_from_string(content);
1135                 if (cal != NULL) {
1136                         ical_saving_vevent(cal);
1137                         icalcomponent_free(cal);
1138                 }
1139         }
1140 }
1141
1142
1143 /* 
1144  * Things we need to do after saving a calendar event.
1145  */
1146 int ical_obj_aftersave(struct CtdlMessage *msg)
1147 {
1148         char roomname[ROOMNAMELEN];
1149         char *p;
1150         int a;
1151
1152         /*
1153          * If this isn't the Calendar> room, no further action is necessary.
1154          */
1155
1156         /* First determine if this is our room */
1157         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1158         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1159                 return 0;       /* It's not the Calendar room. */
1160         }
1161
1162         /* Then determine content-type of the message */
1163         
1164         /* It must be an RFC822 message! */
1165         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1166         if (msg->cm_format_type != 4) return(1);
1167         
1168         /* Find the Content-Type: header */
1169         p = msg->cm_fields['M'];
1170         a = strlen(p);
1171         while (--a > 0) {
1172                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1173                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1174                                 mime_parser(msg->cm_fields['M'],
1175                                         NULL,
1176                                         *ical_obj_aftersave_backend,
1177                                         NULL, NULL,
1178                                         NULL,
1179                                         0
1180                                 );
1181                                 return 0;
1182                         }
1183                         else {
1184                                 return 1;
1185                         }
1186                 }
1187                 p++;
1188         }
1189         
1190         /* Oops!  No Content-Type in this message!  How'd that happen? */
1191         lprintf(7, "RFC822 message with no Content-Type header!\n");
1192         return 1;
1193 }
1194
1195
1196 #endif  /* HAVE_ICAL_H */
1197
1198 /*
1199  * Register this module with the Citadel server.
1200  */
1201 char *Dynamic_Module_Init(void)
1202 {
1203 #ifdef HAVE_ICAL_H
1204         CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
1205         CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
1206         CtdlRegisterSessionHook(ical_create_room, EVT_LOGIN);
1207         CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCal commands");
1208 #endif
1209         return "$Id$";
1210 }