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