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