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