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