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