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