2689056eb97a6bd54fcb8fac35aa9c1cbe3754d0
[citadel.git] / citadel / serv_vcard.c
1 /*
2  * $Id$
3  * 
4  * A server-side module for Citadel which supports address book information
5  * using the standard vCard format.
6  * 
7  * Copyright (c) 1999-2002 / released under the GNU General Public License
8  */
9
10 /*
11  * Where we keep messages containing the vCards that source our directory.  It
12  * makes no sense to change this, because you'd have to change it on every
13  * system on the network.  That would be stupid.
14  */
15 #define ADDRESS_BOOK_ROOM       "Global Address Book"
16
17 /*
18  * Format of the "Extended ID" field of the message containing a user's
19  * vCard.  Doesn't matter what it really looks like as long as it's both
20  * unique and consistent (because we use it for replication checking to
21  * delete the old vCard network-wide when the user enters a new one).
22  */
23 #define VCARD_EXT_FORMAT        "Citadel vCard: personal card for %s at %s"
24
25
26 #include "sysdep.h"
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <pwd.h>
33 #include <errno.h>
34 #include <sys/types.h>
35
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
38 # include <time.h>
39 #else
40 # if HAVE_SYS_TIME_H
41 #  include <sys/time.h>
42 # else
43 #  include <time.h>
44 # endif
45 #endif
46
47 #include <sys/wait.h>
48 #include <string.h>
49 #include <limits.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "sysdep_decls.h"
53 #include "citserver.h"
54 #include "support.h"
55 #include "config.h"
56 #include "control.h"
57 #include "serv_extensions.h"
58 #include "room_ops.h"
59 #include "user_ops.h"
60 #include "policy.h"
61 #include "database.h"
62 #include "msgbase.h"
63 #include "internet_addressing.h"
64 #include "tools.h"
65 #include "vcard.h"
66 #include "serv_ldap.h"
67
68 struct vcard_internal_info {
69         long msgnum;
70 };
71
72 /* Message number symbol used internally by these functions */
73 #define VC ((struct vcard_internal_info *)CtdlGetUserData(SYM_VCARD))
74
75
76 /*
77  * set global flag calling for an aide to validate new users
78  */
79 void set_mm_valid(void) {
80         begin_critical_section(S_CONTROL);
81         get_control();
82         CitControl.MMflags = CitControl.MMflags | MM_VALID ;
83         put_control();
84         end_critical_section(S_CONTROL);
85 }
86
87
88
89 /*
90  * Extract Internet e-mail addresses from a message containing a vCard, and
91  * perform a callback for any found.
92  */
93 void vcard_extract_internet_addresses(struct CtdlMessage *msg,
94                                 void (*callback)(char *, char *) ) {
95         struct vCard *v;
96         char *s;
97         char *addr;
98         char citadel_address[SIZ];
99         int instance = 0;
100         int found_something = 0;
101
102         if (msg->cm_fields['A'] == NULL) return;
103         if (msg->cm_fields['N'] == NULL) return;
104         snprintf(citadel_address, sizeof citadel_address, "%s @ %s",
105                 msg->cm_fields['A'], msg->cm_fields['N']);
106
107         v = vcard_load(msg->cm_fields['M']);
108         if (v == NULL) return;
109
110         /* Go through the vCard searching for *all* instances of
111          * the "email;internet" key
112          */
113         do {
114                 s = vcard_get_prop(v, "email;internet", 0, instance++, 0);
115                 if (s != NULL) {
116                         addr = strdoop(s);
117                         striplt(addr);
118                         if (strlen(addr) > 0) {
119                                 if (callback != NULL) {
120                                         callback(addr, citadel_address);
121                                 }
122                         }
123                         phree(addr);
124                         found_something = 1;
125                 }
126                 else {
127                         found_something = 0;
128                 }
129         } while(found_something);
130
131         vcard_free(v);
132 }
133
134
135
136 /*
137  * Callback for vcard_add_to_directory()
138  * (Lotsa ugly nested callbacks.  Oh well.)
139  * This little shim function makes sure we're not 
140  */
141 void vcard_directory_add_user(char *internet_addr, char *citadel_addr) {
142         char buf[SIZ];
143
144         /* We have to validate that we're not stepping on someone else's
145          * email address ... but only if we're logged in.  Otherwise it's
146          * probably just the networker or something.
147          */
148         if (CC->logged_in) {
149                 lprintf(CTDL_DEBUG, "Checking for <%s>...\n", internet_addr);
150                 if (CtdlDirectoryLookup(buf, internet_addr) == 0) {
151                         if (strcasecmp(buf, citadel_addr)) {
152                                 /* This address belongs to someone else.
153                                  * Bail out silently without saving.
154                                  */
155                                 lprintf(CTDL_DEBUG, "DOOP!\n");
156                                 return;
157                         }
158                 }
159         }
160         lprintf(CTDL_INFO, "Adding %s (%s) to directory\n",
161                         citadel_addr, internet_addr);
162         CtdlDirectoryAddUser(internet_addr, citadel_addr);
163 }
164
165
166 /*
167  * Back end function for cmd_igab()
168  */
169 void vcard_add_to_directory(long msgnum, void *data) {
170         struct CtdlMessage *msg;
171
172         msg = CtdlFetchMessage(msgnum);
173         if (msg != NULL) {
174                 vcard_extract_internet_addresses(msg, vcard_directory_add_user);
175         }
176
177 #ifdef HAVE_LDAP
178         ctdl_vcard_to_ldap(msg, V2L_WRITE);
179 #endif
180
181         CtdlFreeMessage(msg);
182 }
183
184
185 /*
186  * Initialize Global Adress Book
187  */
188 void cmd_igab(char *argbuf) {
189         char hold_rm[ROOMNAMELEN];
190
191         if (CtdlAccessCheck(ac_aide)) return;
192
193         strcpy(hold_rm, CC->room.QRname);       /* save current room */
194
195         if (getroom(&CC->room, ADDRESS_BOOK_ROOM) != 0) {
196                 getroom(&CC->room, hold_rm);
197                 cprintf("%d cannot get address book room\n", ERROR + ROOM_NOT_FOUND);
198                 return;
199         }
200
201         /* Empty the existing database first.
202          */
203         CtdlDirectoryInit();
204
205         /* We want *all* vCards in this room */
206         CtdlForEachMessage(MSGS_ALL, 0, "text/x-vcard",
207                 NULL, vcard_add_to_directory, NULL);
208
209         getroom(&CC->room, hold_rm);    /* return to saved room */
210         cprintf("%d Directory has been rebuilt.\n", CIT_OK);
211 }
212
213
214
215
216 /*
217  * See if there is a valid Internet address in a vCard to use for outbound
218  * Internet messages.  If there is, stick it in CC->cs_inet_email.
219  */
220 void vcard_populate_cs_inet_email(struct vCard *v) {
221         char *s, *addr;
222         int continue_searching = 1;
223         int instance = 0;
224
225         /* Go through the vCard searching for *all* instances of
226          * the "email;internet" key
227          */
228         do {
229                 s = vcard_get_prop(v, "email;internet", 0, instance++, 0);
230                 if (s != NULL) {
231                         continue_searching = 1;
232                         addr = strdoop(s);
233                         striplt(addr);
234                         if (strlen(addr) > 0) {
235                                 if (IsDirectory(addr)) {
236                                         continue_searching = 0;
237                                         safestrncpy(CC->cs_inet_email,
238                                                 addr,
239                                                 sizeof(CC->cs_inet_email)
240                                         );
241                                 }
242                         }
243                         phree(addr);
244                 }
245                 else {
246                         continue_searching = 0;
247                 }
248         } while(continue_searching);
249 }
250
251
252
253 /*
254  * This handler detects whether the user is attempting to save a new
255  * vCard as part of his/her personal configuration, and handles the replace
256  * function accordingly (delete the user's existing vCard in the config room
257  * and in the global address book).
258  */
259 int vcard_upload_beforesave(struct CtdlMessage *msg) {
260         char *ptr;
261         int linelen;
262         char buf[SIZ];
263         struct ctdluser usbuf;
264         long what_user;
265
266         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
267
268         /* If this isn't a "My Citadel Config" room, don't bother. */
269         if ( (CC->room.QRflags && QR_MAILBOX)
270            && (!strcasecmp(&CC->room.QRname[11], USERCONFIGROOM)) ) {
271                 /* Yes, we want to do this */
272         }
273         else {
274                 return(0);
275         }
276
277         /* If this isn't a MIME message, don't bother. */
278         if (msg->cm_format_type != 4) return(0);
279
280         /* Ok, if we got this far, look into the situation further... */
281
282         ptr = msg->cm_fields['M'];
283         if (ptr == NULL) return(0);
284         while (ptr != NULL) {
285         
286                 linelen = strcspn(ptr, "\n");
287                 if (linelen == 0) return(0);    /* end of headers */    
288                 
289                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
290                         /* Bingo!  The user is uploading a new vCard, so
291                          * delete the old one.  First, figure out which user
292                          * is being re-registered...
293                          */
294                         what_user = atol(CC->room.QRname);
295
296                         if (what_user == CC->user.usernum) {
297                                 /* It's the logged in user.  That was easy. */
298                                 memcpy(&usbuf, &CC->user,
299                                         sizeof(struct ctdluser) );
300                         }
301                         
302                         else if (getuserbynumber(&usbuf, what_user) == 0) {
303                                 /* We fetched a valid user record */
304                         }
305                 
306                         else {
307                                 /* No user with that number! */
308                                 return(0);
309                         }
310
311                         /* Delete the user's old vCard.  This would probably
312                          * get taken care of by the replication check, but we
313                          * want to make sure there is absolutely only one
314                          * vCard in the user's config room at all times.
315                          */
316                         CtdlDeleteMessages(CC->room.QRname,
317                                         0L, "text/x-vcard");
318
319                         /* Set the Extended-ID to a standardized one so the
320                          * replication always works correctly
321                          */
322                         if (msg->cm_fields['E'] != NULL)
323                                 phree(msg->cm_fields['E']);
324
325                         if (msg->cm_fields['A'] != NULL)
326                                 phree(msg->cm_fields['A']);
327
328                         msg->cm_fields['A'] = strdoop(usbuf.fullname);
329
330                         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
331                                 msg->cm_fields['A'], NODENAME);
332                         msg->cm_fields['E'] = strdoop(buf);
333
334                         /* Now allow the save to complete. */
335                         return(0);
336                 }
337
338                 ptr = strchr((char *)ptr, '\n');
339                 if (ptr != NULL) ++ptr;
340         }
341
342         return(0);
343 }
344
345
346
347 /*
348  * This handler detects whether the user is attempting to save a new
349  * vCard as part of his/her personal configuration, and handles the replace
350  * function accordingly (copy the vCard from the config room to the global
351  * address book).
352  */
353 int vcard_upload_aftersave(struct CtdlMessage *msg) {
354         char *ptr;
355         int linelen;
356         long I;
357         struct vCard *v;
358
359         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
360
361         /* If this isn't the configuration room, or if this isn't a MIME
362          * message, don't bother.
363          */
364         if (msg->cm_fields['O'] == NULL) return(0);
365         if (strcasecmp(msg->cm_fields['O'], USERCONFIGROOM)) return(0);
366         if (msg->cm_format_type != 4) return(0);
367
368         ptr = msg->cm_fields['M'];
369         if (ptr == NULL) return(0);
370         while (ptr != NULL) {
371         
372                 linelen = strcspn(ptr, "\n");
373                 if (linelen == 0) return(0);    /* end of headers */    
374                 
375                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
376                         /* Bingo!  The user is uploading a new vCard, so
377                          * copy it to the Global Address Book room.
378                          */
379
380                         I = atol(msg->cm_fields['I']);
381                         if (I < 0L) return(0);
382
383                         /* Put it in the Global Address Book room... */
384                         CtdlSaveMsgPointerInRoom(ADDRESS_BOOK_ROOM, I,
385                                 (SM_VERIFY_GOODNESS | SM_DO_REPL_CHECK) );
386
387                         /* ...and also in the directory database. */
388                         vcard_add_to_directory(I, NULL);
389
390                         /* Store our Internet return address in memory */
391                         v = vcard_load(msg->cm_fields['M']);
392                         vcard_populate_cs_inet_email(v);
393                         vcard_free(v);
394
395                         /* Some sites want an Aide to be notified when a
396                          * user registers or re-registers...
397                          */
398                         set_mm_valid();
399
400                         /* ...which also means we need to flag the user */
401                         lgetuser(&CC->user, CC->curr_user);
402                         CC->user.flags |= (US_REGIS|US_NEEDVALID);
403                         lputuser(&CC->user);
404
405                         return(0);
406                 }
407
408                 ptr = strchr((char *)ptr, '\n');
409                 if (ptr != NULL) ++ptr;
410         }
411
412         return(0);
413 }
414
415
416
417 /*
418  * back end function used for callbacks
419  */
420 void vcard_gu_backend(long msgnum, void *userdata) {
421         VC->msgnum = msgnum;
422 }
423
424
425 /*
426  * If this user has a vcard on disk, read it into memory, otherwise allocate
427  * and return an empty vCard.
428  */
429 struct vCard *vcard_get_user(struct ctdluser *u) {
430         char hold_rm[ROOMNAMELEN];
431         char config_rm[ROOMNAMELEN];
432         struct CtdlMessage *msg;
433         struct vCard *v;
434
435         strcpy(hold_rm, CC->room.QRname);       /* save current room */
436         MailboxName(config_rm, sizeof config_rm, u, USERCONFIGROOM);
437
438         if (getroom(&CC->room, config_rm) != 0) {
439                 getroom(&CC->room, hold_rm);
440                 return vcard_new();
441         }
442
443         /* We want the last (and probably only) vcard in this room */
444         VC->msgnum = (-1);
445         CtdlForEachMessage(MSGS_LAST, 1, "text/x-vcard",
446                 NULL, vcard_gu_backend, NULL);
447         getroom(&CC->room, hold_rm);    /* return to saved room */
448
449         if (VC->msgnum < 0L) return vcard_new();
450
451         msg = CtdlFetchMessage(VC->msgnum);
452         if (msg == NULL) return vcard_new();
453
454         v = vcard_load(msg->cm_fields['M']);
455         CtdlFreeMessage(msg);
456         return v;
457 }
458
459
460 /*
461  * Store this user's vCard in the appropriate place
462  */
463 /*
464  * Write our config to disk
465  */
466 void vcard_write_user(struct ctdluser *u, struct vCard *v) {
467         char temp[PATH_MAX];
468         FILE *fp;
469         char *ser;
470
471         strcpy(temp, tmpnam(NULL));
472         ser = vcard_serialize(v);
473
474         fp = fopen(temp, "w");
475         if (fp == NULL) return;
476         if (ser == NULL) {
477                 fprintf(fp, "begin:vcard\r\nend:vcard\r\n");
478         } else {
479                 fwrite(ser, strlen(ser), 1, fp);
480                 phree(ser);
481         }
482         fclose(fp);
483
484         /* This handy API function does all the work for us.
485          * NOTE: normally we would want to set that last argument to 1, to
486          * force the system to delete the user's old vCard.  But it doesn't
487          * have to, because the vcard_upload_beforesave() hook above
488          * is going to notice what we're trying to do, and delete the old vCard.
489          */
490         CtdlWriteObject(USERCONFIGROOM, /* which room */
491                         "text/x-vcard", /* MIME type */
492                         temp,           /* temp file */
493                         u,              /* which user */
494                         0,              /* not binary */
495                         0,              /* don't delete others of this type */
496                         0);             /* no flags */
497
498         unlink(temp);
499 }
500
501
502
503 /*
504  * Old style "enter registration info" command.  This function simply honors
505  * the REGI protocol command, translates the entered parameters into a vCard,
506  * and enters the vCard into the user's configuration.
507  */
508 void cmd_regi(char *argbuf) {
509         int a,b,c;
510         char buf[SIZ];
511         struct vCard *my_vcard;
512
513         char tmpaddr[SIZ];
514         char tmpcity[SIZ];
515         char tmpstate[SIZ];
516         char tmpzip[SIZ];
517         char tmpaddress[SIZ];
518         char tmpcountry[SIZ];
519
520         if (!(CC->logged_in)) {
521                 cprintf("%d Not logged in.\n",ERROR + NOT_LOGGED_IN);
522                 return;
523         }
524
525         my_vcard = vcard_get_user(&CC->user);
526         strcpy(tmpaddr, "");
527         strcpy(tmpcity, "");
528         strcpy(tmpstate, "");
529         strcpy(tmpzip, "");
530         strcpy(tmpcountry, "USA");
531
532         cprintf("%d Send registration...\n", SEND_LISTING);
533         a=0;
534         while (client_gets(buf), strcmp(buf,"000")) {
535                 if (a==0) vcard_set_prop(my_vcard, "n", buf, 0);
536                 if (a==1) strcpy(tmpaddr, buf);
537                 if (a==2) strcpy(tmpcity, buf);
538                 if (a==3) strcpy(tmpstate, buf);
539                 if (a==4) {
540                         for (c=0; c<strlen(buf); ++c) {
541                                 if ((buf[c]>='0') && (buf[c]<='9')) {
542                                         b = strlen(tmpzip);
543                                         tmpzip[b] = buf[c];
544                                         tmpzip[b+1] = 0;
545                                 }
546                         }
547                 }
548                 if (a==5) vcard_set_prop(my_vcard, "tel;home", buf, 0);
549                 if (a==6) vcard_set_prop(my_vcard, "email;internet", buf, 0);
550                 if (a==7) strcpy(tmpcountry, buf);
551                 ++a;
552         }
553
554         snprintf(tmpaddress, sizeof tmpaddress, ";;%s;%s;%s;%s;%s",
555                 tmpaddr, tmpcity, tmpstate, tmpzip, tmpcountry);
556         vcard_set_prop(my_vcard, "adr", tmpaddress, 0);
557         vcard_write_user(&CC->user, my_vcard);
558         vcard_free(my_vcard);
559 }
560
561
562 /*
563  * Protocol command to fetch registration info for a user
564  */
565 void cmd_greg(char *argbuf)
566 {
567         struct ctdluser usbuf;
568         struct vCard *v;
569         char *s;
570         char who[SIZ];
571         char adr[SIZ];
572         char buf[SIZ];
573
574         extract(who, argbuf, 0);
575
576         if (!(CC->logged_in)) {
577                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
578                 return;
579         }
580
581         if (!strcasecmp(who,"_SELF_")) strcpy(who,CC->curr_user);
582
583         if ((CC->user.axlevel < 6) && (strcasecmp(who,CC->curr_user))) {
584                 cprintf("%d Higher access required.\n",
585                         ERROR + HIGHER_ACCESS_REQUIRED);
586                 return;
587         }
588
589         if (getuser(&usbuf, who) != 0) {
590                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, who);
591                 return;
592         }
593
594         v = vcard_get_user(&usbuf);
595
596         cprintf("%d %s\n", LISTING_FOLLOWS, usbuf.fullname);
597         cprintf("%ld\n", usbuf.usernum);
598         cprintf("%s\n", usbuf.password);
599         s = vcard_get_prop(v, "n", 0, 0, 0);
600         cprintf("%s\n", s ? s : " ");   /* name */
601
602         s = vcard_get_prop(v, "adr", 0, 0, 0);
603         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
604
605         extract_token(buf, adr, 2, ';');
606         cprintf("%s\n", buf);                           /* street */
607         extract_token(buf, adr, 3, ';');
608         cprintf("%s\n", buf);                           /* city */
609         extract_token(buf, adr, 4, ';');
610         cprintf("%s\n", buf);                           /* state */
611         extract_token(buf, adr, 5, ';');
612         cprintf("%s\n", buf);                           /* zip */
613
614         s = vcard_get_prop(v, "tel;home", 0, 0, 0);
615         if (s == NULL) s = vcard_get_prop(v, "tel", 1, 0, 0);
616         if (s != NULL) {
617                 cprintf("%s\n", s);
618         }
619         else {
620                 cprintf(" \n");
621         }
622
623         cprintf("%d\n", usbuf.axlevel);
624
625         s = vcard_get_prop(v, "email;internet", 0, 0, 0);
626         cprintf("%s\n", s ? s : " ");
627         s = vcard_get_prop(v, "adr", 0, 0, 0);
628         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
629
630         extract_token(buf, adr, 6, ';');
631         cprintf("%s\n", buf);                           /* country */
632         cprintf("000\n");
633 }
634
635
636 /*
637  * When a user is being created, create his/her vCard.
638  */
639 void vcard_newuser(struct ctdluser *usbuf) {
640         char buf[SIZ];
641         char vname[SIZ];
642
643         char lastname[SIZ];
644         char firstname[SIZ];
645         char middlename[SIZ];
646         char honorific_prefixes[SIZ];
647         char honorific_suffixes[SIZ];
648
649         struct vCard *v;
650         int i;
651
652         /* Try to intelligently convert the screen name to a
653          * fully expanded vCard name based on the number of
654          * words in the name
655          */
656         strcpy(lastname, "");
657         strcpy(firstname, "");
658         strcpy(middlename, "");
659         strcpy(honorific_prefixes, "");
660         strcpy(honorific_suffixes, "");
661
662         strcpy(buf, usbuf->fullname);
663
664         /* Honorific suffixes */
665         if (num_tokens(buf, ',') > 1) {
666                 extract_token(honorific_suffixes, buf, (num_tokens(buf, ' ') - 1), ',');
667                 remove_token(buf, (num_tokens(buf, ',') - 1), ',');
668         }
669
670         /* Find a last name */
671         extract_token(lastname, buf, (num_tokens(buf, ' ') - 1), ' ');
672         remove_token(buf, (num_tokens(buf, ' ') - 1), ' ');
673
674         /* Find honorific prefixes */
675         if (num_tokens(buf, ' ') > 2) {
676                 extract_token(honorific_prefixes, buf, 0, ' ');
677                 remove_token(buf, 0, ' ');
678         }
679
680         /* Find a middle name */
681         if (num_tokens(buf, ' ') > 1) {
682                 extract_token(middlename, buf, (num_tokens(buf, ' ') - 1), ' ');
683                 remove_token(buf, (num_tokens(buf, ' ') - 1), ' ');
684         }
685
686         /* Anything left is probably the first name */
687         strcpy(firstname, buf);
688         striplt(firstname);
689
690         /* Compose the structured name */
691         sprintf(vname, "%s;%s;%s;%s;%s", lastname, firstname, middlename,
692                 honorific_prefixes, honorific_suffixes);
693
694         lprintf(CTDL_DEBUG, "Converted <%s> to <%s>\n", usbuf->fullname, vname);
695
696         /* Create and save the vCard */
697         v = vcard_new();
698         if (v == NULL) return;
699         sprintf(buf, "%s@%s", usbuf->fullname, config.c_fqdn);
700         for (i=0; i<strlen(buf); ++i) {
701                 if (buf[i] == ' ') buf[i] = '_';
702         }
703         vcard_add_prop(v, "fn", usbuf->fullname);
704         vcard_add_prop(v, "n", vname);
705         vcard_add_prop(v, "email;internet", buf);
706         vcard_write_user(usbuf, v);
707         vcard_free(v);
708 }
709
710
711 /*
712  * When a user is being deleted, we have to remove his/her vCard.
713  * This is accomplished by issuing a message with 'CANCEL' in the S (special)
714  * field, and the same Extended ID as the existing card.
715  */
716 void vcard_purge(struct ctdluser *usbuf) {
717         struct CtdlMessage *msg;
718         char buf[SIZ];
719
720         msg = (struct CtdlMessage *) mallok(sizeof(struct CtdlMessage));
721         if (msg == NULL) return;
722         memset(msg, 0, sizeof(struct CtdlMessage));
723
724         msg->cm_magic = CTDLMESSAGE_MAGIC;
725         msg->cm_anon_type = MES_NORMAL;
726         msg->cm_format_type = 0;
727         msg->cm_fields['A'] = strdoop(usbuf->fullname);
728         msg->cm_fields['O'] = strdoop(ADDRESS_BOOK_ROOM);
729         msg->cm_fields['N'] = strdoop(NODENAME);
730         msg->cm_fields['M'] = strdoop("Purge this vCard\n");
731
732         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
733                         msg->cm_fields['A'], NODENAME);
734         msg->cm_fields['E'] = strdoop(buf);
735
736         msg->cm_fields['S'] = strdoop("CANCEL");
737
738         CtdlSubmitMsg(msg, NULL, ADDRESS_BOOK_ROOM);
739         CtdlFreeMessage(msg);
740 }
741
742
743 /*
744  * Grab vCard directory stuff out of incoming network messages
745  */
746 int vcard_extract_from_network(struct CtdlMessage *msg, char *target_room) {
747         char *ptr;
748         int linelen;
749
750         if (msg == NULL) return(0);
751
752         if (strcasecmp(target_room, ADDRESS_BOOK_ROOM)) {
753                 return(0);
754         }
755
756         if (msg->cm_format_type != 4) return(0);
757
758         ptr = msg->cm_fields['M'];
759         if (ptr == NULL) return(0);
760         while (ptr != NULL) {
761         
762                 linelen = strcspn(ptr, "\n");
763                 if (linelen == 0) return(0);    /* end of headers */    
764                 
765                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
766                          /* It's a vCard.  Add it to the directory. */
767                         vcard_extract_internet_addresses(msg,
768                                                         CtdlDirectoryAddUser);
769                         return(0);
770                 }
771
772                 ptr = strchr((char *)ptr, '\n');
773                 if (ptr != NULL) ++ptr;
774         }
775
776         return(0);
777 }
778
779
780
781 /* 
782  * When a vCard is being removed from the Global Address Book room, remove it
783  * from the directory as well.
784  */
785 void vcard_delete_remove(char *room, long msgnum) {
786         struct CtdlMessage *msg;
787         char *ptr;
788         int linelen;
789
790         if (msgnum <= 0L) return;
791
792         if (strcasecmp(room, ADDRESS_BOOK_ROOM)) {
793                 return;
794         }
795
796         msg = CtdlFetchMessage(msgnum);
797         if (msg == NULL) return;
798
799         ptr = msg->cm_fields['M'];
800         if (ptr == NULL) goto EOH;
801         while (ptr != NULL) {
802                 linelen = strcspn(ptr, "\n");
803                 if (linelen == 0) goto EOH;
804                 
805                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
806                         /* Bingo!  A vCard is being deleted.
807                         */
808                         vcard_extract_internet_addresses(msg,
809                                                         CtdlDirectoryDelUser);
810 #ifdef HAVE_LDAP
811                         ctdl_vcard_to_ldap(msg, V2L_DELETE);
812 #endif
813                 }
814                 ptr = strchr((char *)ptr, '\n');
815                 if (ptr != NULL) ++ptr;
816         }
817
818 EOH:    CtdlFreeMessage(msg);
819 }
820
821
822
823 /*
824  * Query Directory
825  */
826 void cmd_qdir(char *argbuf) {
827         char citadel_addr[SIZ];
828         char internet_addr[SIZ];
829
830         if (CtdlAccessCheck(ac_logged_in)) return;
831
832         extract(internet_addr, argbuf, 0);
833
834         if (CtdlDirectoryLookup(citadel_addr, internet_addr) != 0) {
835                 cprintf("%d %s was not found.\n",
836                         ERROR + NO_SUCH_USER, internet_addr);
837                 return;
838         }
839
840         cprintf("%d %s\n", CIT_OK, citadel_addr);
841 }
842
843
844 /*
845  * We don't know if the Contacts room exists so we just create it at login
846  */
847 void vcard_create_room(void)
848 {
849         struct ctdlroom qr;
850         struct visit vbuf;
851
852         /* Create the calendar room if it doesn't already exist */
853         create_room(USERCONTACTSROOM, 4, "", 0, 1, 0);
854
855         /* Set expiration policy to manual; otherwise objects will be lost! */
856         if (lgetroom(&qr, USERCONTACTSROOM)) {
857                 lprintf(CTDL_ERR, "Couldn't get the user CONTACTS room!\n");
858                 return;
859         }
860         qr.QRep.expire_mode = EXPIRE_MANUAL;
861         qr.QRdefaultview = 2;   /* 2 = address book view */
862         lputroom(&qr);
863
864         /* Set the view to a calendar view */
865         CtdlGetRelationship(&vbuf, &CC->user, &qr);
866         vbuf.v_view = 2;        /* 2 = address book view */
867         CtdlSetRelationship(&vbuf, &CC->user, &qr);
868
869         return;
870 }
871
872
873
874
875 /*
876  * Session startup, allocate some per-session data
877  */
878 void vcard_session_startup_hook(void) {
879         CtdlAllocUserData(SYM_VCARD, sizeof(struct vcard_internal_info));
880 }
881
882
883 /*
884  * When a user logs in...
885  */
886 void vcard_session_login_hook(void) {
887         struct vCard *v;
888
889         v = vcard_get_user(&CC->user);
890         vcard_populate_cs_inet_email(v);
891
892         vcard_free(v);
893
894         vcard_create_room();
895 }
896
897
898
899 char *serv_vcard_init(void)
900 {
901         struct ctdlroom qr;
902
903         CtdlRegisterSessionHook(vcard_session_startup_hook, EVT_START);
904         CtdlRegisterSessionHook(vcard_session_login_hook, EVT_LOGIN);
905         CtdlRegisterMessageHook(vcard_upload_beforesave, EVT_BEFORESAVE);
906         CtdlRegisterMessageHook(vcard_upload_aftersave, EVT_AFTERSAVE);
907         CtdlRegisterDeleteHook(vcard_delete_remove);
908         CtdlRegisterProtoHook(cmd_regi, "REGI", "Enter registration info");
909         CtdlRegisterProtoHook(cmd_greg, "GREG", "Get registration info");
910         CtdlRegisterProtoHook(cmd_igab, "IGAB",
911                                         "Initialize Global Address Book");
912         CtdlRegisterProtoHook(cmd_qdir, "QDIR", "Query Directory");
913         CtdlRegisterUserHook(vcard_newuser, EVT_NEWUSER);
914         CtdlRegisterUserHook(vcard_purge, EVT_PURGEUSER);
915         CtdlRegisterNetprocHook(vcard_extract_from_network);
916
917         /* Create the Global ADdress Book room if necessary */
918         create_room(ADDRESS_BOOK_ROOM, 3, "", 0, 1, 0);
919
920         /* Set expiration policy to manual; otherwise objects will be lost! */
921         if (!lgetroom(&qr, ADDRESS_BOOK_ROOM)) {
922                 qr.QRep.expire_mode = EXPIRE_MANUAL;
923                 qr.QRdefaultview = 2;   /* 2 = address book view */
924                 lputroom(&qr);
925         }
926
927         return "$Id$";
928 }