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