]> code.citadel.org Git - citadel.git/blob - citadel/serv_calendar.c
* serv_calendar.c: ICAL FREEBUSY command now tries the supplied name not
[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 <stdlib.h>
14 #include <unistd.h>
15 #include <sys/types.h>
16 #include <limits.h>
17 #include <stdio.h>
18 #include <string.h>
19 #ifdef HAVE_STRINGS_H
20 #include <strings.h>
21 #endif
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 "serv_extensions.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 #include "internet_addressing.h"
35 #include "serv_calendar.h"
36
37 #ifdef CITADEL_WITH_CALENDAR_SERVICE
38
39 #include <ical.h>
40 #include "ical_dezonify.h"
41
42 struct ical_respond_data {
43         char desired_partnum[SIZ];
44         icalcomponent *cal;
45 };
46
47
48 /*
49  * Utility function to create a new VCALENDAR component with some of the
50  * required fields already set the way we like them.
51  */
52 icalcomponent *icalcomponent_new_citadel_vcalendar(void) {
53         icalcomponent *encaps;
54
55         encaps = icalcomponent_new_vcalendar();
56         if (encaps == NULL) {
57                 lprintf(CTDL_CRIT, "Error at %s:%d - could not allocate component!\n",
58                         __FILE__, __LINE__);
59                 return NULL;
60         }
61
62         /* Set the Product ID */
63         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
64
65         /* Set the Version Number */
66         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
67
68         return(encaps);
69 }
70
71
72 /*
73  * Utility function to encapsulate a subcomponent into a full VCALENDAR
74  */
75 icalcomponent *ical_encapsulate_subcomponent(icalcomponent *subcomp) {
76         icalcomponent *encaps;
77
78         /* If we're already looking at a full VCALENDAR component,
79          * don't bother ... just return itself.
80          */
81         if (icalcomponent_isa(subcomp) == ICAL_VCALENDAR_COMPONENT) {
82                 return subcomp;
83         }
84
85         /* Encapsulate the VEVENT component into a complete VCALENDAR */
86         encaps = icalcomponent_new_citadel_vcalendar();
87         if (encaps == NULL) return NULL;
88
89         /* Encapsulate the subcomponent inside */
90         icalcomponent_add_component(encaps, subcomp);
91
92         /* Convert all timestamps to UTC so we don't have to deal with
93          * stupid VTIMEZONE crap.
94          */
95         ical_dezonify(encaps);
96
97         /* Return the object we just created. */
98         return(encaps);
99 }
100
101
102
103
104 /*
105  * Write a calendar object into the specified user's calendar room.
106  * 
107  * ok
108  */
109 void ical_write_to_cal(struct ctdluser *u, icalcomponent *cal) {
110         char temp[PATH_MAX];
111         FILE *fp;
112         char *ser;
113         icalcomponent *encaps;
114
115         if (cal == NULL) return;
116
117         /* If the supplied object is a subcomponent, encapsulate it in
118          * a full VCALENDAR component, and save that instead.
119          */
120         if (icalcomponent_isa(cal) != ICAL_VCALENDAR_COMPONENT) {
121                 encaps = ical_encapsulate_subcomponent(
122                         icalcomponent_new_clone(cal)
123                 );
124                 ical_write_to_cal(u, encaps);
125                 icalcomponent_free(encaps);
126                 return;
127         }
128
129         strcpy(temp, tmpnam(NULL));
130         ser = icalcomponent_as_ical_string(cal);
131         if (ser == NULL) return;
132
133         /* Make a temp file out of it */
134         fp = fopen(temp, "w");
135         if (fp == NULL) return;
136         fwrite(ser, strlen(ser), 1, fp);
137         fclose(fp);
138
139         /* This handy API function does all the work for us.
140          */
141         CtdlWriteObject(USERCALENDARROOM,       /* which room */
142                         "text/calendar",        /* MIME type */
143                         temp,                   /* temp file */
144                         u,                      /* which user */
145                         0,                      /* not binary */
146                         0,              /* don't delete others of this type */
147                         0);                     /* no flags */
148
149         unlink(temp);
150 }
151
152
153 /*
154  * Add a calendar object to the user's calendar
155  * 
156  * ok because it uses ical_write_to_cal()
157  */
158 void ical_add(icalcomponent *cal, int recursion_level) {
159         icalcomponent *c;
160
161         /*
162          * The VEVENT subcomponent is the one we're interested in saving.
163          */
164         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
165         
166                 ical_write_to_cal(&CC->user, cal);
167
168         }
169
170         /* If the component has subcomponents, recurse through them. */
171         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
172             (c != 0);
173             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
174                 /* Recursively process subcomponent */
175                 ical_add(c, recursion_level+1);
176         }
177
178 }
179
180
181
182 /*
183  * Send a reply to a meeting invitation.
184  *
185  * 'request' is the invitation to reply to.
186  * 'action' is the string "accept" or "decline".
187  *
188  * (Sorry about this being more than 80 columns ... there was just
189  * no easy way to break it down sensibly.)
190  * 
191  * ok
192  */
193 void ical_send_a_reply(icalcomponent *request, char *action) {
194         icalcomponent *the_reply = NULL;
195         icalcomponent *vevent = NULL;
196         icalproperty *attendee = NULL;
197         char attendee_string[SIZ];
198         icalproperty *organizer = NULL;
199         char organizer_string[SIZ];
200         icalproperty *summary = NULL;
201         char summary_string[SIZ];
202         icalproperty *me_attend = NULL;
203         struct recptypes *recp = NULL;
204         icalparameter *partstat = NULL;
205         char *serialized_reply = NULL;
206         char *reply_message_text = NULL;
207         struct CtdlMessage *msg = NULL;
208         struct recptypes *valid = NULL;
209
210         strcpy(organizer_string, "");
211         strcpy(summary_string, "Calendar item");
212
213         if (request == NULL) {
214                 lprintf(CTDL_ERR, "ERROR: trying to reply to NULL event?\n");
215                 return;
216         }
217
218         the_reply = icalcomponent_new_clone(request);
219         if (the_reply == NULL) {
220                 lprintf(CTDL_ERR, "ERROR: cannot clone request\n");
221                 return;
222         }
223
224         /* Change the method from REQUEST to REPLY */
225         icalcomponent_set_method(the_reply, ICAL_METHOD_REPLY);
226
227         vevent = icalcomponent_get_first_component(the_reply, ICAL_VEVENT_COMPONENT);
228         if (vevent != NULL) {
229                 /* Hunt for attendees, removing ones that aren't us.
230                  * (Actually, remove them all, cloning our own one so we can
231                  * re-insert it later)
232                  */
233                 while (attendee = icalcomponent_get_first_property(vevent,
234                     ICAL_ATTENDEE_PROPERTY), (attendee != NULL)
235                 ) {
236                         if (icalproperty_get_attendee(attendee)) {
237                                 strcpy(attendee_string,
238                                         icalproperty_get_attendee(attendee) );
239                                 if (!strncasecmp(attendee_string, "MAILTO:", 7)) {
240                                         strcpy(attendee_string, &attendee_string[7]);
241                                         striplt(attendee_string);
242                                         recp = validate_recipients(attendee_string);
243                                         if (recp != NULL) {
244                                                 if (!strcasecmp(recp->recp_local, CC->user.fullname)) {
245                                                         if (me_attend) icalproperty_free(me_attend);
246                                                         me_attend = icalproperty_new_clone(attendee);
247                                                 }
248                                                 free(recp);
249                                         }
250                                 }
251                         }
252                         /* Remove it... */
253                         icalcomponent_remove_property(vevent, attendee);
254                         icalproperty_free(attendee);
255                 }
256
257                 /* We found our own address in the attendee list. */
258                 if (me_attend) {
259                         /* Change the partstat from NEEDS-ACTION to ACCEPT or DECLINE */
260                         icalproperty_remove_parameter(me_attend, ICAL_PARTSTAT_PARAMETER);
261
262                         if (!strcasecmp(action, "accept")) {
263                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_ACCEPTED);
264                         }
265                         else if (!strcasecmp(action, "decline")) {
266                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_DECLINED);
267                         }
268                         else if (!strcasecmp(action, "tentative")) {
269                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_TENTATIVE);
270                         }
271
272                         if (partstat) icalproperty_add_parameter(me_attend, partstat);
273
274                         /* Now insert it back into the vevent. */
275                         icalcomponent_add_property(vevent, me_attend);
276                 }
277
278                 /* Figure out who to send this thing to */
279                 organizer = icalcomponent_get_first_property(vevent, ICAL_ORGANIZER_PROPERTY);
280                 if (organizer != NULL) {
281                         if (icalproperty_get_organizer(organizer)) {
282                                 strcpy(organizer_string,
283                                         icalproperty_get_organizer(organizer) );
284                         }
285                 }
286                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
287                         strcpy(organizer_string, &organizer_string[7]);
288                         striplt(organizer_string);
289                 } else {
290                         strcpy(organizer_string, "");
291                 }
292
293                 /* Extract the summary string -- we'll use it as the
294                  * message subject for the reply
295                  */
296                 summary = icalcomponent_get_first_property(vevent, ICAL_SUMMARY_PROPERTY);
297                 if (summary != NULL) {
298                         if (icalproperty_get_summary(summary)) {
299                                 strcpy(summary_string,
300                                         icalproperty_get_summary(summary) );
301                         }
302                 }
303
304         }
305
306         /* Now generate the reply message and send it out. */
307         serialized_reply = strdup(icalcomponent_as_ical_string(the_reply));
308         icalcomponent_free(the_reply);  /* don't need this anymore */
309         if (serialized_reply == NULL) return;
310
311         reply_message_text = malloc(strlen(serialized_reply) + SIZ);
312         if (reply_message_text != NULL) {
313                 sprintf(reply_message_text,
314                         "Content-type: text/calendar\r\n\r\n%s\r\n",
315                         serialized_reply
316                 );
317
318                 msg = CtdlMakeMessage(&CC->user, organizer_string,
319                         CC->room.QRname, 0, FMT_RFC822,
320                         "",
321                         summary_string,         /* Use summary for subject */
322                         reply_message_text);
323         
324                 if (msg != NULL) {
325                         valid = validate_recipients(organizer_string);
326                         CtdlSubmitMsg(msg, valid, "");
327                         CtdlFreeMessage(msg);
328                 }
329         }
330         free(serialized_reply);
331 }
332
333
334
335 /*
336  * Callback function for mime parser that hunts for calendar content types
337  * and turns them into calendar objects
338  */
339 void ical_locate_part(char *name, char *filename, char *partnum, char *disp,
340                 void *content, char *cbtype, size_t length, char *encoding,
341                 void *cbuserdata) {
342
343         struct ical_respond_data *ird = NULL;
344
345         ird = (struct ical_respond_data *) cbuserdata;
346
347         /* desired_partnum can be set to "_HUNT_" to have it just look for
348          * the first part with a content type of text/calendar.  Otherwise
349          * we have to only process the right one.
350          */
351         if (strcasecmp(ird->desired_partnum, "_HUNT_")) {
352                 if (strcasecmp(partnum, ird->desired_partnum)) {
353                         return;
354                 }
355         }
356
357         if (strcasecmp(cbtype, "text/calendar")) {
358                 return;
359         }
360
361         if (ird->cal != NULL) {
362                 icalcomponent_free(ird->cal);
363                 ird->cal = NULL;
364         }
365
366         ird->cal = icalcomponent_new_from_string(content);
367         if (ird->cal != NULL) {
368                 ical_dezonify(ird->cal);
369         }
370 }
371
372
373 /*
374  * Respond to a meeting request.
375  */
376 void ical_respond(long msgnum, char *partnum, char *action) {
377         struct CtdlMessage *msg;
378         struct ical_respond_data ird;
379
380         if (
381            (strcasecmp(action, "accept"))
382            && (strcasecmp(action, "decline"))
383         ) {
384                 cprintf("%d Action must be 'accept' or 'decline'\n",
385                         ERROR + ILLEGAL_VALUE
386                 );
387                 return;
388         }
389
390         msg = CtdlFetchMessage(msgnum);
391         if (msg == NULL) {
392                 cprintf("%d Message %ld not found.\n",
393                         ERROR + ILLEGAL_VALUE,
394                         (long)msgnum
395                 );
396                 return;
397         }
398
399         memset(&ird, 0, sizeof ird);
400         strcpy(ird.desired_partnum, partnum);
401         mime_parser(msg->cm_fields['M'],
402                 NULL,
403                 *ical_locate_part,              /* callback function */
404                 NULL, NULL,
405                 (void *) &ird,                  /* user data */
406                 0
407         );
408
409         /* We're done with the incoming message, because we now have a
410          * calendar object in memory.
411          */
412         CtdlFreeMessage(msg);
413
414         /*
415          * Here is the real meat of this function.  Handle the event.
416          */
417         if (ird.cal != NULL) {
418                 /* Save this in the user's calendar if necessary */
419                 if (!strcasecmp(action, "accept")) {
420                         ical_add(ird.cal, 0);
421                 }
422
423                 /* Send a reply if necessary */
424                 if (icalcomponent_get_method(ird.cal) == ICAL_METHOD_REQUEST) {
425                         ical_send_a_reply(ird.cal, action);
426                 }
427
428                 /* Now that we've processed this message, we don't need it
429                  * anymore.  So delete it.
430                  */
431                 CtdlDeleteMessages(CC->room.QRname, msgnum, "");
432
433                 /* Free the memory we allocated and return a response. */
434                 icalcomponent_free(ird.cal);
435                 ird.cal = NULL;
436                 cprintf("%d ok\n", CIT_OK);
437                 return;
438         }
439         else {
440                 cprintf("%d No calendar object found\n", ERROR + ROOM_NOT_FOUND);
441                 return;
442         }
443
444         /* should never get here */
445 }
446
447
448 /*
449  * Figure out the UID of the calendar event being referred to in a
450  * REPLY object.  This function is recursive.
451  */
452 void ical_learn_uid_of_reply(char *uidbuf, icalcomponent *cal) {
453         icalcomponent *subcomponent;
454         icalproperty *p;
455
456         /* If this object is a REPLY, then extract the UID. */
457         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
458                 p = icalcomponent_get_first_property(cal, ICAL_UID_PROPERTY);
459                 if (p != NULL) {
460                         strcpy(uidbuf, icalproperty_get_comment(p));
461                 }
462         }
463
464         /* Otherwise, recurse through any VEVENT subcomponents.  We do NOT want the
465          * UID of the reply; we want the UID of the invitation being replied to.
466          */
467         for (subcomponent = icalcomponent_get_first_component(cal, ICAL_VEVENT_COMPONENT);
468             subcomponent != NULL;
469             subcomponent = icalcomponent_get_next_component(cal, ICAL_VEVENT_COMPONENT) ) {
470                 ical_learn_uid_of_reply(uidbuf, subcomponent);
471         }
472 }
473
474
475 /*
476  * ical_update_my_calendar_with_reply() refers to this callback function; when we
477  * locate the message containing the calendar event we're replying to, this function
478  * gets called.  It basically just sticks the message number in a supplied buffer.
479  */
480 void ical_hunt_for_event_to_update(long msgnum, void *data) {
481         long *msgnumptr;
482
483         msgnumptr = (long *) data;
484         *msgnumptr = msgnum;
485 }
486
487
488 struct original_event_container {
489         icalcomponent *c;
490 };
491
492 /*
493  * Callback function for mime parser that hunts for calendar content types
494  * and turns them into calendar objects (called by ical_update_my_calendar_with_reply()
495  * to fetch the object being updated)
496  */
497 void ical_locate_original_event(char *name, char *filename, char *partnum, char *disp,
498                 void *content, char *cbtype, size_t length, char *encoding,
499                 void *cbuserdata) {
500
501         struct original_event_container *oec = NULL;
502
503         if (strcasecmp(cbtype, "text/calendar")) {
504                 return;
505         }
506         oec = (struct original_event_container *) cbuserdata;
507         if (oec->c != NULL) {
508                 icalcomponent_free(oec->c);
509         }
510         oec->c = icalcomponent_new_from_string(content);
511 }
512
513
514 /*
515  * Merge updated attendee information from a REPLY into an existing event.
516  */
517 void ical_merge_attendee_reply(icalcomponent *event, icalcomponent *reply) {
518         icalcomponent *c;
519         icalproperty *e_attendee, *r_attendee;
520
521         /* First things first.  If we're not looking at a VEVENT component,
522          * recurse through subcomponents until we find one.
523          */
524         if (icalcomponent_isa(event) != ICAL_VEVENT_COMPONENT) {
525                 for (c = icalcomponent_get_first_component(event, ICAL_VEVENT_COMPONENT);
526                     c != NULL;
527                     c = icalcomponent_get_next_component(event, ICAL_VEVENT_COMPONENT) ) {
528                         ical_merge_attendee_reply(c, reply);
529                 }
530                 return;
531         }
532
533         /* Now do the same thing with the reply.
534          */
535         if (icalcomponent_isa(reply) != ICAL_VEVENT_COMPONENT) {
536                 for (c = icalcomponent_get_first_component(reply, ICAL_VEVENT_COMPONENT);
537                     c != NULL;
538                     c = icalcomponent_get_next_component(reply, ICAL_VEVENT_COMPONENT) ) {
539                         ical_merge_attendee_reply(event, c);
540                 }
541                 return;
542         }
543
544         /* Clone the reply, because we're going to rip its guts out. */
545         reply = icalcomponent_new_clone(reply);
546
547         /* At this point we're looking at the correct subcomponents.
548          * Iterate through the attendees looking for a match.
549          */
550 STARTOVER:
551         for (e_attendee = icalcomponent_get_first_property(event, ICAL_ATTENDEE_PROPERTY);
552             e_attendee != NULL;
553             e_attendee = icalcomponent_get_next_property(event, ICAL_ATTENDEE_PROPERTY)) {
554
555                 for (r_attendee = icalcomponent_get_first_property(reply, ICAL_ATTENDEE_PROPERTY);
556                     r_attendee != NULL;
557                     r_attendee = icalcomponent_get_next_property(reply, ICAL_ATTENDEE_PROPERTY)) {
558
559                         /* Check to see if these two attendees match...
560                          */
561                         if (!strcasecmp(
562                            icalproperty_get_attendee(e_attendee),
563                            icalproperty_get_attendee(r_attendee)
564                         )) {
565                                 /* ...and if they do, remove the attendee from the event
566                                  * and replace it with the attendee from the reply.  (The
567                                  * reply's copy will have the same address, but an updated
568                                  * status.)
569                                  */
570                                 TRACE;
571                                 icalcomponent_remove_property(event, e_attendee);
572                                 TRACE;
573                                 icalproperty_free(e_attendee);
574                                 TRACE;
575                                 icalcomponent_remove_property(reply, r_attendee);
576                                 TRACE;
577                                 icalcomponent_add_property(event, r_attendee);
578                                 TRACE;
579
580                                 /* Since we diddled both sets of attendees, we have to start
581                                  * the iteration over again.  This will not create an infinite
582                                  * loop because we removed the attendee from the reply.  (That's
583                                  * why we cloned the reply, and that's what we mean by "ripping
584                                  * its guts out.")
585                                  */
586                                 goto STARTOVER;
587                         }
588         
589                 }
590         }
591
592         /* Free the *clone* of the reply. */
593         icalcomponent_free(reply);
594 }
595
596
597
598
599 /*
600  * Handle an incoming RSVP (object with method==ICAL_METHOD_REPLY) for a
601  * calendar event.  The object has already been deserialized for us; all
602  * we have to do here is hunt for the event in our calendar, merge in the
603  * updated attendee status, and save it again.
604  *
605  * This function returns 0 on success, 1 if the event was not found in the
606  * user's calendar, or 2 if an internal error occurred.
607  */
608 int ical_update_my_calendar_with_reply(icalcomponent *cal) {
609         char uid[SIZ];
610         char hold_rm[ROOMNAMELEN];
611         long msgnum_being_replaced = 0;
612         struct CtdlMessage *template = NULL;
613         struct CtdlMessage *msg;
614         struct original_event_container oec;
615         icalcomponent *original_event;
616         char *serialized_event = NULL;
617         char roomname[ROOMNAMELEN];
618         char *message_text = NULL;
619
620         /* Figure out just what event it is we're dealing with */
621         strcpy(uid, "--==<< InVaLiD uId >>==--");
622         ical_learn_uid_of_reply(uid, cal);
623         lprintf(CTDL_DEBUG, "UID of event being replied to is <%s>\n", uid);
624
625         strcpy(hold_rm, CC->room.QRname);       /* save current room */
626
627         if (getroom(&CC->room, USERCALENDARROOM) != 0) {
628                 getroom(&CC->room, hold_rm);
629                 lprintf(CTDL_CRIT, "cannot get user calendar room\n");
630                 return(2);
631         }
632
633         /*
634          * Pound through the user's calendar looking for a message with
635          * the Citadel EUID set to the value we're looking for.  Since
636          * Citadel always sets the message EUID to the vCalendar UID of
637          * the event, this will work.
638          */
639         template = (struct CtdlMessage *)
640                 malloc(sizeof(struct CtdlMessage));
641         memset(template, 0, sizeof(struct CtdlMessage));
642         template->cm_fields['E'] = strdup(uid);
643         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
644                 template, ical_hunt_for_event_to_update, &msgnum_being_replaced);
645         CtdlFreeMessage(template);
646         getroom(&CC->room, hold_rm);    /* return to saved room */
647
648         lprintf(CTDL_DEBUG, "msgnum_being_replaced == %ld\n", msgnum_being_replaced);
649         if (msgnum_being_replaced == 0) {
650                 return(1);                      /* no calendar event found */
651         }
652
653         /* Now we know the ID of the message containing the event being updated.
654          * We don't actually have to delete it; that'll get taken care of by the
655          * server when we save another event with the same UID.  This just gives
656          * us the ability to load the event into memory so we can diddle the
657          * attendees.
658          */
659         msg = CtdlFetchMessage(msgnum_being_replaced);
660         if (msg == NULL) {
661                 return(2);                      /* internal error */
662         }
663         oec.c = NULL;
664         mime_parser(msg->cm_fields['M'],
665                 NULL,
666                 *ical_locate_original_event,    /* callback function */
667                 NULL, NULL,
668                 &oec,                           /* user data */
669                 0
670         );
671         CtdlFreeMessage(msg);
672
673         original_event = oec.c;
674         if (original_event == NULL) {
675                 lprintf(CTDL_ERR, "ERROR: Original_component is NULL.\n");
676                 return(2);
677         }
678
679         /* Merge the attendee's updated status into the event */
680         ical_merge_attendee_reply(original_event, cal);
681
682         /* Serialize it */
683         serialized_event = strdup(icalcomponent_as_ical_string(original_event));
684         icalcomponent_free(original_event);     /* Don't need this anymore. */
685         if (serialized_event == NULL) return(2);
686
687         MailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
688
689         message_text = malloc(strlen(serialized_event) + SIZ);
690         if (message_text != NULL) {
691                 sprintf(message_text,
692                         "Content-type: text/calendar\r\n\r\n%s\r\n",
693                         serialized_event
694                 );
695
696                 msg = CtdlMakeMessage(&CC->user,
697                         "",                     /* No recipient */
698                         roomname,
699                         0, FMT_RFC822,
700                         "",
701                         "",             /* no subject */
702                         message_text);
703         
704                 if (msg != NULL) {
705                         CIT_ICAL->avoid_sending_invitations = 1;
706                         CtdlSubmitMsg(msg, NULL, roomname);
707                         CtdlFreeMessage(msg);
708                         CIT_ICAL->avoid_sending_invitations = 0;
709                 }
710         }
711         free(serialized_event);
712         return(0);
713 }
714
715
716 /*
717  * Handle an incoming RSVP for an event.  (This is the server subcommand part; it
718  * simply extracts the calendar object from the message, deserializes it, and
719  * passes it up to ical_update_my_calendar_with_reply() for processing.
720  */
721 void ical_handle_rsvp(long msgnum, char *partnum, char *action) {
722         struct CtdlMessage *msg;
723         struct ical_respond_data ird;
724         int ret;
725
726         if (
727            (strcasecmp(action, "update"))
728            && (strcasecmp(action, "ignore"))
729         ) {
730                 cprintf("%d Action must be 'update' or 'ignore'\n",
731                         ERROR + ILLEGAL_VALUE
732                 );
733                 return;
734         }
735
736         msg = CtdlFetchMessage(msgnum);
737         if (msg == NULL) {
738                 cprintf("%d Message %ld not found.\n",
739                         ERROR + ILLEGAL_VALUE,
740                         (long)msgnum
741                 );
742                 return;
743         }
744
745         memset(&ird, 0, sizeof ird);
746         strcpy(ird.desired_partnum, partnum);
747         mime_parser(msg->cm_fields['M'],
748                 NULL,
749                 *ical_locate_part,              /* callback function */
750                 NULL, NULL,
751                 (void *) &ird,                  /* user data */
752                 0
753         );
754
755         /* We're done with the incoming message, because we now have a
756          * calendar object in memory.
757          */
758         CtdlFreeMessage(msg);
759
760         /*
761          * Here is the real meat of this function.  Handle the event.
762          */
763         if (ird.cal != NULL) {
764                 /* Update the user's calendar if necessary */
765                 if (!strcasecmp(action, "update")) {
766                         ret = ical_update_my_calendar_with_reply(ird.cal);
767                         if (ret == 0) {
768                                 cprintf("%d Your calendar has been updated with this reply.\n",
769                                         CIT_OK);
770                         }
771                         else if (ret == 1) {
772                                 cprintf("%d This event does not exist in your calendar.\n",
773                                         ERROR + FILE_NOT_FOUND);
774                         }
775                         else {
776                                 cprintf("%d An internal error occurred.\n",
777                                         ERROR + INTERNAL_ERROR);
778                         }
779                 }
780                 else {
781                         cprintf("%d This reply has been ignored.\n", CIT_OK);
782                 }
783
784                 /* Now that we've processed this message, we don't need it
785                  * anymore.  So delete it.  (Maybe make this optional?)
786                  */
787                 CtdlDeleteMessages(CC->room.QRname, msgnum, "");
788
789                 /* Free the memory we allocated and return a response. */
790                 icalcomponent_free(ird.cal);
791                 ird.cal = NULL;
792                 return;
793         }
794         else {
795                 cprintf("%d No calendar object found\n", ERROR + ROOM_NOT_FOUND);
796                 return;
797         }
798
799         /* should never get here */
800 }
801
802
803 /*
804  * Search for a property in both the top level and in a VEVENT subcomponent
805  */
806 icalproperty *ical_ctdl_get_subprop(
807                 icalcomponent *cal,
808                 icalproperty_kind which_prop
809 ) {
810         icalproperty *p;
811         icalcomponent *c;
812
813         p = icalcomponent_get_first_property(cal, which_prop);
814         if (p == NULL) {
815                 c = icalcomponent_get_first_component(cal,
816                                                         ICAL_VEVENT_COMPONENT);
817                 if (c != NULL) {
818                         p = icalcomponent_get_first_property(c, which_prop);
819                 }
820         }
821         return p;
822 }
823
824
825 /*
826  * Check to see if two events overlap.  Returns nonzero if they do.
827  * (This function is used in both Citadel and WebCit.  If you change it in
828  * one place, change it in the other.  Better yet, put it in a library.)
829  */
830 int ical_ctdl_is_overlap(
831                         struct icaltimetype t1start,
832                         struct icaltimetype t1end,
833                         struct icaltimetype t2start,
834                         struct icaltimetype t2end
835 ) {
836
837         if (icaltime_is_null_time(t1start)) return(0);
838         if (icaltime_is_null_time(t2start)) return(0);
839
840         /* First, check for all-day events */
841         if (t1start.is_date) {
842                 if (!icaltime_compare_date_only(t1start, t2start)) {
843                         return(1);
844                 }
845                 if (!icaltime_is_null_time(t2end)) {
846                         if (!icaltime_compare_date_only(t1start, t2end)) {
847                                 return(1);
848                         }
849                 }
850         }
851
852         if (t2start.is_date) {
853                 if (!icaltime_compare_date_only(t2start, t1start)) {
854                         return(1);
855                 }
856                 if (!icaltime_is_null_time(t1end)) {
857                         if (!icaltime_compare_date_only(t2start, t1end)) {
858                                 return(1);
859                         }
860                 }
861         }
862
863         /* Now check for overlaps using date *and* time. */
864
865         /* First, bail out if either event 1 or event 2 is missing end time. */
866         if (icaltime_is_null_time(t1end)) return(0);
867         if (icaltime_is_null_time(t2end)) return(0);
868
869         /* If event 1 ends before event 2 starts, we're in the clear. */
870         if (icaltime_compare(t1end, t2start) <= 0) return(0);
871
872         /* If event 2 ends before event 1 starts, we're also ok. */
873         if (icaltime_compare(t2end, t1start) <= 0) return(0);
874
875         /* Otherwise, they overlap. */
876         return(1);
877 }
878
879
880
881 /*
882  * Backend for ical_hunt_for_conflicts()
883  */
884 void ical_hunt_for_conflicts_backend(long msgnum, void *data) {
885         icalcomponent *cal;
886         struct CtdlMessage *msg;
887         struct ical_respond_data ird;
888         struct icaltimetype t1start, t1end, t2start, t2end;
889         icalproperty *p;
890         char conflict_event_uid[SIZ];
891         char conflict_event_summary[SIZ];
892         char compare_uid[SIZ];
893
894         cal = (icalcomponent *)data;
895         strcpy(compare_uid, "");
896         strcpy(conflict_event_uid, "");
897         strcpy(conflict_event_summary, "");
898
899         msg = CtdlFetchMessage(msgnum);
900         if (msg == NULL) return;
901         memset(&ird, 0, sizeof ird);
902         strcpy(ird.desired_partnum, "_HUNT_");
903         mime_parser(msg->cm_fields['M'],
904                 NULL,
905                 *ical_locate_part,              /* callback function */
906                 NULL, NULL,
907                 (void *) &ird,                  /* user data */
908                 0
909         );
910         CtdlFreeMessage(msg);
911
912         if (ird.cal == NULL) return;
913
914         t1start = icaltime_null_time();
915         t1end = icaltime_null_time();
916         t2start = icaltime_null_time();
917         t1end = icaltime_null_time();
918
919         /* Now compare cal to ird.cal */
920         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTSTART_PROPERTY);
921         if (p == NULL) return;
922         if (p != NULL) t2start = icalproperty_get_dtstart(p);
923         
924         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTEND_PROPERTY);
925         if (p != NULL) t2end = icalproperty_get_dtend(p);
926
927         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
928         if (p == NULL) return;
929         if (p != NULL) t1start = icalproperty_get_dtstart(p);
930         
931         p = ical_ctdl_get_subprop(cal, ICAL_DTEND_PROPERTY);
932         if (p != NULL) t1end = icalproperty_get_dtend(p);
933         
934         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
935         if (p != NULL) {
936                 strcpy(compare_uid, icalproperty_get_comment(p));
937         }
938
939         p = ical_ctdl_get_subprop(ird.cal, ICAL_UID_PROPERTY);
940         if (p != NULL) {
941                 strcpy(conflict_event_uid, icalproperty_get_comment(p));
942         }
943
944         p = ical_ctdl_get_subprop(ird.cal, ICAL_SUMMARY_PROPERTY);
945         if (p != NULL) {
946                 strcpy(conflict_event_summary, icalproperty_get_comment(p));
947         }
948
949         icalcomponent_free(ird.cal);
950
951         if (ical_ctdl_is_overlap(t1start, t1end, t2start, t2end)) {
952                 cprintf("%ld||%s|%s|%d|\n",
953                         msgnum,
954                         conflict_event_uid,
955                         conflict_event_summary,
956                         (       ((strlen(compare_uid)>0)
957                                 &&(!strcasecmp(compare_uid,
958                                 conflict_event_uid))) ? 1 : 0
959                         )
960                 );
961         }
962 }
963
964
965
966 /* 
967  * Phase 2 of "hunt for conflicts" operation.
968  * At this point we have a calendar object which represents the VEVENT that
969  * we're considering adding to the calendar.  Now hunt through the user's
970  * calendar room, and output zero or more existing VEVENTs which conflict
971  * with this one.
972  */
973 void ical_hunt_for_conflicts(icalcomponent *cal) {
974         char hold_rm[ROOMNAMELEN];
975
976         strcpy(hold_rm, CC->room.QRname);       /* save current room */
977
978         if (getroom(&CC->room, USERCALENDARROOM) != 0) {
979                 getroom(&CC->room, hold_rm);
980                 cprintf("%d You do not have a calendar.\n", ERROR + ROOM_NOT_FOUND);
981                 return;
982         }
983
984         cprintf("%d Conflicting events:\n", LISTING_FOLLOWS);
985
986         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
987                 NULL,
988                 ical_hunt_for_conflicts_backend,
989                 (void *) cal
990         );
991
992         cprintf("000\n");
993         getroom(&CC->room, hold_rm);    /* return to saved room */
994
995 }
996
997
998
999 /*
1000  * Hunt for conflicts (Phase 1 -- retrieve the object and call Phase 2)
1001  */
1002 void ical_conflicts(long msgnum, char *partnum) {
1003         struct CtdlMessage *msg;
1004         struct ical_respond_data ird;
1005
1006         msg = CtdlFetchMessage(msgnum);
1007         if (msg == NULL) {
1008                 cprintf("%d Message %ld not found.\n",
1009                         ERROR + ILLEGAL_VALUE,
1010                         (long)msgnum
1011                 );
1012                 return;
1013         }
1014
1015         memset(&ird, 0, sizeof ird);
1016         strcpy(ird.desired_partnum, partnum);
1017         mime_parser(msg->cm_fields['M'],
1018                 NULL,
1019                 *ical_locate_part,              /* callback function */
1020                 NULL, NULL,
1021                 (void *) &ird,                  /* user data */
1022                 0
1023         );
1024
1025         CtdlFreeMessage(msg);
1026
1027         if (ird.cal != NULL) {
1028                 ical_hunt_for_conflicts(ird.cal);
1029                 icalcomponent_free(ird.cal);
1030                 return;
1031         }
1032         else {
1033                 cprintf("%d No calendar object found\n", ERROR + ROOM_NOT_FOUND);
1034                 return;
1035         }
1036
1037         /* should never get here */
1038 }
1039
1040
1041
1042 /*
1043  * Look for busy time in a VEVENT and add it to the supplied VFREEBUSY.
1044  */
1045 void ical_add_to_freebusy(icalcomponent *fb, icalcomponent *cal) {
1046         icalproperty *p;
1047         icalvalue *v;
1048         struct icalperiodtype my_period;
1049
1050         if (cal == NULL) return;
1051         my_period = icalperiodtype_null_period();
1052
1053         if (icalcomponent_isa(cal) != ICAL_VEVENT_COMPONENT) {
1054                 ical_add_to_freebusy(fb,
1055                         icalcomponent_get_first_component(
1056                                 cal, ICAL_VEVENT_COMPONENT
1057                         )
1058                 );
1059                 return;
1060         }
1061
1062         ical_dezonify(cal);
1063
1064         /* If this event is not opaque, the user isn't publishing it as
1065          * busy time, so don't bother doing anything else.
1066          */
1067         p = icalcomponent_get_first_property(cal, ICAL_TRANSP_PROPERTY);
1068         if (p != NULL) {
1069                 v = icalproperty_get_value(p);
1070                 if (v != NULL) {
1071                         if (icalvalue_get_transp(v) != ICAL_TRANSP_OPAQUE) {
1072                                 return;
1073                         }
1074                 }
1075         }
1076
1077         /* Convert the DTSTART and DTEND properties to an icalperiod. */
1078         p = icalcomponent_get_first_property(cal, ICAL_DTSTART_PROPERTY);
1079         if (p != NULL) {
1080                 my_period.start = icalproperty_get_dtstart(p);
1081         }
1082
1083         p = icalcomponent_get_first_property(cal, ICAL_DTEND_PROPERTY);
1084         if (p != NULL) {
1085                 my_period.end = icalproperty_get_dtstart(p);
1086         }
1087
1088         /* Now add it. */
1089         icalcomponent_add_property(fb,
1090                 icalproperty_new_freebusy(my_period)
1091         );
1092
1093 }
1094
1095
1096
1097 /*
1098  * Backend for ical_freebusy()
1099  *
1100  * This function simply loads the messages in the user's calendar room,
1101  * which contain VEVENTs, then strips them of all non-freebusy data, and
1102  * adds them to the supplied VCALENDAR.
1103  *
1104  */
1105 void ical_freebusy_backend(long msgnum, void *data) {
1106         icalcomponent *cal;
1107         struct CtdlMessage *msg;
1108         struct ical_respond_data ird;
1109
1110         cal = (icalcomponent *)data;
1111
1112         msg = CtdlFetchMessage(msgnum);
1113         if (msg == NULL) return;
1114         memset(&ird, 0, sizeof ird);
1115         strcpy(ird.desired_partnum, "_HUNT_");
1116         mime_parser(msg->cm_fields['M'],
1117                 NULL,
1118                 *ical_locate_part,              /* callback function */
1119                 NULL, NULL,
1120                 (void *) &ird,                  /* user data */
1121                 0
1122         );
1123         CtdlFreeMessage(msg);
1124
1125         if (ird.cal == NULL) return;
1126
1127         ical_add_to_freebusy(cal, ird.cal);
1128
1129         /* Now free the memory. */
1130         icalcomponent_free(ird.cal);
1131 }
1132
1133
1134
1135 /*
1136  * Grab another user's free/busy times
1137  */
1138 void ical_freebusy(char *who) {
1139         struct ctdluser usbuf;
1140         char calendar_room_name[ROOMNAMELEN];
1141         char hold_rm[ROOMNAMELEN];
1142         char *serialized_request = NULL;
1143         icalcomponent *encaps = NULL;
1144         icalcomponent *fb = NULL;
1145         int found_user = (-1);
1146         struct recptypes *recp = NULL;
1147         char buf[SIZ];
1148         char host[SIZ];
1149         char type[SIZ];
1150         int i = 0;
1151         int config_lines = 0;
1152
1153         /* First try an exact match. */
1154         found_user = getuser(&usbuf, who);
1155
1156         /* If not found, try it as an unqualified email address. */
1157         if (found_user != 0) {
1158                 strcpy(buf, who);
1159                 recp = validate_recipients(buf);
1160                 lprintf(CTDL_DEBUG, "Trying <%s>\n", buf);
1161                 if (recp != NULL) {
1162                         if (recp->num_local == 1) {
1163                                 found_user = getuser(&usbuf, recp->recp_local);
1164                         }
1165                         free(recp);
1166                 }
1167         }
1168
1169         /* If still not found, try it as an address qualified with the
1170          * primary FQDN of this Citadel node.
1171          */
1172         if (found_user != 0) {
1173                 snprintf(buf, sizeof buf, "%s@%s", who, config.c_fqdn);
1174                 lprintf(CTDL_DEBUG, "Trying <%s>\n", buf);
1175                 recp = validate_recipients(buf);
1176                 if (recp != NULL) {
1177                         if (recp->num_local == 1) {
1178                                 found_user = getuser(&usbuf, recp->recp_local);
1179                         }
1180                         free(recp);
1181                 }
1182         }
1183
1184         /* Still not found?  Try qualifying it with every domain we
1185          * might have addresses in.
1186          */
1187         if (found_user != 0) {
1188                 config_lines = num_tokens(inetcfg, '\n');
1189                 for (i=0; ((i < config_lines) && (found_user != 0)); ++i) {
1190                         extract_token(buf, inetcfg, i, '\n');
1191                         extract_token(host, buf, 0, '|');
1192                         extract_token(type, buf, 1, '|');
1193
1194                         if ( (!strcasecmp(type, "localhost"))
1195                            || (!strcasecmp(type, "directory")) ) {
1196                                 snprintf(buf, sizeof buf, "%s@%s", who, host);
1197                                 lprintf(CTDL_DEBUG, "Trying <%s>\n", buf);
1198                                 recp = validate_recipients(buf);
1199                                 if (recp != NULL) {
1200                                         if (recp->num_local == 1) {
1201                                                 found_user = getuser(&usbuf, recp->recp_local);
1202                                         }
1203                                         free(recp);
1204                                 }
1205                         }
1206                 }
1207         }
1208
1209         if (found_user != 0) {
1210                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1211                 return;
1212         }
1213
1214         MailboxName(calendar_room_name, sizeof calendar_room_name,
1215                 &usbuf, USERCALENDARROOM);
1216
1217         strcpy(hold_rm, CC->room.QRname);       /* save current room */
1218
1219         if (getroom(&CC->room, calendar_room_name) != 0) {
1220                 cprintf("%d Cannot open calendar\n", ERROR + ROOM_NOT_FOUND);
1221                 getroom(&CC->room, hold_rm);
1222                 return;
1223         }
1224
1225         /* Create a VFREEBUSY subcomponent */
1226         lprintf(CTDL_DEBUG, "Creating VFREEBUSY component\n");
1227         fb = icalcomponent_new_vfreebusy();
1228         if (fb == NULL) {
1229                 cprintf("%d Internal error: cannot allocate memory.\n",
1230                         ERROR + INTERNAL_ERROR);
1231                 icalcomponent_free(encaps);
1232                 getroom(&CC->room, hold_rm);
1233                 return;
1234         }
1235
1236         lprintf(CTDL_DEBUG, "Adding busy time from events\n");
1237         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
1238                 NULL, ical_freebusy_backend, (void *)fb
1239         );
1240
1241         /* Set the method to PUBLISH */
1242         icalcomponent_set_method(fb, ICAL_METHOD_PUBLISH);
1243
1244         /* Set the DTSTAMP to right now. */
1245         icalcomponent_set_dtstamp(fb, icaltime_from_timet(time(NULL), 0));
1246
1247         /* FIXME we still need (at least) DTSTART, DTEND, and the user's
1248          * e-mail address as ORGANIZER.
1249          */
1250
1251         /* Put the freebusy component into the calendar component */
1252         lprintf(CTDL_DEBUG, "Encapsulating\n");
1253         encaps = ical_encapsulate_subcomponent(fb);
1254         if (encaps == NULL) {
1255                 icalcomponent_free(fb);
1256                 cprintf("%d Internal error: cannot allocate memory.\n",
1257                         ERROR + INTERNAL_ERROR);
1258                 getroom(&CC->room, hold_rm);
1259                 return;
1260         }
1261
1262         /* Set the method to PUBLISH */
1263         lprintf(CTDL_DEBUG, "Setting method\n");
1264         icalcomponent_set_method(encaps, ICAL_METHOD_PUBLISH);
1265
1266         /* Serialize it */
1267         lprintf(CTDL_DEBUG, "Serializing\n");
1268         serialized_request = strdup(icalcomponent_as_ical_string(encaps));
1269         icalcomponent_free(encaps);     /* Don't need this anymore. */
1270
1271         cprintf("%d Here is the free/busy data:\n", LISTING_FOLLOWS);
1272         if (serialized_request != NULL) {
1273                 client_write(serialized_request, strlen(serialized_request));
1274                 free(serialized_request);
1275         }
1276         cprintf("\n000\n");
1277
1278         /* Go back to the room from which we came... */
1279         getroom(&CC->room, hold_rm);
1280 }
1281
1282
1283
1284
1285 /*
1286  * All Citadel calendar commands from the client come through here.
1287  */
1288 void cmd_ical(char *argbuf)
1289 {
1290         char subcmd[SIZ];
1291         long msgnum;
1292         char partnum[SIZ];
1293         char action[SIZ];
1294         char who[SIZ];
1295
1296         extract(subcmd, argbuf, 0);
1297
1298         /* Allow "test" and "freebusy" subcommands without logging in. */
1299
1300         if (!strcasecmp(subcmd, "test")) {
1301                 cprintf("%d This server supports calendaring\n", CIT_OK);
1302                 return;
1303         }
1304
1305         if (!strcasecmp(subcmd, "freebusy")) {
1306                 extract(who, argbuf, 1);
1307                 ical_freebusy(who);
1308                 return;
1309         }
1310
1311         if (!strcasecmp(subcmd, "sgi")) {
1312                 CIT_ICAL->server_generated_invitations =
1313                         (extract_int(argbuf, 1) ? 1 : 0) ;
1314                 cprintf("%d %d\n",
1315                         CIT_OK, CIT_ICAL->server_generated_invitations);
1316                 return;
1317         }
1318
1319         if (CtdlAccessCheck(ac_logged_in)) return;
1320
1321         if (!strcasecmp(subcmd, "respond")) {
1322                 msgnum = extract_long(argbuf, 1);
1323                 extract(partnum, argbuf, 2);
1324                 extract(action, argbuf, 3);
1325                 ical_respond(msgnum, partnum, action);
1326                 return;
1327         }
1328
1329         if (!strcasecmp(subcmd, "handle_rsvp")) {
1330                 msgnum = extract_long(argbuf, 1);
1331                 extract(partnum, argbuf, 2);
1332                 extract(action, argbuf, 3);
1333                 ical_handle_rsvp(msgnum, partnum, action);
1334                 return;
1335         }
1336
1337         if (!strcasecmp(subcmd, "conflicts")) {
1338                 msgnum = extract_long(argbuf, 1);
1339                 extract(partnum, argbuf, 2);
1340                 ical_conflicts(msgnum, partnum);
1341                 return;
1342         }
1343
1344         cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1345 }
1346
1347
1348
1349 /*
1350  * We don't know if the calendar room exists so we just create it at login
1351  */
1352 void ical_create_room(void)
1353 {
1354         struct ctdlroom qr;
1355         struct visit vbuf;
1356
1357         /* Create the calendar room if it doesn't already exist */
1358         create_room(USERCALENDARROOM, 4, "", 0, 1, 0);
1359
1360         /* Set expiration policy to manual; otherwise objects will be lost! */
1361         if (lgetroom(&qr, USERCALENDARROOM)) {
1362                 lprintf(CTDL_CRIT, "Couldn't get the user calendar room!\n");
1363                 return;
1364         }
1365         qr.QRep.expire_mode = EXPIRE_MANUAL;
1366         qr.QRdefaultview = 3;   /* 3 = calendar view */
1367         lputroom(&qr);
1368
1369         /* Set the view to a calendar view */
1370         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1371         vbuf.v_view = 3;        /* 3 = calendar */
1372         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1373
1374         /* Create the tasks list room if it doesn't already exist */
1375         create_room(USERTASKSROOM, 4, "", 0, 1, 0);
1376
1377         /* Set expiration policy to manual; otherwise objects will be lost! */
1378         if (lgetroom(&qr, USERTASKSROOM)) {
1379                 lprintf(CTDL_CRIT, "Couldn't get the user calendar room!\n");
1380                 return;
1381         }
1382         qr.QRep.expire_mode = EXPIRE_MANUAL;
1383         qr.QRdefaultview = 4;   /* 4 = tasks view */
1384         lputroom(&qr);
1385
1386         /* Set the view to a task list view */
1387         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1388         vbuf.v_view = 4;        /* 4 = tasks */
1389         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1390
1391         return;
1392 }
1393
1394
1395 /*
1396  * ical_send_out_invitations() is called by ical_saving_vevent() when it
1397  * finds a VEVENT.
1398  */
1399 void ical_send_out_invitations(icalcomponent *cal) {
1400         icalcomponent *the_request = NULL;
1401         char *serialized_request = NULL;
1402         icalcomponent *encaps = NULL;
1403         char *request_message_text = NULL;
1404         struct CtdlMessage *msg = NULL;
1405         struct recptypes *valid = NULL;
1406         char attendees_string[SIZ];
1407         int num_attendees = 0;
1408         char this_attendee[SIZ];
1409         icalproperty *attendee = NULL;
1410         char summary_string[SIZ];
1411         icalproperty *summary = NULL;
1412
1413         if (cal == NULL) {
1414                 lprintf(CTDL_ERR, "ERROR: trying to reply to NULL event?\n");
1415                 return;
1416         }
1417
1418
1419         /* If this is a VCALENDAR component, look for a VEVENT subcomponent. */
1420         if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
1421                 ical_send_out_invitations(
1422                         icalcomponent_get_first_component(
1423                                 cal, ICAL_VEVENT_COMPONENT
1424                         )
1425                 );
1426                 return;
1427         }
1428
1429         /* Clone the event */
1430         the_request = icalcomponent_new_clone(cal);
1431         if (the_request == NULL) {
1432                 lprintf(CTDL_ERR, "ERROR: cannot clone calendar object\n");
1433                 return;
1434         }
1435
1436         /* Extract the summary string -- we'll use it as the
1437          * message subject for the request
1438          */
1439         strcpy(summary_string, "Meeting request");
1440         summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
1441         if (summary != NULL) {
1442                 if (icalproperty_get_summary(summary)) {
1443                         strcpy(summary_string,
1444                                 icalproperty_get_summary(summary) );
1445                 }
1446         }
1447
1448         /* Determine who the recipients of this message are (the attendees) */
1449         strcpy(attendees_string, "");
1450         for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
1451                 if (icalproperty_get_attendee(attendee)) {
1452                         strcpy(this_attendee, icalproperty_get_attendee(attendee) );
1453                         if (!strncasecmp(this_attendee, "MAILTO:", 7)) {
1454                                 strcpy(this_attendee, &this_attendee[7]);
1455
1456                                 if (!CtdlIsMe(this_attendee)) { /* don't send an invitation to myself! */
1457                                         snprintf(&attendees_string[strlen(attendees_string)],
1458                                                 sizeof(attendees_string) - strlen(attendees_string),
1459                                                 "%s, ",
1460                                                 this_attendee
1461                                         );
1462                                         ++num_attendees;
1463                                 }
1464                         }
1465                 }
1466         }
1467
1468         lprintf(CTDL_DEBUG, "<%d> attendees: <%s>\n", num_attendees, attendees_string);
1469
1470         /* If there are no attendees, there are no invitations to send, so...
1471          * don't bother putting one together!  Punch out, Maverick!
1472          */
1473         if (num_attendees == 0) {
1474                 icalcomponent_free(the_request);
1475                 return;
1476         }
1477
1478         /* Encapsulate the VEVENT component into a complete VCALENDAR */
1479         encaps = icalcomponent_new_vcalendar();
1480         if (encaps == NULL) {
1481                 lprintf(CTDL_DEBUG, "Error at %s:%d - could not allocate component!\n",
1482                         __FILE__, __LINE__);
1483                 icalcomponent_free(the_request);
1484                 return;
1485         }
1486
1487         /* Set the Product ID */
1488         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1489
1490         /* Set the Version Number */
1491         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1492
1493         /* Set the method to REQUEST */
1494         icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
1495
1496         /* Now make sure all of the DTSTART and DTEND properties are UTC. */
1497         ical_dezonify(the_request);
1498
1499         /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
1500          * are responsible for "the_request"'s memory -- it will be freed
1501          * when we free "encaps".
1502          */
1503         icalcomponent_add_component(encaps, the_request);
1504
1505         /* Serialize it */
1506         serialized_request = strdup(icalcomponent_as_ical_string(encaps));
1507         icalcomponent_free(encaps);     /* Don't need this anymore. */
1508         if (serialized_request == NULL) return;
1509
1510         request_message_text = malloc(strlen(serialized_request) + SIZ);
1511         if (request_message_text != NULL) {
1512                 sprintf(request_message_text,
1513                         "Content-type: text/calendar\r\n\r\n%s\r\n",
1514                         serialized_request
1515                 );
1516
1517                 msg = CtdlMakeMessage(&CC->user,
1518                         "",                     /* No single recipient here */
1519                         CC->room.QRname, 0, FMT_RFC822,
1520                         "",
1521                         summary_string,         /* Use summary for subject */
1522                         request_message_text);
1523         
1524                 if (msg != NULL) {
1525                         valid = validate_recipients(attendees_string);
1526                         CtdlSubmitMsg(msg, valid, "");
1527                         CtdlFreeMessage(msg);
1528                 }
1529         }
1530         free(serialized_request);
1531 }
1532
1533
1534 /*
1535  * When a calendar object is being saved, determine whether it's a VEVENT
1536  * and the user saving it is the organizer.  If so, send out invitations
1537  * to any listed attendees.
1538  *
1539  */
1540 void ical_saving_vevent(icalcomponent *cal) {
1541         icalcomponent *c;
1542         icalproperty *organizer = NULL;
1543         char organizer_string[SIZ];
1544
1545         /* Don't send out invitations unless the client wants us to. */
1546         if (CIT_ICAL->server_generated_invitations == 0) {
1547                 return;
1548         }
1549
1550         /* Don't send out invitations if we've been asked not to. */
1551         if (CIT_ICAL->avoid_sending_invitations > 0) {
1552                 return;
1553         }
1554
1555         strcpy(organizer_string, "");
1556         /*
1557          * The VEVENT subcomponent is the one we're interested in.
1558          * Send out invitations if, and only if, this user is the Organizer.
1559          */
1560         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
1561                 organizer = icalcomponent_get_first_property(cal,
1562                                                 ICAL_ORGANIZER_PROPERTY);
1563                 if (organizer != NULL) {
1564                         if (icalproperty_get_organizer(organizer)) {
1565                                 strcpy(organizer_string,
1566                                         icalproperty_get_organizer(organizer));
1567                         }
1568                 }
1569                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
1570                         strcpy(organizer_string, &organizer_string[7]);
1571                         striplt(organizer_string);
1572                         /*
1573                          * If the user saving the event is listed as the
1574                          * organizer, then send out invitations.
1575                          */
1576                         if (CtdlIsMe(organizer_string)) {
1577                                 ical_send_out_invitations(cal);
1578                         }
1579                 }
1580         }
1581
1582         /* If the component has subcomponents, recurse through them. */
1583         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
1584             (c != NULL);
1585             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
1586                 /* Recursively process subcomponent */
1587                 ical_saving_vevent(c);
1588         }
1589
1590 }
1591
1592
1593
1594 /*
1595  * Back end for ical_obj_beforesave()
1596  * This hunts for the UID of the calendar event (becomes Citadel msg EUID),
1597  * the summary of the event (becomes message subject),
1598  * and the start time (becomes message date/time).
1599  */
1600 void ical_ctdl_set_extended_msgid(char *name, char *filename, char *partnum,
1601                 char *disp, void *content, char *cbtype, size_t length,
1602                 char *encoding, void *cbuserdata)
1603 {
1604         icalcomponent *cal;
1605         icalproperty *p;
1606         struct icalmessagemod *imm;
1607
1608         imm = (struct icalmessagemod *)cbuserdata;
1609
1610         /* If this is a text/calendar object, hunt for the UID and drop it in
1611          * the "user data" pointer for the MIME parser.  When
1612          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1613          * to that string.
1614          */
1615         if (!strcasecmp(cbtype, "text/calendar")) {
1616                 cal = icalcomponent_new_from_string(content);
1617                 if (cal != NULL) {
1618                         if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
1619                                 cal = icalcomponent_get_first_component(
1620                                         cal, ICAL_VEVENT_COMPONENT
1621                                 );
1622                         }
1623                 }
1624                 if (cal != NULL) {
1625                         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
1626                         if (p != NULL) {
1627                                 strcpy(imm->uid, icalproperty_get_comment(p));
1628                         }
1629                         p = ical_ctdl_get_subprop(cal, ICAL_SUMMARY_PROPERTY);
1630                         if (p != NULL) {
1631                                 strcpy(imm->subject,
1632                                                 icalproperty_get_comment(p));
1633                         }
1634                         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
1635                         if (p != NULL) {
1636                                 imm->dtstart = icaltime_as_timet(icalproperty_get_dtstart(p));
1637                         }
1638                         icalcomponent_free(cal);
1639                 }
1640         }
1641 }
1642
1643
1644
1645
1646
1647 /*
1648  * See if we need to prevent the object from being saved (we don't allow
1649  * MIME types other than text/calendar in the Calendar> room).  Also, when
1650  * saving an event to the calendar, set the message's Citadel extended message
1651  * ID to the UID of the object.  This causes our replication checker to
1652  * automatically delete any existing instances of the same object.  (Isn't
1653  * that cool?)
1654  *
1655  * We also set the message's Subject to the event summary, and the Date/time to
1656  * the event start time.
1657  */
1658 int ical_obj_beforesave(struct CtdlMessage *msg)
1659 {
1660         char roomname[ROOMNAMELEN];
1661         char *p;
1662         int a;
1663         struct icalmessagemod imm;
1664
1665         /*
1666          * Only messages with content-type text/calendar
1667          * may be saved to Calendar>.  If the message is bound for
1668          * Calendar> but doesn't have this content-type, throw an error
1669          * so that the message may not be posted.
1670          */
1671
1672         /* First determine if this is our room */
1673         MailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
1674         if (strcasecmp(roomname, CC->room.QRname)) {
1675                 return 0;       /* It's not the Calendar room. */
1676         }
1677
1678         /* Then determine content-type of the message */
1679         
1680         /* It must be an RFC822 message! */
1681         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1682         if (msg->cm_format_type != 4)
1683                 return 1;       /* You tried to save a non-RFC822 message! */
1684         
1685         /* Find the Content-Type: header */
1686         p = msg->cm_fields['M'];
1687         a = strlen(p);
1688         while (--a > 0) {
1689                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1690                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1691                                 memset(&imm, 0, sizeof(struct icalmessagemod));
1692                                 mime_parser(msg->cm_fields['M'],
1693                                         NULL,
1694                                         *ical_ctdl_set_extended_msgid,
1695                                         NULL, NULL,
1696                                         (void *)&imm,
1697                                         0
1698                                 );
1699                                 if (strlen(imm.uid) > 0) {
1700                                         if (msg->cm_fields['E'] != NULL) {
1701                                                 free(msg->cm_fields['E']);
1702                                         }
1703                                         msg->cm_fields['E'] = strdup(imm.uid);
1704                                 }
1705                                 if (strlen(imm.subject) > 0) {
1706                                         if (msg->cm_fields['U'] != NULL) {
1707                                                 free(msg->cm_fields['U']);
1708                                         }
1709                                         msg->cm_fields['U'] = strdup(imm.subject);
1710                                 }
1711                                 if (imm.dtstart > 0) {
1712                                         if (msg->cm_fields['T'] != NULL) {
1713                                                 free(msg->cm_fields['T']);
1714                                         }
1715                                         msg->cm_fields['T'] = strdup("000000000000000000");
1716                                         sprintf(msg->cm_fields['T'], "%ld", imm.dtstart);
1717                                 }
1718                                 return 0;
1719                         }
1720                         else {
1721                                 return 1;
1722                         }
1723                 }
1724                 p++;
1725         }
1726         
1727         /* Oops!  No Content-Type in this message!  How'd that happen? */
1728         lprintf(CTDL_ERR, "RFC822 message with no Content-Type header!\n");
1729         return 1;
1730 }
1731
1732
1733 /*
1734  * Things we need to do after saving a calendar event.
1735  */
1736 void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
1737                 char *disp, void *content, char *cbtype, size_t length,
1738                 char *encoding, void *cbuserdata)
1739 {
1740         icalcomponent *cal;
1741
1742         /* If this is a text/calendar object, hunt for the UID and drop it in
1743          * the "user data" pointer for the MIME parser.  When
1744          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1745          * to that string.
1746          */
1747         if (!strcasecmp(cbtype, "text/calendar")) {
1748                 cal = icalcomponent_new_from_string(content);
1749                 if (cal != NULL) {
1750                         ical_saving_vevent(cal);
1751                         icalcomponent_free(cal);
1752                 }
1753         }
1754 }
1755
1756
1757 /* 
1758  * Things we need to do after saving a calendar event.
1759  */
1760 int ical_obj_aftersave(struct CtdlMessage *msg)
1761 {
1762         char roomname[ROOMNAMELEN];
1763         char *p;
1764         int a;
1765
1766         /*
1767          * If this isn't the Calendar> room, no further action is necessary.
1768          */
1769
1770         /* First determine if this is our room */
1771         MailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
1772         if (strcasecmp(roomname, CC->room.QRname)) {
1773                 return 0;       /* It's not the Calendar room. */
1774         }
1775
1776         /* Then determine content-type of the message */
1777         
1778         /* It must be an RFC822 message! */
1779         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1780         if (msg->cm_format_type != 4) return(1);
1781         
1782         /* Find the Content-Type: header */
1783         p = msg->cm_fields['M'];
1784         a = strlen(p);
1785         while (--a > 0) {
1786                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1787                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1788                                 mime_parser(msg->cm_fields['M'],
1789                                         NULL,
1790                                         *ical_obj_aftersave_backend,
1791                                         NULL, NULL,
1792                                         NULL,
1793                                         0
1794                                 );
1795                                 return 0;
1796                         }
1797                         else {
1798                                 return 1;
1799                         }
1800                 }
1801                 p++;
1802         }
1803         
1804         /* Oops!  No Content-Type in this message!  How'd that happen? */
1805         lprintf(CTDL_ERR, "RFC822 message with no Content-Type header!\n");
1806         return 1;
1807 }
1808
1809
1810 void ical_session_startup(void) {
1811         CtdlAllocUserData(SYM_CIT_ICAL, sizeof(struct cit_ical));
1812         memset(CIT_ICAL, 0, sizeof(struct cit_ical));
1813 }
1814
1815
1816 #endif  /* CITADEL_WITH_CALENDAR_SERVICE */
1817
1818 /*
1819  * Register this module with the Citadel server.
1820  */
1821 char *serv_calendar_init(void)
1822 {
1823 #ifdef CITADEL_WITH_CALENDAR_SERVICE
1824         CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
1825         CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
1826         CtdlRegisterSessionHook(ical_create_room, EVT_LOGIN);
1827         CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCal commands");
1828         CtdlRegisterSessionHook(ical_session_startup, EVT_START);
1829 #endif
1830         return "$Id$";
1831 }