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