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