]> code.citadel.org Git - citadel.git/blob - citadel/serv_calendar.c
b175fd9195d21f0bea7124cdda89ef8ef35c1d48
[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
377 /*
378  * ical_update_my_calendar_with_reply() refers to this callback function; when we
379  * locate the message containing the calendar event we're replying to, this function
380  * gets called.  It basically just sticks the message number in a supplied buffer.
381  */
382 void ical_hunt_for_event_to_update(long msgnum, void *data) {
383         long *msgnumptr;
384
385         msgnumptr = (long *) data;
386         *msgnumptr = msgnum;
387 }
388
389
390 struct original_event_container {
391         icalcomponent *c;
392 };
393
394 /*
395  * Callback function for mime parser that hunts for calendar content types
396  * and turns them into calendar objects (called by ical_update_my_calendar_with_reply()
397  * to fetch the object being updated)
398  */
399 void ical_locate_original_event(char *name, char *filename, char *partnum, char *disp,
400                 void *content, char *cbtype, size_t length, char *encoding,
401                 void *cbuserdata) {
402
403         struct original_event_container *oec = NULL;
404
405         if (strcasecmp(cbtype, "text/calendar")) {
406                 return;
407         }
408         oec = (struct original_event_container *) cbuserdata;
409         if (oec->c != NULL) {
410                 icalcomponent_free(oec->c);
411         }
412         oec->c = icalcomponent_new_from_string(content);
413 }
414
415
416 /*
417  * Handle an incoming RSVP (object with method==ICAL_METHOD_REPLY) for a
418  * calendar event.  The object has already been deserialized for us; all
419  * we have to do here is hunt for the event in our calendar, merge in the
420  * updated attendee status, and save it again.
421  *
422  * This function returns 0 on success, 1 if the event was not found in the
423  * user's calendar, or 2 if an internal error occurred.
424  */
425 int ical_update_my_calendar_with_reply(icalcomponent *cal) {
426         char uid[SIZ];
427         char hold_rm[ROOMNAMELEN];
428         long msgnum_being_replaced = 0;
429         struct CtdlMessage *template = NULL;
430         struct CtdlMessage *msg;
431         struct original_event_container oec;
432         icalcomponent *original_event;
433
434         /* Figure out just what event it is we're dealing with */
435         strcpy(uid, "--==<< InVaLiD uId >>==--");
436         ical_learn_uid_of_reply(uid, cal);
437         lprintf(9, "UID of event being replied to is <%s>\n", uid);
438
439         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
440
441         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
442                 getroom(&CC->quickroom, hold_rm);
443                 lprintf(3, "cannot get user calendar room\n");
444                 return(2);
445         }
446
447         /*
448          * Pound through the user's calendar looking for a message with
449          * the Citadel EUID set to the value we're looking for.  Since
450          * Citadel always sets the message EUID to the vCalendar UID of
451          * the event, this will work.
452          */
453         template = (struct CtdlMessage *)
454                 mallok(sizeof(struct CtdlMessage));
455         memset(template, 0, sizeof(struct CtdlMessage));
456         template->cm_fields['E'] = strdoop(uid);
457         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
458                 template, ical_hunt_for_event_to_update, &msgnum_being_replaced);
459         CtdlFreeMessage(template);
460         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
461
462         lprintf(9, "msgnum_being_replaced == %ld\n", msgnum_being_replaced);
463         if (msgnum_being_replaced == 0) {
464                 return(1);                      /* no calendar event found */
465         }
466
467         /* Now we know the ID of the message containing the event being updated.
468          * We don't actually have to delete it; that'll get taken care of by the
469          * server when we save another event with the same UID.  This just gives
470          * us the ability to load the event into memory so we can diddle the
471          * attendees.
472          */
473         msg = CtdlFetchMessage(msgnum_being_replaced);
474         if (msg == NULL) {
475                 return(2);                      /* internal error */
476         }
477         oec.c = NULL;
478         mime_parser(msg->cm_fields['M'],
479                 NULL,
480                 *ical_locate_original_event,    /* callback function */
481                 NULL, NULL,
482                 &oec,                           /* user data */
483                 0
484         );
485         CtdlFreeMessage(msg);
486
487         original_event = oec.c;
488         if (original_event == NULL) {
489                 lprintf(3, "ERROR: Original_component is NULL.\n");
490                 return(1);
491         }
492
493         /* FIXME finish this */
494         /* merge "cal" into "original_event" */
495         /* reserialize "original_event" and save to disk */
496
497         icalcomponent_free(original_event);
498         return(0);
499 }
500
501
502 /*
503  * Handle an incoming RSVP for an event.  (This is the server subcommand part; it
504  * simply extracts the calendar object from the message, deserializes it, and
505  * passes it up to ical_update_my_calendar_with_reply() for processing.
506  */
507 void ical_handle_rsvp(long msgnum, char *partnum, char *action) {
508         struct CtdlMessage *msg;
509         struct ical_respond_data ird;
510         int ret;
511
512         if (
513            (strcasecmp(action, "update"))
514            && (strcasecmp(action, "ignore"))
515         ) {
516                 cprintf("%d Action must be 'update' or 'ignore'\n",
517                         ERROR + ILLEGAL_VALUE
518                 );
519                 return;
520         }
521
522         msg = CtdlFetchMessage(msgnum);
523         if (msg == NULL) {
524                 cprintf("%d Message %ld not found.\n",
525                         ERROR+ILLEGAL_VALUE,
526                         (long)msgnum
527                 );
528                 return;
529         }
530
531         memset(&ird, 0, sizeof ird);
532         strcpy(ird.desired_partnum, partnum);
533         mime_parser(msg->cm_fields['M'],
534                 NULL,
535                 *ical_locate_part,              /* callback function */
536                 NULL, NULL,
537                 (void *) &ird,                  /* user data */
538                 0
539         );
540
541         /* We're done with the incoming message, because we now have a
542          * calendar object in memory.
543          */
544         CtdlFreeMessage(msg);
545
546         /*
547          * Here is the real meat of this function.  Handle the event.
548          */
549         if (ird.cal != NULL) {
550                 /* Update the user's calendar if necessary */
551                 if (!strcasecmp(action, "update")) {
552                         ret = ical_update_my_calendar_with_reply(ird.cal);
553                         if (ret == 0) {
554                                 cprintf("%d Your calendar has been updated with this reply.\n",
555                                         CIT_OK);
556                         }
557                         else if (ret == 1) {
558                                 cprintf("%d This event does not exist in your calendar.\n",
559                                         ERROR + FILE_NOT_FOUND);
560                         }
561                         else {
562                                 cprintf("%d An internal error occurred.\n",
563                                         ERROR + INTERNAL_ERROR);
564                         }
565                 }
566                 else {
567                         cprintf("%d This reply has been ignored.\n", CIT_OK);
568                 }
569
570                 /* Now that we've processed this message, we don't need it
571                  * anymore.  So delete it.  FIXME uncomment this when ready!
572                 CtdlDeleteMessages(CC->quickroom.QRname, msgnum, "");
573                  */
574
575                 /* Free the memory we allocated and return a response. */
576                 icalcomponent_free(ird.cal);
577                 ird.cal = NULL;
578                 return;
579         }
580         else {
581                 cprintf("%d No calendar object found\n", ERROR);
582                 return;
583         }
584
585         /* should never get here */
586 }
587
588
589 /*
590  * Search for a property in both the top level and in a VEVENT subcomponent
591  */
592 icalproperty *ical_ctdl_get_subprop(
593                 icalcomponent *cal,
594                 icalproperty_kind which_prop
595 ) {
596         icalproperty *p;
597         icalcomponent *c;
598
599         p = icalcomponent_get_first_property(cal, which_prop);
600         if (p == NULL) {
601                 c = icalcomponent_get_first_component(cal,
602                                                         ICAL_VEVENT_COMPONENT);
603                 if (c != NULL) {
604                         p = icalcomponent_get_first_property(c, which_prop);
605                 }
606         }
607         return p;
608 }
609
610
611 /*
612  * Check to see if two events overlap.  Returns nonzero if they do.
613  */
614 int ical_ctdl_is_overlap(
615                         struct icaltimetype t1start,
616                         struct icaltimetype t1end,
617                         struct icaltimetype t2start,
618                         struct icaltimetype t2end
619 ) {
620
621         if (icaltime_is_null_time(t1start)) return(0);
622         if (icaltime_is_null_time(t2start)) return(0);
623
624         /* First, check for all-day events */
625         if (t1start.is_date) {
626                 if (!icaltime_compare_date_only(t1start, t2start)) {
627                         return(1);
628                 }
629                 if (!icaltime_is_null_time(t2end)) {
630                         if (!icaltime_compare_date_only(t1start, t2end)) {
631                                 return(1);
632                         }
633                 }
634         }
635
636         if (t2start.is_date) {
637                 if (!icaltime_compare_date_only(t2start, t1start)) {
638                         return(1);
639                 }
640                 if (!icaltime_is_null_time(t1end)) {
641                         if (!icaltime_compare_date_only(t2start, t1end)) {
642                                 return(1);
643                         }
644                 }
645         }
646
647         /* Now check for overlaps using date *and* time. */
648
649         /* First, bail out if either event 1 or event 2 is missing end time. */
650         if (icaltime_is_null_time(t1end)) return(0);
651         if (icaltime_is_null_time(t2end)) return(0);
652
653         /* If event 1 ends before event 2 starts, we're in the clear. */
654         if (icaltime_compare(t1end, t2start) <= 0) return(0);
655
656         /* If event 2 ends before event 1 starts, we're also ok. */
657         if (icaltime_compare(t2end, t1start) <= 0) return(0);
658
659         /* Otherwise, they overlap. */
660         return(1);
661 }
662
663
664
665 /*
666  * Backend for ical_hunt_for_conflicts()
667  */
668 void ical_hunt_for_conflicts_backend(long msgnum, void *data) {
669         icalcomponent *cal;
670         struct CtdlMessage *msg;
671         struct ical_respond_data ird;
672         struct icaltimetype t1start, t1end, t2start, t2end;
673         icalproperty *p;
674         char conflict_event_uid[SIZ];
675         char conflict_event_summary[SIZ];
676         char compare_uid[SIZ];
677
678         cal = (icalcomponent *)data;
679         strcpy(compare_uid, "");
680         strcpy(conflict_event_uid, "");
681         strcpy(conflict_event_summary, "");
682
683         msg = CtdlFetchMessage(msgnum);
684         if (msg == NULL) return;
685         memset(&ird, 0, sizeof ird);
686         strcpy(ird.desired_partnum, "1");       /* hopefully it's always 1 */
687         mime_parser(msg->cm_fields['M'],
688                 NULL,
689                 *ical_locate_part,              /* callback function */
690                 NULL, NULL,
691                 (void *) &ird,                  /* user data */
692                 0
693         );
694         CtdlFreeMessage(msg);
695
696         if (ird.cal == NULL) return;
697
698         t1start = icaltime_null_time();
699         t1end = icaltime_null_time();
700         t2start = icaltime_null_time();
701         t1end = icaltime_null_time();
702
703         /* Now compare cal to ird.cal */
704         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTSTART_PROPERTY);
705         if (p == NULL) return;
706         if (p != NULL) t2start = icalproperty_get_dtstart(p);
707         
708         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTEND_PROPERTY);
709         if (p != NULL) t2end = icalproperty_get_dtend(p);
710
711         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
712         if (p == NULL) return;
713         if (p != NULL) t1start = icalproperty_get_dtstart(p);
714         
715         p = ical_ctdl_get_subprop(cal, ICAL_DTEND_PROPERTY);
716         if (p != NULL) t1end = icalproperty_get_dtend(p);
717         
718         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
719         if (p != NULL) {
720                 strcpy(compare_uid, icalproperty_get_comment(p));
721         }
722
723         p = ical_ctdl_get_subprop(ird.cal, ICAL_UID_PROPERTY);
724         if (p != NULL) {
725                 strcpy(conflict_event_uid, icalproperty_get_comment(p));
726         }
727
728         p = ical_ctdl_get_subprop(ird.cal, ICAL_SUMMARY_PROPERTY);
729         if (p != NULL) {
730                 strcpy(conflict_event_summary, icalproperty_get_comment(p));
731         }
732
733
734         icalcomponent_free(ird.cal);
735
736         if (ical_ctdl_is_overlap(t1start, t1end, t2start, t2end)) {
737                 cprintf("%ld||%s|%s|%d|\n",
738                         msgnum,
739                         conflict_event_uid,
740                         conflict_event_summary,
741                         (       ((strlen(compare_uid)>0)
742                                 &&(!strcasecmp(compare_uid,
743                                 conflict_event_uid))) ? 1 : 0
744                         )
745                 );
746         }
747 }
748
749
750
751 /* 
752  * Phase 2 of "hunt for conflicts" operation.
753  * At this point we have a calendar object which represents the VEVENT that
754  * we're considering adding to the calendar.  Now hunt through the user's
755  * calendar room, and output zero or more existing VEVENTs which conflict
756  * with this one.
757  */
758 void ical_hunt_for_conflicts(icalcomponent *cal) {
759         char hold_rm[ROOMNAMELEN];
760
761         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
762
763         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
764                 getroom(&CC->quickroom, hold_rm);
765                 cprintf("%d You do not have a calendar.\n", ERROR);
766                 return;
767         }
768
769         cprintf("%d Conflicting events:\n", LISTING_FOLLOWS);
770
771         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
772                 NULL,
773                 ical_hunt_for_conflicts_backend,
774                 (void *) cal
775         );
776
777         cprintf("000\n");
778         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
779
780 }
781
782
783
784 /*
785  * Hunt for conflicts (Phase 1 -- retrieve the object and call Phase 2)
786  */
787 void ical_conflicts(long msgnum, char *partnum) {
788         struct CtdlMessage *msg;
789         struct ical_respond_data ird;
790
791         msg = CtdlFetchMessage(msgnum);
792         if (msg == NULL) {
793                 cprintf("%d Message %ld not found.\n",
794                         ERROR+ILLEGAL_VALUE,
795                         (long)msgnum
796                 );
797                 return;
798         }
799
800         memset(&ird, 0, sizeof ird);
801         strcpy(ird.desired_partnum, partnum);
802         mime_parser(msg->cm_fields['M'],
803                 NULL,
804                 *ical_locate_part,              /* callback function */
805                 NULL, NULL,
806                 (void *) &ird,                  /* user data */
807                 0
808         );
809
810         CtdlFreeMessage(msg);
811
812         if (ird.cal != NULL) {
813                 ical_hunt_for_conflicts(ird.cal);
814                 icalcomponent_free(ird.cal);
815                 return;
816         }
817         else {
818                 cprintf("%d No calendar object found\n", ERROR);
819                 return;
820         }
821
822         /* should never get here */
823 }
824
825
826
827
828 /*
829  * All Citadel calendar commands from the client come through here.
830  */
831 void cmd_ical(char *argbuf)
832 {
833         char subcmd[SIZ];
834         long msgnum;
835         char partnum[SIZ];
836         char action[SIZ];
837
838         if (CtdlAccessCheck(ac_logged_in)) return;
839
840         extract(subcmd, argbuf, 0);
841
842         if (!strcmp(subcmd, "test")) {
843                 cprintf("%d This server supports calendaring\n", CIT_OK);
844                 return;
845         }
846
847         else if (!strcmp(subcmd, "respond")) {
848                 msgnum = extract_long(argbuf, 1);
849                 extract(partnum, argbuf, 2);
850                 extract(action, argbuf, 3);
851                 ical_respond(msgnum, partnum, action);
852         }
853
854         else if (!strcmp(subcmd, "handle_rsvp")) {
855                 msgnum = extract_long(argbuf, 1);
856                 extract(partnum, argbuf, 2);
857                 extract(action, argbuf, 3);
858                 ical_handle_rsvp(msgnum, partnum, action);
859         }
860
861         else if (!strcmp(subcmd, "conflicts")) {
862                 msgnum = extract_long(argbuf, 1);
863                 extract(partnum, argbuf, 2);
864                 ical_conflicts(msgnum, partnum);
865         }
866
867         else {
868                 cprintf("%d Invalid subcommand\n", ERROR+CMD_NOT_SUPPORTED);
869                 return;
870         }
871
872         /* should never get here */
873 }
874
875
876
877 /*
878  * We don't know if the calendar room exists so we just create it at login
879  */
880 void ical_create_room(void)
881 {
882         struct quickroom qr;
883         struct visit vbuf;
884
885         /* Create the calendar room if it doesn't already exist */
886         create_room(USERCALENDARROOM, 4, "", 0, 1, 0);
887
888         /* Set expiration policy to manual; otherwise objects will be lost! */
889         if (lgetroom(&qr, USERCALENDARROOM)) {
890                 lprintf(3, "Couldn't get the user calendar room!\n");
891                 return;
892         }
893         qr.QRep.expire_mode = EXPIRE_MANUAL;
894         lputroom(&qr);
895
896         /* Set the view to a calendar view */
897         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
898         vbuf.v_view = 3;        /* 3 = calendar */
899         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
900
901         /* Create the tasks list room if it doesn't already exist */
902         create_room(USERTASKSROOM, 4, "", 0, 1, 0);
903
904         /* Set expiration policy to manual; otherwise objects will be lost! */
905         if (lgetroom(&qr, USERTASKSROOM)) {
906                 lprintf(3, "Couldn't get the user calendar room!\n");
907                 return;
908         }
909         qr.QRep.expire_mode = EXPIRE_MANUAL;
910         lputroom(&qr);
911
912         /* Set the view to a task list view */
913         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
914         vbuf.v_view = 4;        /* 4 = tasks */
915         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
916
917         return;
918 }
919
920
921 /*
922  * ical_send_out_invitations() is called by ical_saving_vevent() when it
923  * finds a VEVENT.   FIXME ... finish implementing.
924  */
925 void ical_send_out_invitations(icalcomponent *cal) {
926         icalcomponent *the_request = NULL;
927         char *serialized_request = NULL;
928         char *request_message_text = NULL;
929         struct CtdlMessage *msg = NULL;
930         struct recptypes *valid = NULL;
931         char attendees_string[SIZ];
932         char this_attendee[SIZ];
933         icalproperty *attendee = NULL;
934         char summary_string[SIZ];
935         icalproperty *summary = NULL;
936         icalcomponent *encaps = NULL;
937
938         if (cal == NULL) {
939                 lprintf(3, "ERROR: trying to reply to NULL event?\n");
940                 return;
941         }
942
943         /* Clone the event */
944         the_request = icalcomponent_new_clone(cal);
945         if (the_request == NULL) {
946                 lprintf(3, "ERROR: cannot clone calendar object\n");
947                 return;
948         }
949
950         /* Extract the summary string -- we'll use it as the
951          * message subject for the request
952          */
953         strcpy(summary_string, "Meeting request");
954         summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
955         if (summary != NULL) {
956                 if (icalproperty_get_summary(summary)) {
957                         strcpy(summary_string,
958                                 icalproperty_get_summary(summary) );
959                 }
960         }
961
962         /* Determine who the recipients of this message are (the attendees) */
963         strcpy(attendees_string, "");
964         for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
965                 if (icalproperty_get_attendee(attendee)) {
966                         strcpy(this_attendee, icalproperty_get_attendee(attendee) );
967                         if (!strncasecmp(this_attendee, "MAILTO:", 7)) {
968                                 strcpy(this_attendee, &this_attendee[7]);
969                                 snprintf(&attendees_string[strlen(attendees_string)],
970                                         sizeof(attendees_string) - strlen(attendees_string),
971                                         "%s, ",
972                                         this_attendee
973                                 );
974                         }
975                 }
976         }
977
978         lprintf(9, "attendees_string: <%s>\n", attendees_string);
979
980         /* Encapsulate the VEVENT component into a complete VCALENDAR */
981         encaps = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
982         if (encaps == NULL) {
983                 lprintf(3, "Error at %s:%d - could not allocate component!\n",
984                         __FILE__, __LINE__);
985                 icalcomponent_free(the_request);
986                 return;
987         }
988
989         /* Set the Product ID */
990         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
991
992         /* Set the Version Number */
993         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
994
995         /* Set the method to REQUEST */
996         icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
997
998         /* FIXME: here we need to insert a VTIMEZONE object. */
999
1000         /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
1001          * are responsible for "the_request"'s memory -- it will be freed
1002          * when we free "encaps".
1003          */
1004         icalcomponent_add_component(encaps, the_request);
1005
1006         /* Serialize it */
1007         serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
1008         icalcomponent_free(encaps);     /* Don't need this anymore. */
1009         if (serialized_request == NULL) return;
1010
1011         request_message_text = mallok(strlen(serialized_request) + SIZ);
1012         if (request_message_text != NULL) {
1013                 sprintf(request_message_text,
1014                         "Content-type: text/calendar\r\n\r\n%s\r\n",
1015                         serialized_request
1016                 );
1017
1018                 msg = CtdlMakeMessage(&CC->usersupp,
1019                         "",                     /* No single recipient here */
1020                         CC->quickroom.QRname, 0, FMT_RFC822,
1021                         "",
1022                         summary_string,         /* Use summary for subject */
1023                         request_message_text);
1024         
1025                 if (msg != NULL) {
1026                         valid = validate_recipients(attendees_string);
1027                         CtdlSubmitMsg(msg, valid, "");
1028                         CtdlFreeMessage(msg);
1029                 }
1030         }
1031         phree(serialized_request);
1032 }
1033
1034
1035 /*
1036  * When a calendar object is being saved, determine whether it's a VEVENT
1037  * and the user saving it is the organizer.  If so, send out invitations
1038  * to any listed attendees.
1039  *
1040  */
1041 void ical_saving_vevent(icalcomponent *cal) {
1042         icalcomponent *c;
1043         icalproperty *organizer = NULL;
1044         char organizer_string[SIZ];
1045
1046         strcpy(organizer_string, "");
1047         /*
1048          * The VEVENT subcomponent is the one we're interested in.
1049          * Send out invitations if, and only if, this user is the Organizer.
1050          */
1051         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
1052                 organizer = icalcomponent_get_first_property(cal,
1053                                                 ICAL_ORGANIZER_PROPERTY);
1054                 if (organizer != NULL) {
1055                         if (icalproperty_get_organizer(organizer)) {
1056                                 strcpy(organizer_string,
1057                                         icalproperty_get_organizer(organizer));
1058                         }
1059                 }
1060                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
1061                         strcpy(organizer_string, &organizer_string[7]);
1062                         striplt(organizer_string);
1063                         /*
1064                          * If the user saving the event is listed as the
1065                          * organizer, then send out invitations.
1066                          */
1067                         if (CtdlIsMe(organizer_string)) {
1068                                 ical_send_out_invitations(cal);
1069                         }
1070                 }
1071         }
1072
1073         /* If the component has subcomponents, recurse through them. */
1074         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
1075             (c != NULL);
1076             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
1077                 /* Recursively process subcomponent */
1078                 ical_saving_vevent(c);
1079         }
1080
1081 }
1082
1083
1084
1085 /*
1086  * Back end for ical_obj_beforesave()
1087  * This hunts for the UID of the calendar event.
1088  */
1089 void ical_ctdl_set_extended_msgid(char *name, char *filename, char *partnum,
1090                 char *disp, void *content, char *cbtype, size_t length,
1091                 char *encoding, void *cbuserdata)
1092 {
1093         icalcomponent *cal;
1094         icalproperty *p;
1095
1096         /* If this is a text/calendar object, hunt for the UID and drop it in
1097          * the "user data" pointer for the MIME parser.  When
1098          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1099          * to that string.
1100          */
1101         if (!strcasecmp(cbtype, "text/calendar")) {
1102                 cal = icalcomponent_new_from_string(content);
1103                 if (cal != NULL) {
1104                         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
1105                         if (p != NULL) {
1106                                 strcpy((char *)cbuserdata,
1107                                         icalproperty_get_comment(p)
1108                                 );
1109                         }
1110                         icalcomponent_free(cal);
1111                 }
1112         }
1113 }
1114
1115
1116
1117
1118
1119 /*
1120  * See if we need to prevent the object from being saved (we don't allow
1121  * MIME types other than text/calendar in the Calendar> room).  Also, when
1122  * saving an event to the calendar, set the message's Citadel extended message
1123  * ID to the UID of the object.  This causes our replication checker to
1124  * automatically delete any existing instances of the same object.  (Isn't
1125  * that cool?)
1126  */
1127 int ical_obj_beforesave(struct CtdlMessage *msg)
1128 {
1129         char roomname[ROOMNAMELEN];
1130         char *p;
1131         int a;
1132         char eidbuf[SIZ];
1133
1134         /*
1135          * Only messages with content-type text/calendar
1136          * may be saved to Calendar>.  If the message is bound for
1137          * Calendar> but doesn't have this content-type, throw an error
1138          * so that the message may not be posted.
1139          */
1140
1141         /* First determine if this is our room */
1142         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1143         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1144                 return 0;       /* It's not the Calendar room. */
1145         }
1146
1147         /* Then determine content-type of the message */
1148         
1149         /* It must be an RFC822 message! */
1150         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1151         if (msg->cm_format_type != 4)
1152                 return 1;       /* You tried to save a non-RFC822 message! */
1153         
1154         /* Find the Content-Type: header */
1155         p = msg->cm_fields['M'];
1156         a = strlen(p);
1157         while (--a > 0) {
1158                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1159                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1160                                 strcpy(eidbuf, "");
1161                                 mime_parser(msg->cm_fields['M'],
1162                                         NULL,
1163                                         *ical_ctdl_set_extended_msgid,
1164                                         NULL, NULL,
1165                                         (void *)eidbuf,
1166                                         0
1167                                 );
1168                                 if (strlen(eidbuf) > 0) {
1169                                         if (msg->cm_fields['E'] != NULL) {
1170                                                 phree(msg->cm_fields['E']);
1171                                         }
1172                                         msg->cm_fields['E'] = strdoop(eidbuf);
1173                                 }
1174                                 return 0;
1175                         }
1176                         else {
1177                                 return 1;
1178                         }
1179                 }
1180                 p++;
1181         }
1182         
1183         /* Oops!  No Content-Type in this message!  How'd that happen? */
1184         lprintf(7, "RFC822 message with no Content-Type header!\n");
1185         return 1;
1186 }
1187
1188
1189 /*
1190  * Things we need to do after saving a calendar event.
1191  */
1192 void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
1193                 char *disp, void *content, char *cbtype, size_t length,
1194                 char *encoding, void *cbuserdata)
1195 {
1196         icalcomponent *cal;
1197
1198         /* If this is a text/calendar object, hunt for the UID and drop it in
1199          * the "user data" pointer for the MIME parser.  When
1200          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1201          * to that string.
1202          */
1203         if (!strcasecmp(cbtype, "text/calendar")) {
1204                 cal = icalcomponent_new_from_string(content);
1205                 if (cal != NULL) {
1206                         ical_saving_vevent(cal);
1207                         icalcomponent_free(cal);
1208                 }
1209         }
1210 }
1211
1212
1213 /* 
1214  * Things we need to do after saving a calendar event.
1215  */
1216 int ical_obj_aftersave(struct CtdlMessage *msg)
1217 {
1218         char roomname[ROOMNAMELEN];
1219         char *p;
1220         int a;
1221
1222         /*
1223          * If this isn't the Calendar> room, no further action is necessary.
1224          */
1225
1226         /* First determine if this is our room */
1227         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1228         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1229                 return 0;       /* It's not the Calendar room. */
1230         }
1231
1232         /* Then determine content-type of the message */
1233         
1234         /* It must be an RFC822 message! */
1235         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1236         if (msg->cm_format_type != 4) return(1);
1237         
1238         /* Find the Content-Type: header */
1239         p = msg->cm_fields['M'];
1240         a = strlen(p);
1241         while (--a > 0) {
1242                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1243                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1244                                 mime_parser(msg->cm_fields['M'],
1245                                         NULL,
1246                                         *ical_obj_aftersave_backend,
1247                                         NULL, NULL,
1248                                         NULL,
1249                                         0
1250                                 );
1251                                 return 0;
1252                         }
1253                         else {
1254                                 return 1;
1255                         }
1256                 }
1257                 p++;
1258         }
1259         
1260         /* Oops!  No Content-Type in this message!  How'd that happen? */
1261         lprintf(7, "RFC822 message with no Content-Type header!\n");
1262         return 1;
1263 }
1264
1265
1266 #endif  /* HAVE_ICAL_H */
1267
1268 /*
1269  * Register this module with the Citadel server.
1270  */
1271 char *Dynamic_Module_Init(void)
1272 {
1273 #ifdef HAVE_ICAL_H
1274         CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
1275         CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
1276         CtdlRegisterSessionHook(ical_create_room, EVT_LOGIN);
1277         CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCal commands");
1278 #endif
1279         return "$Id$";
1280 }