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