b82ffbf9432c1dc15056d1b675833436535fa1f3
[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 = strdup(s);
117                         striplt(addr);
118                         if (strlen(addr) > 0) {
119                                 if (callback != NULL) {
120                                         callback(addr, citadel_address);
121                                 }
122                         }
123                         free(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, 1);
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 = strdup(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                         free(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         char *s;
262         int linelen;
263         char buf[SIZ];
264         struct ctdluser usbuf;
265         long what_user;
266         struct vCard *v = NULL;
267         char *ser = NULL;
268         int i = 0;
269         int yes_my_citadel_config = 0;
270         int yes_any_vcard_room = 0;
271
272         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
273
274         /* Is this some user's "My Citadel Config" room? */
275         if ( (CC->room.QRflags && QR_MAILBOX)
276            && (!strcasecmp(&CC->room.QRname[11], USERCONFIGROOM)) ) {
277                 /* Yes, we want to do this */
278                 yes_my_citadel_config = 1;
279         }
280
281         /* Is this a room with an address book in it? */
282         if (CC->curr_view == VIEW_ADDRESSBOOK) {
283                 yes_any_vcard_room = 1;
284         }
285
286         /* If neither condition exists, don't run this hook. */
287         if ( (!yes_my_citadel_config) && (!yes_any_vcard_room) ) {
288                 return(0);
289         }
290
291         /* If this isn't a MIME message, don't bother. */
292         if (msg->cm_format_type != 4) return(0);
293
294         /* Ok, if we got this far, look into the situation further... */
295
296         ptr = msg->cm_fields['M'];
297         if (ptr == NULL) return(0);
298         while (ptr != NULL) {
299         
300                 linelen = strcspn(ptr, "\n");
301                 if (linelen == 0) return(0);    /* end of headers */    
302                 
303                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
304
305
306                         if (yes_my_citadel_config) {
307                                 /* Bingo!  The user is uploading a new vCard, so
308                                  * delete the old one.  First, figure out which user
309                                  * is being re-registered...
310                                  */
311                                 what_user = atol(CC->room.QRname);
312         
313                                 if (what_user == CC->user.usernum) {
314                                         /* It's the logged in user.  That was easy. */
315                                         memcpy(&usbuf, &CC->user,
316                                                 sizeof(struct ctdluser) );
317                                 }
318                                 
319                                 else if (getuserbynumber(&usbuf, what_user) == 0) {
320                                         /* We fetched a valid user record */
321                                 }
322                         
323                                 else {
324                                         /* No user with that number! */
325                                         return(0);
326                                 }
327         
328                                 /* Delete the user's old vCard.  This would probably
329                                  * get taken care of by the replication check, but we
330                                  * want to make sure there is absolutely only one
331                                  * vCard in the user's config room at all times.
332                                  */
333                                 CtdlDeleteMessages(CC->room.QRname,
334                                                 0L, "text/x-vcard");
335
336                                 /* Make the author of the message the name of the user.
337                                  */
338                                 if (msg->cm_fields['A'] != NULL) {
339                                         free(msg->cm_fields['A']);
340                                 }
341                                 msg->cm_fields['A'] = strdup(usbuf.fullname);
342                         }
343
344                         /* Manipulate the vCard data structure */
345                         v = vcard_load(msg->cm_fields['M']);
346                         if (v != NULL) {
347
348                                 /* Insert or replace RFC2739-compliant free/busy URL */
349                                 if (yes_my_citadel_config) {
350                                         sprintf(buf, "http://%s/%s.vfb",
351                                                 config.c_fqdn,
352                                                 usbuf.fullname);
353                                         for (i=0; i<strlen(buf); ++i) {
354                                                 if (buf[i] == ' ') buf[i] = '_';
355                                         }
356                                         vcard_set_prop(v, "FBURL;PREF", buf, 0);
357                                 }
358
359                                 /* If this is an address book room, and the vCard has
360                                  * no UID, then give it one.
361                                  */
362                                 if (yes_any_vcard_room) {
363                                         s = vcard_get_prop(v, "UID", 0, 0, 0);
364                                         if (s == NULL) {
365                                                 generate_uuid(buf);
366                                                 vcard_set_prop(v, "UID", buf, 0);
367                                         }
368                                 }
369
370                                 /* Enforce local UID policy if applicable */
371                                 if (yes_my_citadel_config) {
372                                         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
373                                                 msg->cm_fields['A'], NODENAME);
374                                         vcard_set_prop(v, "UID", buf, 0);
375                                 }
376
377                                 /* Set the EUID of the message to the UID of the vCard */
378                                 if (msg->cm_fields['E'] != NULL) free(msg->cm_fields['E']);
379                                 msg->cm_fields['E'] = strdup(buf);
380
381                                 /* Re-serialize it back into the msg body */
382                                 ser = vcard_serialize(v);
383                                 if (ser != NULL) {
384                                         msg->cm_fields['M'] = realloc(
385                                                 msg->cm_fields['M'],
386                                                 strlen(ser) + 1024
387                                         );
388                                         sprintf(msg->cm_fields['M'],
389                                                 "Content-type: text/x-vcard"
390                                                 "\r\n\r\n%s\r\n", ser);
391                                         free(ser);
392                                 }
393                                 vcard_free(v);
394                         }
395
396                         /* Now allow the save to complete. */
397                         return(0);
398                 }
399
400                 ptr = strchr((char *)ptr, '\n');
401                 if (ptr != NULL) ++ptr;
402         }
403
404         return(0);
405 }
406
407
408
409 /*
410  * This handler detects whether the user is attempting to save a new
411  * vCard as part of his/her personal configuration, and handles the replace
412  * function accordingly (copy the vCard from the config room to the global
413  * address book).
414  */
415 int vcard_upload_aftersave(struct CtdlMessage *msg) {
416         char *ptr;
417         int linelen;
418         long I;
419         struct vCard *v;
420
421         if (!CC->logged_in) return(0);  /* Only do this if logged in. */
422
423         /* If this isn't the configuration room, or if this isn't a MIME
424          * message, don't bother.
425          */
426         if (msg->cm_fields['O'] == NULL) return(0);
427         if (strcasecmp(msg->cm_fields['O'], USERCONFIGROOM)) return(0);
428         if (msg->cm_format_type != 4) return(0);
429
430         ptr = msg->cm_fields['M'];
431         if (ptr == NULL) return(0);
432         while (ptr != NULL) {
433         
434                 linelen = strcspn(ptr, "\n");
435                 if (linelen == 0) return(0);    /* end of headers */    
436                 
437                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
438                         /* Bingo!  The user is uploading a new vCard, so
439                          * copy it to the Global Address Book room.
440                          */
441
442                         I = atol(msg->cm_fields['I']);
443                         if (I < 0L) return(0);
444
445                         /* Store our Internet return address in memory */
446                         v = vcard_load(msg->cm_fields['M']);
447                         vcard_populate_cs_inet_email(v);
448                         vcard_free(v);
449
450                         /* Put it in the Global Address Book room... */
451                         CtdlSaveMsgPointerInRoom(ADDRESS_BOOK_ROOM, I,
452                                 (SM_VERIFY_GOODNESS | SM_DO_REPL_CHECK) );
453
454                         /* ...and also in the directory database. */
455                         vcard_add_to_directory(I, NULL);
456
457                         /* Some sites want an Aide to be notified when a
458                          * user registers or re-registers...
459                          */
460                         set_mm_valid();
461
462                         /* ...which also means we need to flag the user */
463                         lgetuser(&CC->user, CC->curr_user);
464                         CC->user.flags |= (US_REGIS|US_NEEDVALID);
465                         lputuser(&CC->user);
466
467                         return(0);
468                 }
469
470                 ptr = strchr((char *)ptr, '\n');
471                 if (ptr != NULL) ++ptr;
472         }
473
474         return(0);
475 }
476
477
478
479 /*
480  * back end function used for callbacks
481  */
482 void vcard_gu_backend(long msgnum, void *userdata) {
483         VC->msgnum = msgnum;
484 }
485
486
487 /*
488  * If this user has a vcard on disk, read it into memory, otherwise allocate
489  * and return an empty vCard.
490  */
491 struct vCard *vcard_get_user(struct ctdluser *u) {
492         char hold_rm[ROOMNAMELEN];
493         char config_rm[ROOMNAMELEN];
494         struct CtdlMessage *msg;
495         struct vCard *v;
496
497         strcpy(hold_rm, CC->room.QRname);       /* save current room */
498         MailboxName(config_rm, sizeof config_rm, u, USERCONFIGROOM);
499
500         if (getroom(&CC->room, config_rm) != 0) {
501                 getroom(&CC->room, hold_rm);
502                 return vcard_new();
503         }
504
505         /* We want the last (and probably only) vcard in this room */
506         VC->msgnum = (-1);
507         CtdlForEachMessage(MSGS_LAST, 1, "text/x-vcard",
508                 NULL, vcard_gu_backend, NULL);
509         getroom(&CC->room, hold_rm);    /* return to saved room */
510
511         if (VC->msgnum < 0L) return vcard_new();
512
513         msg = CtdlFetchMessage(VC->msgnum, 1);
514         if (msg == NULL) return vcard_new();
515
516         v = vcard_load(msg->cm_fields['M']);
517         CtdlFreeMessage(msg);
518         return v;
519 }
520
521
522 /*
523  * Store this user's vCard in the appropriate place
524  */
525 /*
526  * Write our config to disk
527  */
528 void vcard_write_user(struct ctdluser *u, struct vCard *v) {
529         char temp[PATH_MAX];
530         FILE *fp;
531         char *ser;
532
533         strcpy(temp, tmpnam(NULL));
534         ser = vcard_serialize(v);
535
536         fp = fopen(temp, "w");
537         if (fp == NULL) return;
538         if (ser == NULL) {
539                 fprintf(fp, "begin:vcard\r\nend:vcard\r\n");
540         } else {
541                 fwrite(ser, strlen(ser), 1, fp);
542                 free(ser);
543         }
544         fclose(fp);
545
546         /* This handy API function does all the work for us.
547          * NOTE: normally we would want to set that last argument to 1, to
548          * force the system to delete the user's old vCard.  But it doesn't
549          * have to, because the vcard_upload_beforesave() hook above
550          * is going to notice what we're trying to do, and delete the old vCard.
551          */
552         CtdlWriteObject(USERCONFIGROOM, /* which room */
553                         "text/x-vcard", /* MIME type */
554                         temp,           /* temp file */
555                         u,              /* which user */
556                         0,              /* not binary */
557                         0,              /* don't delete others of this type */
558                         0);             /* no flags */
559
560         unlink(temp);
561 }
562
563
564
565 /*
566  * Old style "enter registration info" command.  This function simply honors
567  * the REGI protocol command, translates the entered parameters into a vCard,
568  * and enters the vCard into the user's configuration.
569  */
570 void cmd_regi(char *argbuf) {
571         int a,b,c;
572         char buf[SIZ];
573         struct vCard *my_vcard;
574
575         char tmpaddr[SIZ];
576         char tmpcity[SIZ];
577         char tmpstate[SIZ];
578         char tmpzip[SIZ];
579         char tmpaddress[SIZ];
580         char tmpcountry[SIZ];
581
582         unbuffer_output();
583
584         if (!(CC->logged_in)) {
585                 cprintf("%d Not logged in.\n",ERROR + NOT_LOGGED_IN);
586                 return;
587         }
588
589         my_vcard = vcard_get_user(&CC->user);
590         strcpy(tmpaddr, "");
591         strcpy(tmpcity, "");
592         strcpy(tmpstate, "");
593         strcpy(tmpzip, "");
594         strcpy(tmpcountry, "USA");
595
596         cprintf("%d Send registration...\n", SEND_LISTING);
597         a=0;
598         while (client_gets(buf), strcmp(buf,"000")) {
599                 if (a==0) vcard_set_prop(my_vcard, "n", buf, 0);
600                 if (a==1) strcpy(tmpaddr, buf);
601                 if (a==2) strcpy(tmpcity, buf);
602                 if (a==3) strcpy(tmpstate, buf);
603                 if (a==4) {
604                         for (c=0; c<strlen(buf); ++c) {
605                                 if ((buf[c]>='0') && (buf[c]<='9')) {
606                                         b = strlen(tmpzip);
607                                         tmpzip[b] = buf[c];
608                                         tmpzip[b+1] = 0;
609                                 }
610                         }
611                 }
612                 if (a==5) vcard_set_prop(my_vcard, "tel;home", buf, 0);
613                 if (a==6) vcard_set_prop(my_vcard, "email;internet", buf, 0);
614                 if (a==7) strcpy(tmpcountry, buf);
615                 ++a;
616         }
617
618         snprintf(tmpaddress, sizeof tmpaddress, ";;%s;%s;%s;%s;%s",
619                 tmpaddr, tmpcity, tmpstate, tmpzip, tmpcountry);
620         vcard_set_prop(my_vcard, "adr", tmpaddress, 0);
621         vcard_write_user(&CC->user, my_vcard);
622         vcard_free(my_vcard);
623 }
624
625
626 /*
627  * Protocol command to fetch registration info for a user
628  */
629 void cmd_greg(char *argbuf)
630 {
631         struct ctdluser usbuf;
632         struct vCard *v;
633         char *s;
634         char who[SIZ];
635         char adr[SIZ];
636         char buf[SIZ];
637
638         extract(who, argbuf, 0);
639
640         if (!(CC->logged_in)) {
641                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
642                 return;
643         }
644
645         if (!strcasecmp(who,"_SELF_")) strcpy(who,CC->curr_user);
646
647         if ((CC->user.axlevel < 6) && (strcasecmp(who,CC->curr_user))) {
648                 cprintf("%d Higher access required.\n",
649                         ERROR + HIGHER_ACCESS_REQUIRED);
650                 return;
651         }
652
653         if (getuser(&usbuf, who) != 0) {
654                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, who);
655                 return;
656         }
657
658         v = vcard_get_user(&usbuf);
659
660         cprintf("%d %s\n", LISTING_FOLLOWS, usbuf.fullname);
661         cprintf("%ld\n", usbuf.usernum);
662         cprintf("%s\n", usbuf.password);
663         s = vcard_get_prop(v, "n", 0, 0, 0);
664         cprintf("%s\n", s ? s : " ");   /* name */
665
666         s = vcard_get_prop(v, "adr", 0, 0, 0);
667         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
668
669         extract_token(buf, adr, 2, ';');
670         cprintf("%s\n", buf);                           /* street */
671         extract_token(buf, adr, 3, ';');
672         cprintf("%s\n", buf);                           /* city */
673         extract_token(buf, adr, 4, ';');
674         cprintf("%s\n", buf);                           /* state */
675         extract_token(buf, adr, 5, ';');
676         cprintf("%s\n", buf);                           /* zip */
677
678         s = vcard_get_prop(v, "tel;home", 0, 0, 0);
679         if (s == NULL) s = vcard_get_prop(v, "tel", 1, 0, 0);
680         if (s != NULL) {
681                 cprintf("%s\n", s);
682         }
683         else {
684                 cprintf(" \n");
685         }
686
687         cprintf("%d\n", usbuf.axlevel);
688
689         s = vcard_get_prop(v, "email;internet", 0, 0, 0);
690         cprintf("%s\n", s ? s : " ");
691         s = vcard_get_prop(v, "adr", 0, 0, 0);
692         snprintf(adr, sizeof adr, "%s", s ? s : " ");/* address... */
693
694         extract_token(buf, adr, 6, ';');
695         cprintf("%s\n", buf);                           /* country */
696         cprintf("000\n");
697 }
698
699
700 /*
701  * When a user is being created, create his/her vCard.
702  */
703 void vcard_newuser(struct ctdluser *usbuf) {
704         char buf[SIZ];
705         char vname[SIZ];
706
707         char lastname[SIZ];
708         char firstname[SIZ];
709         char middlename[SIZ];
710         char honorific_prefixes[SIZ];
711         char honorific_suffixes[SIZ];
712
713         struct vCard *v;
714         int i;
715
716         /* Try to intelligently convert the screen name to a
717          * fully expanded vCard name based on the number of
718          * words in the name
719          */
720         strcpy(lastname, "");
721         strcpy(firstname, "");
722         strcpy(middlename, "");
723         strcpy(honorific_prefixes, "");
724         strcpy(honorific_suffixes, "");
725
726         strcpy(buf, usbuf->fullname);
727
728         /* Honorific suffixes */
729         if (num_tokens(buf, ',') > 1) {
730                 extract_token(honorific_suffixes, buf, (num_tokens(buf, ' ') - 1), ',');
731                 remove_token(buf, (num_tokens(buf, ',') - 1), ',');
732         }
733
734         /* Find a last name */
735         extract_token(lastname, buf, (num_tokens(buf, ' ') - 1), ' ');
736         remove_token(buf, (num_tokens(buf, ' ') - 1), ' ');
737
738         /* Find honorific prefixes */
739         if (num_tokens(buf, ' ') > 2) {
740                 extract_token(honorific_prefixes, buf, 0, ' ');
741                 remove_token(buf, 0, ' ');
742         }
743
744         /* Find a middle name */
745         if (num_tokens(buf, ' ') > 1) {
746                 extract_token(middlename, buf, (num_tokens(buf, ' ') - 1), ' ');
747                 remove_token(buf, (num_tokens(buf, ' ') - 1), ' ');
748         }
749
750         /* Anything left is probably the first name */
751         strcpy(firstname, buf);
752         striplt(firstname);
753
754         /* Compose the structured name */
755         sprintf(vname, "%s;%s;%s;%s;%s", lastname, firstname, middlename,
756                 honorific_prefixes, honorific_suffixes);
757
758         lprintf(CTDL_DEBUG, "Converted <%s> to <%s>\n", usbuf->fullname, vname);
759
760         /* Create and save the vCard */
761         v = vcard_new();
762         if (v == NULL) return;
763         sprintf(buf, "%s@%s", usbuf->fullname, config.c_fqdn);
764         for (i=0; i<strlen(buf); ++i) {
765                 if (buf[i] == ' ') buf[i] = '_';
766         }
767         vcard_add_prop(v, "fn", usbuf->fullname);
768         vcard_add_prop(v, "n", vname);
769         vcard_add_prop(v, "adr", "adr:;;_;_;_;00000;__");
770         vcard_add_prop(v, "email;internet", buf);
771         vcard_write_user(usbuf, v);
772         vcard_free(v);
773 }
774
775
776 /*
777  * When a user is being deleted, we have to remove his/her vCard.
778  * This is accomplished by issuing a message with 'CANCEL' in the S (special)
779  * field, and the same Extended ID as the existing card.
780  */
781 void vcard_purge(struct ctdluser *usbuf) {
782         struct CtdlMessage *msg;
783         char buf[SIZ];
784
785         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
786         if (msg == NULL) return;
787         memset(msg, 0, sizeof(struct CtdlMessage));
788
789         msg->cm_magic = CTDLMESSAGE_MAGIC;
790         msg->cm_anon_type = MES_NORMAL;
791         msg->cm_format_type = 0;
792         msg->cm_fields['A'] = strdup(usbuf->fullname);
793         msg->cm_fields['O'] = strdup(ADDRESS_BOOK_ROOM);
794         msg->cm_fields['N'] = strdup(NODENAME);
795         msg->cm_fields['M'] = strdup("Purge this vCard\n");
796
797         snprintf(buf, sizeof buf, VCARD_EXT_FORMAT,
798                         msg->cm_fields['A'], NODENAME);
799         msg->cm_fields['E'] = strdup(buf);
800
801         msg->cm_fields['S'] = strdup("CANCEL");
802
803         CtdlSubmitMsg(msg, NULL, ADDRESS_BOOK_ROOM);
804         CtdlFreeMessage(msg);
805 }
806
807
808 /*
809  * Grab vCard directory stuff out of incoming network messages
810  */
811 int vcard_extract_from_network(struct CtdlMessage *msg, char *target_room) {
812         char *ptr;
813         int linelen;
814
815         if (msg == NULL) return(0);
816
817         if (strcasecmp(target_room, ADDRESS_BOOK_ROOM)) {
818                 return(0);
819         }
820
821         if (msg->cm_format_type != 4) return(0);
822
823         ptr = msg->cm_fields['M'];
824         if (ptr == NULL) return(0);
825         while (ptr != NULL) {
826         
827                 linelen = strcspn(ptr, "\n");
828                 if (linelen == 0) return(0);    /* end of headers */    
829                 
830                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
831                          /* It's a vCard.  Add it to the directory. */
832                         vcard_extract_internet_addresses(msg,
833                                                         CtdlDirectoryAddUser);
834                         return(0);
835                 }
836
837                 ptr = strchr((char *)ptr, '\n');
838                 if (ptr != NULL) ++ptr;
839         }
840
841         return(0);
842 }
843
844
845
846 /* 
847  * When a vCard is being removed from the Global Address Book room, remove it
848  * from the directory as well.
849  */
850 void vcard_delete_remove(char *room, long msgnum) {
851         struct CtdlMessage *msg;
852         char *ptr;
853         int linelen;
854
855         if (msgnum <= 0L) return;
856
857         if (strcasecmp(room, ADDRESS_BOOK_ROOM)) {
858                 return;
859         }
860
861         msg = CtdlFetchMessage(msgnum, 1);
862         if (msg == NULL) return;
863
864         ptr = msg->cm_fields['M'];
865         if (ptr == NULL) goto EOH;
866         while (ptr != NULL) {
867                 linelen = strcspn(ptr, "\n");
868                 if (linelen == 0) goto EOH;
869                 
870                 if (!strncasecmp(ptr, "Content-type: text/x-vcard", 26)) {
871                         /* Bingo!  A vCard is being deleted.
872                         */
873                         vcard_extract_internet_addresses(msg,
874                                                         CtdlDirectoryDelUser);
875 #ifdef HAVE_LDAP
876                         ctdl_vcard_to_ldap(msg, V2L_DELETE);
877 #endif
878                 }
879                 ptr = strchr((char *)ptr, '\n');
880                 if (ptr != NULL) ++ptr;
881         }
882
883 EOH:    CtdlFreeMessage(msg);
884 }
885
886
887
888 /*
889  * Query Directory
890  */
891 void cmd_qdir(char *argbuf) {
892         char citadel_addr[SIZ];
893         char internet_addr[SIZ];
894
895         if (CtdlAccessCheck(ac_logged_in)) return;
896
897         extract(internet_addr, argbuf, 0);
898
899         if (CtdlDirectoryLookup(citadel_addr, internet_addr) != 0) {
900                 cprintf("%d %s was not found.\n",
901                         ERROR + NO_SUCH_USER, internet_addr);
902                 return;
903         }
904
905         cprintf("%d %s\n", CIT_OK, citadel_addr);
906 }
907
908
909 /*
910  * We don't know if the Contacts room exists so we just create it at login
911  */
912 void vcard_create_room(void)
913 {
914         struct ctdlroom qr;
915         struct visit vbuf;
916
917         /* Create the calendar room if it doesn't already exist */
918         create_room(USERCONTACTSROOM, 4, "", 0, 1, 0, VIEW_ADDRESSBOOK);
919
920         /* Set expiration policy to manual; otherwise objects will be lost! */
921         if (lgetroom(&qr, USERCONTACTSROOM)) {
922                 lprintf(CTDL_ERR, "Couldn't get the user CONTACTS room!\n");
923                 return;
924         }
925         qr.QRep.expire_mode = EXPIRE_MANUAL;
926         qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
927         lputroom(&qr);
928
929         /* Set the view to a calendar view */
930         CtdlGetRelationship(&vbuf, &CC->user, &qr);
931         vbuf.v_view = 2;        /* 2 = address book view */
932         CtdlSetRelationship(&vbuf, &CC->user, &qr);
933
934         return;
935 }
936
937
938
939
940 /*
941  * Session startup, allocate some per-session data
942  */
943 void vcard_session_startup_hook(void) {
944         CtdlAllocUserData(SYM_VCARD, sizeof(struct vcard_internal_info));
945 }
946
947
948 /*
949  * When a user logs in...
950  */
951 void vcard_session_login_hook(void) {
952         struct vCard *v;
953
954         v = vcard_get_user(&CC->user);
955         vcard_populate_cs_inet_email(v);
956
957         vcard_free(v);
958
959         vcard_create_room();
960 }
961
962
963
964 char *serv_vcard_init(void)
965 {
966         struct ctdlroom qr;
967
968         CtdlRegisterSessionHook(vcard_session_startup_hook, EVT_START);
969         CtdlRegisterSessionHook(vcard_session_login_hook, EVT_LOGIN);
970         CtdlRegisterMessageHook(vcard_upload_beforesave, EVT_BEFORESAVE);
971         CtdlRegisterMessageHook(vcard_upload_aftersave, EVT_AFTERSAVE);
972         CtdlRegisterDeleteHook(vcard_delete_remove);
973         CtdlRegisterProtoHook(cmd_regi, "REGI", "Enter registration info");
974         CtdlRegisterProtoHook(cmd_greg, "GREG", "Get registration info");
975         CtdlRegisterProtoHook(cmd_igab, "IGAB",
976                                         "Initialize Global Address Book");
977         CtdlRegisterProtoHook(cmd_qdir, "QDIR", "Query Directory");
978         CtdlRegisterUserHook(vcard_newuser, EVT_NEWUSER);
979         CtdlRegisterUserHook(vcard_purge, EVT_PURGEUSER);
980         CtdlRegisterNetprocHook(vcard_extract_from_network);
981
982         /* Create the Global ADdress Book room if necessary */
983         create_room(ADDRESS_BOOK_ROOM, 3, "", 0, 1, 0, VIEW_ADDRESSBOOK);
984
985         /* Set expiration policy to manual; otherwise objects will be lost! */
986         if (!lgetroom(&qr, ADDRESS_BOOK_ROOM)) {
987                 qr.QRep.expire_mode = EXPIRE_MANUAL;
988                 qr.QRdefaultview = VIEW_ADDRESSBOOK;    /* 2 = address book view */
989                 lputroom(&qr);
990         }
991
992         return "$Id$";
993 }