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