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