1f6d21abe5e1ebd9ca4e24a3217bf533442a23d0
[citadel.git] / webcit / messages.c
1 /*
2  * $Id$
3  *
4  * Functions which deal with the fetching and displaying of messages.
5  *
6  */
7
8 #include "webcit.h"
9 #include "webserver.h"
10 #include "groupdav.h"
11
12 #define SUBJ_COL_WIDTH_PCT              50      /**< Mailbox view column width */
13 #define SENDER_COL_WIDTH_PCT            30      /**< Mailbox view column width */
14 #define DATE_PLUS_BUTTONS_WIDTH_PCT     20      /**< Mailbox view column width */
15
16 /*
17  * Address book entry (keep it short and sweet, it's just a quickie lookup
18  * which we can use to get to the real meat and bones later)
19  */
20 struct addrbookent {
21         char ab_name[64]; /**< name string */
22         long ab_msgnum;   /**< message number of address book entry */
23 };
24
25
26
27 #ifdef HAVE_ICONV
28
29 /*
30  * Wrapper around iconv_open()
31  * Our version adds aliases for non-standard Microsoft charsets
32  * such as 'MS950', aliasing them to names like 'CP950'
33  *
34  * tocode       Target encoding
35  * fromcode     Source encoding
36  */
37 iconv_t ctdl_iconv_open(const char *tocode, const char *fromcode)
38 {
39         iconv_t ic = (iconv_t)(-1) ;
40         ic = iconv_open(tocode, fromcode);
41         if (ic == (iconv_t)(-1) ) {
42                 char alias_fromcode[64];
43                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
44                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
45                         alias_fromcode[0] = 'C';
46                         alias_fromcode[1] = 'P';
47                         ic = iconv_open(tocode, alias_fromcode);
48                 }
49         }
50         return(ic);
51 }
52
53
54
55 inline char *FindNextEnd (char *bptr)
56 {
57         char * end;
58         /* Find the next ?Q? */
59         end = strchr(bptr + 2, '?');
60         if (end == NULL) return NULL;
61         if (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
62             (*(end + 2) == '?')) {
63                 /* skip on to the end of the cluster, the next ?= */
64                 end = strstr(end + 3, "?=");
65         }
66         else
67                 /* sort of half valid encoding, try to find an end. */
68                 end = strstr(bptr, "?=");
69         return end;
70 }
71
72 /*
73  * Handle subjects with RFC2047 encoding such as:
74  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
75  */
76 void utf8ify_rfc822_string(char *buf) {
77         char *start, *end, *next, *nextend, *ptr;
78         char newbuf[1024];
79         char charset[128];
80         char encoding[16];
81         char istr[1024];
82         iconv_t ic = (iconv_t)(-1) ;
83         char *ibuf;                     /**< Buffer of characters to be converted */
84         char *obuf;                     /**< Buffer for converted characters */
85         size_t ibuflen;                 /**< Length of input buffer */
86         size_t obuflen;                 /**< Length of output buffer */
87         char *isav;                     /**< Saved pointer to input buffer */
88         char *osav;                     /**< Saved pointer to output buffer */
89         int passes = 0;
90         int i, len, delta;
91         int illegal_non_rfc2047_encoding = 0;
92
93         /* Sometimes, badly formed messages contain strings which were simply
94          *  written out directly in some foreign character set instead of
95          *  using RFC2047 encoding.  This is illegal but we will attempt to
96          *  handle it anyway by converting from a user-specified default
97          *  charset to UTF-8 if we see any nonprintable characters.
98          */
99         len = strlen(buf);
100         for (i=0; i<len; ++i) {
101                 if ((buf[i] < 32) || (buf[i] > 126)) {
102                         illegal_non_rfc2047_encoding = 1;
103                         i = len; ///< take a shortcut, it won't be more than one.
104                 }
105         }
106         if (illegal_non_rfc2047_encoding) {
107                 char default_header_charset[128];
108                 get_preference("default_header_charset", default_header_charset, sizeof default_header_charset);
109                 if ( (strcasecmp(default_header_charset, "UTF-8")) && (strcasecmp(default_header_charset, "us-ascii")) ) {
110                         ic = ctdl_iconv_open("UTF-8", default_header_charset);
111                         if (ic != (iconv_t)(-1) ) {
112                                 ibuf = malloc(1024);
113                                 isav = ibuf;
114                                 safestrncpy(ibuf, buf, 1024);
115                                 ibuflen = strlen(ibuf);
116                                 obuflen = 1024;
117                                 obuf = (char *) malloc(obuflen);
118                                 osav = obuf;
119                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
120                                 osav[1024-obuflen] = 0;
121                                 strcpy(buf, osav);
122                                 free(osav);
123                                 iconv_close(ic);
124                                 free(isav);
125                         }
126                 }
127         }
128
129         /* pre evaluate the first pair */
130         nextend = end = NULL;
131         len = strlen(buf);
132         start = strstr(buf, "=?");
133         if (start != NULL) 
134                 end = FindNextEnd (start);
135
136         while ((start != NULL) && (end != NULL))
137         {
138                 next = strstr(end, "=?");
139                 if (next != NULL)
140                         nextend = FindNextEnd(next);
141                 if (nextend == NULL)
142                         next = NULL;
143
144                 /* did we find two partitions */
145                 if ((next != NULL) && 
146                     ((next - end) > 2))
147                 {
148                         ptr = end + 2;
149                         while ((ptr < next) && 
150                                (isspace(*ptr) ||
151                                 (*ptr == '\r') ||
152                                 (*ptr == '\n') || 
153                                 (*ptr == '\t')))
154                                 ptr ++;
155                         /* did we find a gab just filled with blanks? */
156                         if (ptr == next)
157                         {
158                                 memmove (end + 2,
159                                          next,
160                                          len - (next - start));
161
162                                 /* now terminate the gab at the end */
163                                 delta = (next - end) - 2;
164                                 len -= delta;
165                                 buf[len] = '\0';
166
167                                 /* move next to its new location. */
168                                 next -= delta;
169                                 nextend -= delta;
170                         }
171                 }
172                 /* our next-pair is our new first pair now. */
173                 start = next;
174                 end = nextend;
175         }
176
177         /* Now we handle foreign character sets properly encoded
178          * in RFC2047 format.
179          */
180         while (start=strstr(buf, "=?"), end=FindNextEnd((start != NULL)? start : buf),
181                 ((start != NULL) && (end != NULL) && (end > start)) )
182         {
183                 extract_token(charset, start, 1, '?', sizeof charset);
184                 extract_token(encoding, start, 2, '?', sizeof encoding);
185                 extract_token(istr, start, 3, '?', sizeof istr);
186
187                 ibuf = malloc(1024);
188                 isav = ibuf;
189                 if (!strcasecmp(encoding, "B")) {       /**< base64 */
190                         ibuflen = CtdlDecodeBase64(ibuf, istr, strlen(istr));
191                 }
192                 else if (!strcasecmp(encoding, "Q")) {  /**< quoted-printable */
193                         size_t len;
194                         long pos;
195                         
196                         len = strlen(istr);
197                         pos = 0;
198                         while (pos < len)
199                         {
200                                 if (istr[pos] == '_') istr[pos] = ' ';
201                                 pos++;
202                         }
203
204                         ibuflen = CtdlDecodeQuotedPrintable(ibuf, istr, len);
205                 }
206                 else {
207                         strcpy(ibuf, istr);             /**< unknown encoding */
208                         ibuflen = strlen(istr);
209                 }
210
211                 ic = ctdl_iconv_open("UTF-8", charset);
212                 if (ic != (iconv_t)(-1) ) {
213                         obuflen = 1024;
214                         obuf = (char *) malloc(obuflen);
215                         osav = obuf;
216                         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
217                         osav[1024-obuflen] = 0;
218
219                         end = start;
220                         end++;
221                         strcpy(start, "");
222                         remove_token(end, 0, '?');
223                         remove_token(end, 0, '?');
224                         remove_token(end, 0, '?');
225                         remove_token(end, 0, '?');
226                         strcpy(end, &end[1]);
227
228                         snprintf(newbuf, sizeof newbuf, "%s%s%s", buf, osav, end);
229                         strcpy(buf, newbuf);
230                         free(osav);
231                         iconv_close(ic);
232                 }
233                 else {
234                         end = start;
235                         end++;
236                         strcpy(start, "");
237                         remove_token(end, 0, '?');
238                         remove_token(end, 0, '?');
239                         remove_token(end, 0, '?');
240                         remove_token(end, 0, '?');
241                         strcpy(end, &end[1]);
242
243                         snprintf(newbuf, sizeof newbuf, "%s(unreadable)%s", buf, end);
244                         strcpy(buf, newbuf);
245                 }
246
247                 free(isav);
248
249                 /*
250                  * Since spammers will go to all sorts of absurd lengths to get their
251                  * messages through, there are LOTS of corrupt headers out there.
252                  * So, prevent a really badly formed RFC2047 header from throwing
253                  * this function into an infinite loop.
254                  */
255                 ++passes;
256                 if (passes > 20) return;
257         }
258
259 }
260 #else
261 inline void utf8ify_rfc822_string(char *a){};
262
263 #endif
264
265
266
267
268 /**
269  * \brief       RFC2047-encode a header field if necessary.
270  *              If no non-ASCII characters are found, the string
271  *              will be copied verbatim without encoding.
272  *
273  * \param       target          Target buffer.
274  * \param       maxlen          Maximum size of target buffer.
275  * \param       source          Source string to be encoded.
276  * \param       SourceLen       Length of the source string
277  * \returns     encoded length; -1 if non success.
278  */
279 int webcit_rfc2047encode(char *target, int maxlen, char *source, long SourceLen)
280 {
281         const char headerStr[] = "=?UTF-8?Q?";
282         int need_to_encode = 0;
283         int i = 0;
284         int len;
285         unsigned char ch;
286
287         if ((source == NULL) || 
288             (target == NULL) ||
289             (SourceLen > maxlen)) return -1;
290
291         while ((!IsEmptyStr (&source[i])) && 
292                (need_to_encode == 0) &&
293                (i < SourceLen) ) {
294                 if (((unsigned char) source[i] < 32) || 
295                     ((unsigned char) source[i] > 126)) {
296                         need_to_encode = 1;
297                 }
298                 i++;
299         }
300
301         if (!need_to_encode) {
302                 memcpy (target, source, SourceLen);
303                 target[SourceLen] = '\0';
304                 return SourceLen;
305         }
306         
307         if (sizeof (headerStr + SourceLen + 2) > maxlen)
308                 return -1;
309         memcpy (target, headerStr, sizeof (headerStr));
310         len = sizeof (headerStr) - 1;
311         for (i=0; (i < SourceLen) && (len + 3< maxlen) ; ++i) {
312                 ch = (unsigned char) source[i];
313                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
314                         sprintf(&target[len], "=%02X", ch);
315                         len += 3;
316                 }
317                 else {
318                         sprintf(&target[len], "%c", ch);
319                         len ++;
320                 }
321         }
322         
323         if (len + 2 < maxlen) {
324                 strcat(&target[len], "?=");
325                 len +=2;
326                 return len;
327         }
328         else
329                 return -1;
330 }
331
332
333
334
335 /*
336  * Look for URL's embedded in a buffer and make them linkable.  We use a
337  * target window in order to keep the Citadel session in its own window.
338  */
339 void url(char *buf, size_t bufsize)
340 {
341         int len, UrlLen, Offset, TrailerLen, outpos;
342         char *start, *end, *pos;
343         char urlbuf[SIZ];
344         char outbuf[SIZ];
345
346         start = NULL;
347         len = strlen(buf);
348         if (len > bufsize) {
349                 lprintf(1, "URL: content longer than buffer!");
350                 return;
351         }
352         end = buf + len;
353         for (pos = buf; (pos < end) && (start == NULL); ++pos) {
354                 if (!strncasecmp(pos, "http://", 7))
355                         start = pos;
356                 if (!strncasecmp(pos, "ftp://", 6))
357                         start = pos;
358         }
359
360         if (start == NULL)
361                 return;
362
363         for (pos = buf+len; pos > start; --pos) {
364                 if (  (!isprint(*pos))
365                    || (isspace(*pos))
366                    || (*pos == '{')
367                    || (*pos == '}')
368                    || (*pos == '|')
369                    || (*pos == '\\')
370                    || (*pos == '^')
371                    || (*pos == '[')
372                    || (*pos == ']')
373                    || (*pos == '`')
374                    || (*pos == '<')
375                    || (*pos == '>')
376                    || (*pos == '(')
377                    || (*pos == ')')
378                 ) {
379                         end = pos;
380                 }
381         }
382         
383         UrlLen = end - start;
384         if (UrlLen > sizeof(urlbuf)){
385                 lprintf(1, "URL: content longer than buffer!");
386                 return;
387         }
388         memcpy(urlbuf, start, UrlLen);
389         urlbuf[UrlLen] = '\0';
390
391         Offset = start - buf;
392         if ((Offset != 0) && (Offset < sizeof(outbuf)))
393                 memcpy(outbuf, buf, Offset);
394         outpos = snprintf(&outbuf[Offset], sizeof(outbuf) - Offset,  
395                           "%ca href=%c%s%c TARGET=%c%s%c%c%s%c/A%c",
396                           LB, QU, urlbuf, QU, QU, TARGET, QU, RB, urlbuf, LB, RB);
397         if (outpos >= sizeof(outbuf) - Offset) {
398                 lprintf(1, "URL: content longer than buffer!");
399                 return;
400         }
401
402         TrailerLen = len - (end - start);
403         if (TrailerLen > 0)
404                 memcpy(outbuf + Offset + outpos, end, TrailerLen);
405         if (Offset + outpos + TrailerLen > bufsize) {
406                 lprintf(1, "URL: content longer than buffer!");
407                 return;
408         }
409         memcpy (buf, outbuf, Offset + outpos + TrailerLen);
410         *(buf + Offset + outpos + TrailerLen) = '\0';
411 }
412
413
414 /**
415  * \brief Turn a vCard "n" (name) field into something displayable.
416  * \param name the name field to convert
417  */
418 void vcard_n_prettyize(char *name)
419 {
420         char *original_name;
421         int i, j, len;
422
423         original_name = strdup(name);
424         len = strlen(original_name);
425         for (i=0; i<5; ++i) {
426                 if (len > 0) {
427                         if (original_name[len-1] == ' ') {
428                                 original_name[--len] = 0;
429                         }
430                         if (original_name[len-1] == ';') {
431                                 original_name[--len] = 0;
432                         }
433                 }
434         }
435         strcpy(name, "");
436         j=0;
437         for (i=0; i<len; ++i) {
438                 if (original_name[i] == ';') {
439                         name[j++] = ',';
440                         name[j++] = ' ';                        
441                 }
442                 else {
443                         name[j++] = original_name[i];
444                 }
445         }
446         name[j] = '\0';
447         free(original_name);
448 }
449
450
451
452
453 /**
454  * \brief preparse a vcard name
455  * display_vcard() calls this after parsing the textual vCard into
456  * our 'struct vCard' data object.
457  * This gets called instead of display_parsed_vcard() if we are only looking
458  * to extract the person's name instead of displaying the card.
459  * \param v the vcard to retrieve the name from
460  * \param storename where to put the name at
461  */
462 void fetchname_parsed_vcard(struct vCard *v, char *storename) {
463         char *name;
464
465         strcpy(storename, "");
466
467         name = vcard_get_prop(v, "n", 1, 0, 0);
468         if (name != NULL) {
469                 strcpy(storename, name);
470                 /* vcard_n_prettyize(storename); */
471         }
472
473 }
474
475
476
477 /**
478  * \brief html print a vcard
479  * display_vcard() calls this after parsing the textual vCard into
480  * our 'struct vCard' data object.
481  *
482  * Set 'full' to nonzero to display the full card, otherwise it will only
483  * show a summary line.
484  *
485  * This code is a bit ugly, so perhaps an explanation is due: we do this
486  * in two passes through the vCard fields.  On the first pass, we process
487  * fields we understand, and then render them in a pretty fashion at the
488  * end.  Then we make a second pass, outputting all the fields we don't
489  * understand in a simple two-column name/value format.
490  * \param v the vCard to display
491  * \param full display all items of the vcard?
492  */
493 void display_parsed_vcard(struct vCard *v, int full) {
494         int i, j;
495         char buf[SIZ];
496         char *name;
497         int is_qp = 0;
498         int is_b64 = 0;
499         char *thisname, *thisvalue;
500         char firsttoken[SIZ];
501         int pass;
502
503         char fullname[SIZ];
504         char title[SIZ];
505         char org[SIZ];
506         char phone[SIZ];
507         char mailto[SIZ];
508
509         strcpy(fullname, "");
510         strcpy(phone, "");
511         strcpy(mailto, "");
512         strcpy(title, "");
513         strcpy(org, "");
514
515         if (!full) {
516                 wprintf("<TD>");
517                 name = vcard_get_prop(v, "fn", 1, 0, 0);
518                 if (name != NULL) {
519                         escputs(name);
520                 }
521                 else if (name = vcard_get_prop(v, "n", 1, 0, 0), name != NULL) {
522                         strcpy(fullname, name);
523                         vcard_n_prettyize(fullname);
524                         escputs(fullname);
525                 }
526                 else {
527                         wprintf("&nbsp;");
528                 }
529                 wprintf("</TD>");
530                 return;
531         }
532
533         wprintf("<div align=center>"
534                 "<table bgcolor=#aaaaaa width=50%%>");
535         for (pass=1; pass<=2; ++pass) {
536
537                 if (v->numprops) for (i=0; i<(v->numprops); ++i) {
538                         int len;
539                         thisname = strdup(v->prop[i].name);
540                         extract_token(firsttoken, thisname, 0, ';', sizeof firsttoken);
541         
542                         for (j=0; j<num_tokens(thisname, ';'); ++j) {
543                                 extract_token(buf, thisname, j, ';', sizeof buf);
544                                 if (!strcasecmp(buf, "encoding=quoted-printable")) {
545                                         is_qp = 1;
546                                         remove_token(thisname, j, ';');
547                                 }
548                                 if (!strcasecmp(buf, "encoding=base64")) {
549                                         is_b64 = 1;
550                                         remove_token(thisname, j, ';');
551                                 }
552                         }
553                         
554                         len = strlen(v->prop[i].value);
555                         /* if we have some untagged QP, detect it here. */
556                         if (!is_qp && (strstr(v->prop[i].value, "=?")!=NULL))
557                                 utf8ify_rfc822_string(v->prop[i].value);
558
559                         if (is_qp) {
560                                 // %ff can become 6 bytes in utf8 
561                                 thisvalue = malloc(len * 2 + 3); 
562                                 j = CtdlDecodeQuotedPrintable(
563                                         thisvalue, v->prop[i].value,
564                                         len);
565                                 thisvalue[j] = 0;
566                         }
567                         else if (is_b64) {
568                                 // ff will become one byte..
569                                 thisvalue = malloc(len + 50);
570                                 CtdlDecodeBase64(
571                                         thisvalue, v->prop[i].value,
572                                         strlen(v->prop[i].value) );
573                         }
574                         else {
575                                 thisvalue = strdup(v->prop[i].value);
576                         }
577         
578                         /** Various fields we may encounter ***/
579         
580                         /** N is name, but only if there's no FN already there */
581                         if (!strcasecmp(firsttoken, "n")) {
582                                 if (IsEmptyStr(fullname)) {
583                                         strcpy(fullname, thisvalue);
584                                         vcard_n_prettyize(fullname);
585                                 }
586                         }
587         
588                         /** FN (full name) is a true 'display name' field */
589                         else if (!strcasecmp(firsttoken, "fn")) {
590                                 strcpy(fullname, thisvalue);
591                         }
592
593                         /** title */
594                         else if (!strcasecmp(firsttoken, "title")) {
595                                 strcpy(title, thisvalue);
596                         }
597         
598                         /** organization */
599                         else if (!strcasecmp(firsttoken, "org")) {
600                                 strcpy(org, thisvalue);
601                         }
602         
603                         else if (!strcasecmp(firsttoken, "email")) {
604                                 size_t len;
605                                 if (!IsEmptyStr(mailto)) strcat(mailto, "<br />");
606                                 strcat(mailto,
607                                         "<a href=\"display_enter"
608                                         "?force_room=_MAIL_?recp=");
609
610                                 len = strlen(mailto);
611                                 urlesc(&mailto[len], SIZ - len, "\"");
612                                 len = strlen(mailto);
613                                 urlesc(&mailto[len], SIZ - len,  fullname);
614                                 len = strlen(mailto);
615                                 urlesc(&mailto[len], SIZ - len, "\" <");
616                                 len = strlen(mailto);
617                                 urlesc(&mailto[len], SIZ - len, thisvalue);
618                                 len = strlen(mailto);
619                                 urlesc(&mailto[len], SIZ - len, ">");
620
621                                 strcat(mailto, "\">");
622                                 len = strlen(mailto);
623                                 stresc(mailto+len, SIZ - len, thisvalue, 1, 1);
624                                 strcat(mailto, "</A>");
625                         }
626                         else if (!strcasecmp(firsttoken, "tel")) {
627                                 if (!IsEmptyStr(phone)) strcat(phone, "<br />");
628                                 strcat(phone, thisvalue);
629                                 for (j=0; j<num_tokens(thisname, ';'); ++j) {
630                                         extract_token(buf, thisname, j, ';', sizeof buf);
631                                         if (!strcasecmp(buf, "tel"))
632                                                 strcat(phone, "");
633                                         else if (!strcasecmp(buf, "work"))
634                                                 strcat(phone, _(" (work)"));
635                                         else if (!strcasecmp(buf, "home"))
636                                                 strcat(phone, _(" (home)"));
637                                         else if (!strcasecmp(buf, "cell"))
638                                                 strcat(phone, _(" (cell)"));
639                                         else {
640                                                 strcat(phone, " (");
641                                                 strcat(phone, buf);
642                                                 strcat(phone, ")");
643                                         }
644                                 }
645                         }
646                         else if (!strcasecmp(firsttoken, "adr")) {
647                                 if (pass == 2) {
648                                         wprintf("<TR><TD>");
649                                         wprintf(_("Address:"));
650                                         wprintf("</TD><TD>");
651                                         for (j=0; j<num_tokens(thisvalue, ';'); ++j) {
652                                                 extract_token(buf, thisvalue, j, ';', sizeof buf);
653                                                 if (!IsEmptyStr(buf)) {
654                                                         escputs(buf);
655                                                         if (j<3) wprintf("<br />");
656                                                         else wprintf(" ");
657                                                 }
658                                         }
659                                         wprintf("</TD></TR>\n");
660                                 }
661                         }
662                         else if (!strcasecmp(firsttoken, "version")) {
663                                 /* ignore */
664                         }
665                         else if (!strcasecmp(firsttoken, "rev")) {
666                                 /* ignore */
667                         }
668                         else if (!strcasecmp(firsttoken, "label")) {
669                                 /* ignore */
670                         }
671                         else {
672
673                                 /*** Don't show extra fields.  They're ugly.
674                                 if (pass == 2) {
675                                         wprintf("<TR><TD>");
676                                         escputs(thisname);
677                                         wprintf("</TD><TD>");
678                                         escputs(thisvalue);
679                                         wprintf("</TD></TR>\n");
680                                 }
681                                 ***/
682                         }
683         
684                         free(thisname);
685                         free(thisvalue);
686                 }
687         
688                 if (pass == 1) {
689                         wprintf("<TR BGCOLOR=\"#AAAAAA\">"
690                         "<TD COLSPAN=2 BGCOLOR=\"#FFFFFF\">"
691                         "<IMG ALIGN=CENTER src=\"static/viewcontacts_48x.gif\">"
692                         "<FONT SIZE=+1><B>");
693                         escputs(fullname);
694                         wprintf("</B></FONT>");
695                         if (!IsEmptyStr(title)) {
696                                 wprintf("<div align=right>");
697                                 escputs(title);
698                                 wprintf("</div>");
699                         }
700                         if (!IsEmptyStr(org)) {
701                                 wprintf("<div align=right>");
702                                 escputs(org);
703                                 wprintf("</div>");
704                         }
705                         wprintf("</TD></TR>\n");
706                 
707                         if (!IsEmptyStr(phone)) {
708                                 wprintf("<tr><td>");
709                                 wprintf(_("Telephone:"));
710                                 wprintf("</td><td>%s</td></tr>\n", phone);
711                         }
712                         if (!IsEmptyStr(mailto)) {
713                                 wprintf("<tr><td>");
714                                 wprintf(_("E-mail:"));
715                                 wprintf("</td><td>%s</td></tr>\n", mailto);
716                         }
717                 }
718
719         }
720
721         wprintf("</table></div>\n");
722 }
723
724
725
726 /**
727  * \brief  Display a textual vCard
728  * (Converts to a vCard object and then calls the actual display function)
729  * Set 'full' to nonzero to display the whole card instead of a one-liner.
730  * Or, if "storename" is non-NULL, just store the person's name in that
731  * buffer instead of displaying the card at all.
732  * \param vcard_source the buffer containing the vcard text
733  * \param alpha what???
734  * \param full should we usse all lines?
735  * \param storename where to store???
736  */
737 void display_vcard(char *vcard_source, char alpha, int full, char *storename) {
738         struct vCard *v;
739         char *name;
740         char buf[SIZ];
741         char this_alpha = 0;
742
743         v = vcard_load(vcard_source);
744         if (v == NULL) return;
745
746         name = vcard_get_prop(v, "n", 1, 0, 0);
747         if (name != NULL) {
748                 utf8ify_rfc822_string(name);
749                 strcpy(buf, name);
750                 this_alpha = buf[0];
751         }
752
753         if (storename != NULL) {
754                 fetchname_parsed_vcard(v, storename);
755         }
756         else if (       (alpha == 0)
757                         || ((isalpha(alpha)) && (tolower(alpha) == tolower(this_alpha)) )
758                         || ((!isalpha(alpha)) && (!isalpha(this_alpha)))
759                 ) {
760                 display_parsed_vcard(v, full);
761         }
762
763         vcard_free(v);
764 }
765
766
767 struct attach_link {
768         char partnum[32];
769         char html[1024];
770 };
771
772
773 /*
774  * I wanna SEE that message!
775  *
776  * msgnum               Message number to display
777  * printable_view       Nonzero to display a printable view
778  * section              Optional for encapsulated message/rfc822 submessage
779  */
780 void read_message(long msgnum, int printable_view, char *section) {
781         char buf[SIZ];
782         char mime_partnum[256] = "";
783         char mime_name[256] = "";
784         char mime_filename[256] = "";
785         char escaped_mime_filename[256] = "";
786         char mime_content_type[256] = "";
787         const char *mime_content_type_ptr;
788         char mime_charset[256] = "";
789         char mime_disposition[256] = "";
790         int mime_length;
791         struct attach_link *attach_links = NULL;
792         int num_attach_links = 0;
793         char mime_submessages[256] = "";
794         char m_subject[1024] = "";
795         char m_cc[1024] = "";
796         char from[256] = "";
797         char node[256] = "";
798         char rfca[256] = "";
799         char reply_to[512] = "";
800         char reply_all[4096] = "";
801         char reply_references[1024] = "";
802         char reply_inreplyto[256] = "";
803         char now[64] = "";
804         int format_type = 0;
805         int nhdr = 0;
806         int bq = 0;
807         int i = 0;
808         char vcard_partnum[256] = "";
809         char cal_partnum[256] = "";
810         char *part_source = NULL;
811         char msg4_partnum[32] = "";
812 #ifdef HAVE_ICONV
813         iconv_t ic = (iconv_t)(-1) ;
814         char *ibuf;                /**< Buffer of characters to be converted */
815         char *obuf;                /**< Buffer for converted characters      */
816         size_t ibuflen;    /**< Length of input buffer         */
817         size_t obuflen;    /**< Length of output buffer       */
818         char *osav;                /**< Saved pointer to output buffer       */
819 #endif
820
821         strcpy(mime_content_type, "text/plain");
822         strcpy(mime_charset, "us-ascii");
823         strcpy(mime_submessages, "");
824
825         serv_printf("MSG4 %ld|%s", msgnum, section);
826         serv_getln(buf, sizeof buf);
827         if (buf[0] != '1') {
828                 wprintf("<strong>");
829                 wprintf(_("ERROR:"));
830                 wprintf("</strong> %s<br />\n", &buf[4]);
831                 return;
832         }
833
834         /** begin everythingamundo table */
835         if (!printable_view) {
836                 wprintf("<div class=\"fix_scrollbar_bug message\" ");
837                 wprintf("onMouseOver=document.getElementById(\"msg%ld\").style.visibility=\"visible\" ", msgnum);
838                 wprintf("onMouseOut=document.getElementById(\"msg%ld\").style.visibility=\"hidden\" >", msgnum);
839         }
840
841         /** begin message header table */
842         wprintf("<div class=\"message_header\">");
843
844         strcpy(m_subject, "");
845         strcpy(m_cc, "");
846
847         while (serv_getln(buf, sizeof buf), strcasecmp(buf, "text")) {
848                 if (!strcmp(buf, "000")) {
849                         wprintf("<i>");
850                         wprintf(_("unexpected end of message"));
851                         wprintf(" (1)</i><br /><br />\n");
852                         wprintf("</div>\n");
853                         return;
854                 }
855                 if (!strncasecmp(buf, "nhdr=yes", 8))
856                         nhdr = 1;
857                 if (nhdr == 1)
858                         buf[0] = '_';
859                 if (!strncasecmp(buf, "type=", 5))
860                         format_type = atoi(&buf[5]);
861                 if (!strncasecmp(buf, "from=", 5)) {
862                         strcpy(from, &buf[5]);
863                         wprintf(_("from "));
864                         wprintf("<a href=\"showuser?who=");
865                         utf8ify_rfc822_string(from);
866                         urlescputs(from);
867                         wprintf("\">");
868                         escputs(from);
869                         wprintf("</a> ");
870                 }
871                 if (!strncasecmp(buf, "subj=", 5)) {
872                         safestrncpy(m_subject, &buf[5], sizeof m_subject);
873                 }
874                 if (!strncasecmp(buf, "msgn=", 5)) {
875                         safestrncpy(reply_inreplyto, &buf[5], sizeof reply_inreplyto);
876                 }
877                 if (!strncasecmp(buf, "wefw=", 5)) {
878                         safestrncpy(reply_references, &buf[5], sizeof reply_references);
879                 }
880                 if (!strncasecmp(buf, "cccc=", 5)) {
881                         int len;
882                         safestrncpy(m_cc, &buf[5], sizeof m_cc);
883                         if (!IsEmptyStr(reply_all)) {
884                                 strcat(reply_all, ", ");
885                         }
886                         len = strlen(reply_all);
887                         safestrncpy(&reply_all[len], &buf[5],
888                                 (sizeof reply_all - len) );
889                 }
890                 if ((!strncasecmp(buf, "hnod=", 5))
891                     && (strcasecmp(&buf[5], serv_info.serv_humannode))) {
892                         wprintf("(%s) ", &buf[5]);
893                 }
894                 if ((!strncasecmp(buf, "room=", 5))
895                     && (strcasecmp(&buf[5], WC->wc_roomname))
896                     && (!IsEmptyStr(&buf[5])) ) {
897                         wprintf(_("in "));
898                         wprintf("%s&gt; ", &buf[5]);
899                 }
900                 if (!strncasecmp(buf, "rfca=", 5)) {
901                         strcpy(rfca, &buf[5]);
902                         wprintf("&lt;");
903                         escputs(rfca);
904                         wprintf("&gt; ");
905                 }
906
907                 if (!strncasecmp(buf, "node=", 5)) {
908                         strcpy(node, &buf[5]);
909                         if ( ((WC->room_flags & QR_NETWORK)
910                         || ((strcasecmp(&buf[5], serv_info.serv_nodename)
911                         && (strcasecmp(&buf[5], serv_info.serv_fqdn)))))
912                         && (IsEmptyStr(rfca))
913                         ) {
914                                 wprintf("@%s ", &buf[5]);
915                         }
916                 }
917                 if (!strncasecmp(buf, "rcpt=", 5)) {
918                         int len;
919                         wprintf(_("to "));
920                         if (!IsEmptyStr(reply_all)) {
921                                 strcat(reply_all, ", ");
922                         }
923                         len = strlen(reply_all);
924                         safestrncpy(&reply_all[len], &buf[5],
925                                 (sizeof reply_all - len) );
926                         utf8ify_rfc822_string(&buf[5]);
927                         escputs(&buf[5]);
928                         wprintf(" ");
929                 }
930                 if (!strncasecmp(buf, "time=", 5)) {
931                         webcit_fmt_date(now, atol(&buf[5]), 0);
932                         wprintf("<span>");
933                         wprintf("%s ", now);
934                         wprintf("</span>");
935                 }
936
937                 if (!strncasecmp(buf, "part=", 5)) {
938                         extract_token(mime_name, &buf[5], 0, '|', sizeof mime_filename);
939                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
940                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
941                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
942                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
943                         mime_length = extract_int(&buf[5], 5);
944
945                         striplt(mime_name);
946                         striplt(mime_filename);
947                         if ( (IsEmptyStr(mime_filename)) && (!IsEmptyStr(mime_name)) ) {
948                                 strcpy(mime_filename, mime_name);
949                         }
950
951                         if (!strcasecmp(mime_content_type, "message/rfc822")) {
952                                 if (!IsEmptyStr(mime_submessages)) {
953                                         strcat(mime_submessages, "|");
954                                 }
955                                 strcat(mime_submessages, mime_partnum);
956                         }
957                         else if ((!strcasecmp(mime_disposition, "inline"))
958                            && (!strncasecmp(mime_content_type, "image/", 6)) ){
959                                 ++num_attach_links;
960                                 attach_links = realloc(attach_links,
961                                         (num_attach_links*sizeof(struct attach_link)));
962                                 safestrncpy(attach_links[num_attach_links-1].partnum, mime_partnum, 32);
963                                 snprintf(attach_links[num_attach_links-1].html, 1024,
964                                         "<img src=\"mimepart/%ld/%s/%s\">",
965                                         msgnum, mime_partnum, mime_filename);
966                         }
967                         else if ( ( (!strcasecmp(mime_disposition, "attachment")) 
968                              || (!strcasecmp(mime_disposition, "inline"))
969                              || (!strcasecmp(mime_disposition, ""))
970                              ) && (!IsEmptyStr(mime_content_type))
971                         ) {
972                                 ++num_attach_links;
973                                 attach_links = realloc(attach_links,
974                                         (num_attach_links*sizeof(struct attach_link)));
975                                 safestrncpy(attach_links[num_attach_links-1].partnum, mime_partnum, 32);
976                                 utf8ify_rfc822_string(mime_filename);
977
978                                 mime_content_type_ptr = mime_content_type;
979                                 if (strcasecmp(mime_content_type, "application/octet-stream") == 0) {
980                                         mime_content_type_ptr = GuessMimeByFilename(mime_filename, 
981                                                                                     strlen(mime_filename));
982                                 }
983                                 urlesc(escaped_mime_filename, 265, mime_filename);
984                                 snprintf(attach_links[num_attach_links-1].html, 1024,
985                                         "<img src=\"display_mime_icon?type=%s\" "
986                                         "border=0 align=middle>\n"
987                                         "%s (%s, %d bytes) [ "
988                                         "<a href=\"mimepart/%ld/%s/%s\""
989                                         "target=\"wc.%ld.%s\">%s</a>"
990                                         " | "
991                                         "<a href=\"mimepart_download/%ld/%s/%s\">%s</a>"
992                                         " ]<br />\n",
993                                         mime_content_type_ptr,
994                                         mime_filename,
995                                         mime_content_type, mime_length,
996                                         msgnum, mime_partnum, escaped_mime_filename,
997                                         msgnum, mime_partnum,
998                                         _("View"),
999                                         msgnum, mime_partnum, escaped_mime_filename,
1000                                         _("Download")
1001                                 );
1002                         }
1003
1004                         /** begin handler prep ***/
1005                         if (  (!strcasecmp(mime_content_type, "text/x-vcard"))
1006                            || (!strcasecmp(mime_content_type, "text/vcard")) ) {
1007                                 strcpy(vcard_partnum, mime_partnum);
1008                         }
1009
1010                         if (  (!strcasecmp(mime_content_type, "text/calendar"))
1011                            || (!strcasecmp(mime_content_type, "application/ics")) ) {
1012                                 strcpy(cal_partnum, mime_partnum);
1013                         }
1014
1015                         /** end handler prep ***/
1016
1017                 }
1018
1019         }
1020
1021         /* Trim down excessively long lists of thread references.  We eliminate the
1022          * second one in the list so that the thread root remains intact.
1023          */
1024         int rrtok = num_tokens(reply_references, '|');
1025         int rrlen = strlen(reply_references);
1026         if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
1027                 remove_token(reply_references, 1, '|');
1028         }
1029
1030         /* Generate a reply-to address */
1031         if (!IsEmptyStr(rfca)) {
1032                 if (!IsEmptyStr(from)) {
1033                         snprintf(reply_to, sizeof(reply_to), "%s <%s>", from, rfca);
1034                 }
1035                 else {
1036                         strcpy(reply_to, rfca);
1037                 }
1038         }
1039         else {
1040         if ((!IsEmptyStr(node))
1041                    && (strcasecmp(node, serv_info.serv_nodename))
1042                    && (strcasecmp(node, serv_info.serv_humannode)) ) {
1043                         snprintf(reply_to, sizeof(reply_to), "%s @ %s",
1044                                 from, node);
1045                 }
1046                 else {
1047                         snprintf(reply_to, sizeof(reply_to), "%s", from);
1048                 }
1049         }
1050
1051         if (nhdr == 1) {
1052                 wprintf("****");
1053         }
1054
1055         utf8ify_rfc822_string(m_cc);
1056         utf8ify_rfc822_string(m_subject);
1057
1058         /** start msg buttons */
1059
1060         if (!printable_view) {
1061                 wprintf("<p id=\"msg%ld\" class=\"msgbuttons\" >\n",msgnum);
1062
1063                 /* Reply */
1064                 if ( (WC->wc_view == VIEW_MAILBOX) || (WC->wc_view == VIEW_BBS) ) {
1065                         wprintf("<a href=\"display_enter");
1066                         if (WC->is_mailbox) {
1067                                 wprintf("?replyquote=%ld", msgnum);
1068                         }
1069                         wprintf("?recp=");
1070                         urlescputs(reply_to);
1071                         if (!IsEmptyStr(m_subject)) {
1072                                 wprintf("?subject=");
1073                                 if (strncasecmp(m_subject, "Re:", 3)) wprintf("Re:%20");
1074                                 urlescputs(m_subject);
1075                         }
1076                         wprintf("?references=");
1077                         if (!IsEmptyStr(reply_references)) {
1078                                 urlescputs(reply_references);
1079                                 urlescputs("|");
1080                         }
1081                         urlescputs(reply_inreplyto);
1082                         wprintf("\"><span>[</span>%s<span>]</span></a> ", _("Reply"));
1083                 }
1084
1085                 /* ReplyQuoted */
1086                 if ( (WC->wc_view == VIEW_MAILBOX) || (WC->wc_view == VIEW_BBS) ) {
1087                         if (!WC->is_mailbox) {
1088                                 wprintf("<a href=\"display_enter");
1089                                 wprintf("?replyquote=%ld", msgnum);
1090                                 wprintf("?recp=");
1091                                 urlescputs(reply_to);
1092                                 if (!IsEmptyStr(m_subject)) {
1093                                         wprintf("?subject=");
1094                                         if (strncasecmp(m_subject, "Re:", 3)) wprintf("Re:%20");
1095                                         urlescputs(m_subject);
1096                                 }
1097                                 wprintf("?references=");
1098                                 if (!IsEmptyStr(reply_references)) {
1099                                         urlescputs(reply_references);
1100                                         urlescputs("|");
1101                                 }
1102                                 urlescputs(reply_inreplyto);
1103                                 wprintf("\"><span>[</span>%s<span>]</span></a> ", _("ReplyQuoted"));
1104                         }
1105                 }
1106
1107                 /* ReplyAll */
1108                 if (WC->wc_view == VIEW_MAILBOX) {
1109                         wprintf("<a href=\"display_enter");
1110                         wprintf("?replyquote=%ld", msgnum);
1111                         wprintf("?recp=");
1112                         urlescputs(reply_to);
1113                         wprintf("?cc=");
1114                         urlescputs(reply_all);
1115                         if (!IsEmptyStr(m_subject)) {
1116                                 wprintf("?subject=");
1117                                 if (strncasecmp(m_subject, "Re:", 3)) wprintf("Re:%20");
1118                                 urlescputs(m_subject);
1119                         }
1120                         wprintf("?references=");
1121                         if (!IsEmptyStr(reply_references)) {
1122                                 urlescputs(reply_references);
1123                                 urlescputs("|");
1124                         }
1125                         urlescputs(reply_inreplyto);
1126                         wprintf("\"><span>[</span>%s<span>]</span></a> ", _("ReplyAll"));
1127                 }
1128
1129                 /* Forward */
1130                 if (WC->wc_view == VIEW_MAILBOX) {
1131                         wprintf("<a href=\"display_enter?fwdquote=%ld?subject=", msgnum);
1132                         if (strncasecmp(m_subject, "Fwd:", 4)) wprintf("Fwd:%20");
1133                         urlescputs(m_subject);
1134                         wprintf("\"><span>[</span>%s<span>]</span></a> ", _("Forward"));
1135                 }
1136
1137                 /* If this is one of my own rooms, or if I'm an Aide or Room Aide, I can move/delete */
1138                 if ( (WC->is_room_aide) || (WC->is_mailbox) || (WC->room_flags2 & QR2_COLLABDEL) ) {
1139                         /** Move */
1140                         wprintf("<a href=\"confirm_move_msg?msgid=%ld\"><span>[</span>%s<span>]</span></a> ",
1141                                 msgnum, _("Move"));
1142         
1143                         /** Delete */
1144                         wprintf("<a href=\"delete_msg?msgid=%ld\" "
1145                                 "onClick=\"return confirm('%s');\">"
1146                                 "<span>[</span>%s<span>]</span> "
1147                                 "</a> ", msgnum, _("Delete this message?"), _("Delete")
1148                         );
1149                 }
1150
1151                 /* Headers */
1152                 wprintf("<a href=\"#\" onClick=\"window.open('msgheaders/%ld', 'headers%ld', 'toolbar=no,location=no,directories=no,copyhistory=no,status=yes,scrollbars=yes,resizable=yes,width=600,height=400'); \" >"
1153                         "<span>[</span>%s<span>]</span></a>", msgnum, msgnum, _("Headers"));
1154
1155
1156                 /* Print */
1157                 wprintf("<a href=\"#\" onClick=\"window.open('printmsg/%ld', 'print%ld', 'toolbar=no,location=no,directories=no,copyhistory=no,status=yes,scrollbars=yes,resizable=yes,width=600,height=400'); \" >"
1158                         "<span>[</span>%s<span>]</span></a>", msgnum, msgnum, _("Print"));
1159
1160                 wprintf("</p>");
1161
1162         }
1163
1164         if (!IsEmptyStr(m_cc)) {
1165                 wprintf("<p>");
1166                 wprintf(_("CC:"));
1167                 wprintf(" ");
1168                 escputs(m_cc);
1169                 wprintf("</p>");
1170         }
1171         if (!IsEmptyStr(m_subject)) {
1172                 wprintf("<p class=\"message_subject\">");
1173                 wprintf(_("Subject:"));
1174                 wprintf(" ");
1175                 escputs(m_subject);
1176                 wprintf("</p>");
1177         }
1178
1179         wprintf("</div>");
1180
1181         /* Begin body */
1182         wprintf("<div class=\"message_content\">");
1183
1184         /*
1185          * Learn the content type
1186          */
1187         strcpy(mime_content_type, "text/plain");
1188         while (serv_getln(buf, sizeof buf), (!IsEmptyStr(buf))) {
1189                 if (!strcmp(buf, "000")) {
1190                         /* This is not necessarily an error condition.  See bug #226. */
1191                         goto ENDBODY;
1192                 }
1193                 if (!strncasecmp(buf, "X-Citadel-MSG4-Partnum:", 23)) {
1194                         safestrncpy(msg4_partnum, &buf[23], sizeof(msg4_partnum));
1195                         striplt(msg4_partnum);
1196                 }
1197                 if (!strncasecmp(buf, "Content-type:", 13)) {
1198                         int len;
1199                         safestrncpy(mime_content_type, &buf[13], sizeof(mime_content_type));
1200                         striplt(mime_content_type);
1201                         len = strlen(mime_content_type);
1202                         for (i=0; i<len; ++i) {
1203                                 if (!strncasecmp(&mime_content_type[i], "charset=", 8)) {
1204                                         safestrncpy(mime_charset, &mime_content_type[i+8],
1205                                                 sizeof mime_charset);
1206                                 }
1207                         }
1208                         for (i=0; i<len; ++i) {
1209                                 if (mime_content_type[i] == ';') {
1210                                         mime_content_type[i] = 0;
1211                                         len = i - 1;
1212                                 }
1213                         }
1214                         len = strlen(mime_charset);
1215                         for (i=0; i<len; ++i) {
1216                                 if (mime_charset[i] == ';') {
1217                                         mime_charset[i] = 0;
1218                                         len = i - 1;
1219                                 }
1220                         }
1221                 }
1222         }
1223
1224         /* Set up a character set conversion if we need to (and if we can) */
1225 #ifdef HAVE_ICONV
1226         if (strchr(mime_charset, ';')) strcpy(strchr(mime_charset, ';'), "");
1227         if ( (strcasecmp(mime_charset, "us-ascii"))
1228            && (strcasecmp(mime_charset, "UTF-8"))
1229            && (strcasecmp(mime_charset, ""))
1230         ) {
1231                 ic = ctdl_iconv_open("UTF-8", mime_charset);
1232                 if (ic == (iconv_t)(-1) ) {
1233                         lprintf(5, "%s:%d iconv_open(UTF-8, %s) failed: %s\n",
1234                                 __FILE__, __LINE__, mime_charset, strerror(errno));
1235                 }
1236         }
1237 #endif
1238
1239         /* Messages in legacy Citadel variformat get handled thusly... */
1240         if (!strcasecmp(mime_content_type, "text/x-citadel-variformat")) {
1241                 fmout("JUSTIFY");
1242         }
1243
1244         /* Boring old 80-column fixed format text gets handled this way... */
1245         else if ( (!strcasecmp(mime_content_type, "text/plain"))
1246                 || (!strcasecmp(mime_content_type, "text")) ) {
1247                 buf [0] = '\0';
1248                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1249                         int len;
1250                         len = strlen(buf);
1251                         if ((len > 0) && buf[len-1] == '\n') buf[--len] = 0;
1252                         if ((len > 0) && buf[len-1] == '\r') buf[--len] = 0;
1253
1254 #ifdef HAVE_ICONV
1255                         if (ic != (iconv_t)(-1) ) {
1256                                 ibuf = buf;
1257                                 ibuflen = strlen(ibuf);
1258                                 obuflen = SIZ;
1259                                 obuf = (char *) malloc(obuflen);
1260                                 osav = obuf;
1261                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1262                                 osav[SIZ-obuflen] = 0;
1263                                 safestrncpy(buf, osav, sizeof buf);
1264                                 free(osav);
1265                         }
1266 #endif
1267
1268                         len = strlen(buf);
1269                         while ((!IsEmptyStr(buf)) && (isspace(buf[len-1])))
1270                                 buf[--len] = 0;
1271                         if ((bq == 0) &&
1272                         ((!strncmp(buf, ">", 1)) || (!strncmp(buf, " >", 2)) )) {
1273                                 wprintf("<blockquote>");
1274                                 bq = 1;
1275                         } else if ((bq == 1) &&
1276                                 (strncmp(buf, ">", 1)) && (strncmp(buf, " >", 2)) ) {
1277                                 wprintf("</blockquote>");
1278                                 bq = 0;
1279                         }
1280                         wprintf("<tt>");
1281                         url(buf, sizeof(buf));
1282                         escputs(buf);
1283                         wprintf("</tt><br />\n");
1284                 }
1285                 wprintf("</i><br />");
1286         }
1287
1288         else /** HTML is fun, but we've got to strip it first */
1289         if (!strcasecmp(mime_content_type, "text/html")) {
1290                 output_html(mime_charset, (WC->wc_view == VIEW_WIKI ? 1 : 0));
1291         }
1292
1293         /** Unknown weirdness */
1294         else {
1295                 wprintf(_("I don't know how to display %s"), mime_content_type);
1296                 wprintf("<br />\n", mime_content_type);
1297                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) { }
1298         }
1299
1300 ENDBODY:        /* If there are attached submessages, display them now... */
1301
1302         if ( (!IsEmptyStr(mime_submessages)) && (!section[0]) ) {
1303                 for (i=0; i<num_tokens(mime_submessages, '|'); ++i) {
1304                         extract_token(buf, mime_submessages, i, '|', sizeof buf);
1305                         /** use printable_view to suppress buttons */
1306                         wprintf("<blockquote>");
1307                         read_message(msgnum, 1, buf);
1308                         wprintf("</blockquote>");
1309                 }
1310         }
1311
1312
1313         /** Afterwards, offer links to download attachments 'n' such */
1314         if ( (num_attach_links > 0) && (!section[0]) ) {
1315                 for (i=0; i<num_attach_links; ++i) {
1316                         if (strcasecmp(attach_links[i].partnum, msg4_partnum)) {
1317                                 wprintf("%s", attach_links[i].html);
1318                         }
1319                 }
1320         }
1321
1322         /** Handler for vCard parts */
1323         if (!IsEmptyStr(vcard_partnum)) {
1324                 part_source = load_mimepart(msgnum, vcard_partnum);
1325                 if (part_source != NULL) {
1326
1327                         /** If it's my vCard I can edit it */
1328                         if (    (!strcasecmp(WC->wc_roomname, USERCONFIGROOM))
1329                                 || (!strcasecmp(&WC->wc_roomname[11], USERCONFIGROOM))
1330                                 || (WC->wc_view == VIEW_ADDRESSBOOK)
1331                         ) {
1332                                 wprintf("<a href=\"edit_vcard?"
1333                                         "msgnum=%ld?partnum=%s\">",
1334                                         msgnum, vcard_partnum);
1335                                 wprintf("[%s]</a>", _("edit"));
1336                         }
1337
1338                         /** In all cases, display the full card */
1339                         display_vcard(part_source, 0, 1, NULL);
1340                 }
1341         }
1342
1343         /** Handler for calendar parts */
1344         if (!IsEmptyStr(cal_partnum)) {
1345                 part_source = load_mimepart(msgnum, cal_partnum);
1346                 if (part_source != NULL) {
1347                         cal_process_attachment(part_source,
1348                                                 msgnum, cal_partnum);
1349                 }
1350         }
1351
1352         if (part_source) {
1353                 free(part_source);
1354                 part_source = NULL;
1355         }
1356
1357         wprintf("</div>\n");
1358
1359         /** end everythingamundo table */
1360         if (!printable_view) {
1361                 wprintf("</div>\n");
1362         }
1363
1364         if (num_attach_links > 0) {
1365                 free(attach_links);
1366         }
1367
1368 #ifdef HAVE_ICONV
1369         if (ic != (iconv_t)(-1) ) {
1370                 iconv_close(ic);
1371         }
1372 #endif
1373 }
1374
1375
1376
1377 /**
1378  * \brief Unadorned HTML output of an individual message, suitable
1379  * for placing in a hidden iframe, for printing, or whatever
1380  *
1381  * \param msgnum_as_string Message number, as a string instead of as a long int
1382  */
1383 void embed_message(char *msgnum_as_string) {
1384         long msgnum = 0L;
1385
1386         msgnum = atol(msgnum_as_string);
1387         begin_ajax_response();
1388         read_message(msgnum, 0, "");
1389         end_ajax_response();
1390 }
1391
1392
1393 /**
1394  * \brief Printable view of a message
1395  *
1396  * \param msgnum_as_string Message number, as a string instead of as a long int
1397  */
1398 void print_message(char *msgnum_as_string) {
1399         long msgnum = 0L;
1400
1401         msgnum = atol(msgnum_as_string);
1402         output_headers(0, 0, 0, 0, 0, 0);
1403
1404         wprintf("Content-type: text/html\r\n"
1405                 "Server: %s\r\n"
1406                 "Connection: close\r\n",
1407                 PACKAGE_STRING);
1408         begin_burst();
1409
1410         wprintf("\r\n\r\n<html>\n"
1411                 "<head><title>Printable view</title></head>\n"
1412                 "<body onLoad=\" window.print(); window.close(); \">\n"
1413         );
1414         
1415         read_message(msgnum, 1, "");
1416
1417         wprintf("\n</body></html>\n\n");
1418         wDumpContent(0);
1419 }
1420
1421
1422
1423 /**
1424  * \brief Display a message's headers
1425  *
1426  * \param msgnum_as_string Message number, as a string instead of as a long int
1427  */
1428 void display_headers(char *msgnum_as_string) {
1429         long msgnum = 0L;
1430         char buf[1024];
1431
1432         msgnum = atol(msgnum_as_string);
1433         output_headers(0, 0, 0, 0, 0, 0);
1434
1435         wprintf("Content-type: text/plain\r\n"
1436                 "Server: %s\r\n"
1437                 "Connection: close\r\n",
1438                 PACKAGE_STRING);
1439         begin_burst();
1440
1441         serv_printf("MSG2 %ld|3", msgnum);
1442         serv_getln(buf, sizeof buf);
1443         if (buf[0] == '1') {
1444                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1445                         wprintf("%s\n", buf);
1446                 }
1447         }
1448
1449         wDumpContent(0);
1450 }
1451
1452
1453
1454 /**
1455  * \brief Read message in simple, JavaScript-embeddable form for 'forward'
1456  *      or 'reply quoted' operations.
1457  *
1458  * NOTE: it is VITALLY IMPORTANT that we output no single-quotes or linebreaks
1459  *       in this function.  Doing so would throw a JavaScript error in the
1460  *       'supplied text' argument to the editor.
1461  *
1462  * \param msgnum Message number of the message we want to quote
1463  * \param forward_attachments Nonzero if we want attachments to be forwarded
1464  */
1465 void pullquote_message(long msgnum, int forward_attachments, int include_headers) {
1466         char buf[SIZ];
1467         char mime_partnum[256];
1468         char mime_filename[256];
1469         char mime_content_type[256];
1470         char mime_charset[256];
1471         char mime_disposition[256];
1472         int mime_length;
1473         char *attachments = NULL;
1474         char *ptr = NULL;
1475         int num_attachments = 0;
1476         struct wc_attachment *att, *aptr;
1477         char m_subject[1024];
1478         char from[256];
1479         char node[256];
1480         char rfca[256];
1481         char to[256];
1482         char reply_to[512];
1483         char now[256];
1484         int format_type = 0;
1485         int nhdr = 0;
1486         int bq = 0;
1487         int i = 0;
1488 #ifdef HAVE_ICONV
1489         iconv_t ic = (iconv_t)(-1) ;
1490         char *ibuf;                /**< Buffer of characters to be converted */
1491         char *obuf;                /**< Buffer for converted characters      */
1492         size_t ibuflen;    /**< Length of input buffer         */
1493         size_t obuflen;    /**< Length of output buffer       */
1494         char *osav;                /**< Saved pointer to output buffer       */
1495 #endif
1496
1497         strcpy(from, "");
1498         strcpy(node, "");
1499         strcpy(rfca, "");
1500         strcpy(reply_to, "");
1501         strcpy(mime_content_type, "text/plain");
1502         strcpy(mime_charset, "us-ascii");
1503
1504         serv_printf("MSG4 %ld", msgnum);
1505         serv_getln(buf, sizeof buf);
1506         if (buf[0] != '1') {
1507                 wprintf(_("ERROR:"));
1508                 wprintf("%s<br />", &buf[4]);
1509                 return;
1510         }
1511
1512         strcpy(m_subject, "");
1513
1514         while (serv_getln(buf, sizeof buf), strcasecmp(buf, "text")) {
1515                 if (!strcmp(buf, "000")) {
1516                         wprintf("%s (3)", _("unexpected end of message"));
1517                         return;
1518                 }
1519                 if (include_headers) {
1520                         if (!strncasecmp(buf, "nhdr=yes", 8))
1521                                 nhdr = 1;
1522                         if (nhdr == 1)
1523                                 buf[0] = '_';
1524                         if (!strncasecmp(buf, "type=", 5))
1525                                 format_type = atoi(&buf[5]);
1526                         if (!strncasecmp(buf, "from=", 5)) {
1527                                 strcpy(from, &buf[5]);
1528                                 wprintf(_("from "));
1529                                 utf8ify_rfc822_string(from);
1530                                 msgescputs(from);
1531                         }
1532                         if (!strncasecmp(buf, "subj=", 5)) {
1533                                 strcpy(m_subject, &buf[5]);
1534                         }
1535                         if ((!strncasecmp(buf, "hnod=", 5))
1536                             && (strcasecmp(&buf[5], serv_info.serv_humannode))) {
1537                                 wprintf("(%s) ", &buf[5]);
1538                         }
1539                         if ((!strncasecmp(buf, "room=", 5))
1540                             && (strcasecmp(&buf[5], WC->wc_roomname))
1541                             && (!IsEmptyStr(&buf[5])) ) {
1542                                 wprintf(_("in "));
1543                                 wprintf("%s&gt; ", &buf[5]);
1544                         }
1545                         if (!strncasecmp(buf, "rfca=", 5)) {
1546                                 strcpy(rfca, &buf[5]);
1547                                 wprintf("&lt;");
1548                                 msgescputs(rfca);
1549                                 wprintf("&gt; ");
1550                         }
1551                         if (!strncasecmp(buf, "node=", 5)) {
1552                                 strcpy(node, &buf[5]);
1553                                 if ( ((WC->room_flags & QR_NETWORK)
1554                                 || ((strcasecmp(&buf[5], serv_info.serv_nodename)
1555                                 && (strcasecmp(&buf[5], serv_info.serv_fqdn)))))
1556                                 && (IsEmptyStr(rfca))
1557                                 ) {
1558                                         wprintf("@%s ", &buf[5]);
1559                                 }
1560                         }
1561                         if (!strncasecmp(buf, "rcpt=", 5)) {
1562                                 wprintf(_("to "));
1563                                 strcpy(to, &buf[5]);
1564                                 utf8ify_rfc822_string(to);
1565                                 wprintf("%s ", to);
1566                         }
1567                         if (!strncasecmp(buf, "time=", 5)) {
1568                                 webcit_fmt_date(now, atol(&buf[5]), 0);
1569                                 wprintf("%s ", now);
1570                         }
1571                 }
1572
1573                 /**
1574                  * Save attachment info for later.  We can't start downloading them
1575                  * yet because we're in the middle of a server transaction.
1576                  */
1577                 if (!strncasecmp(buf, "part=", 5)) {
1578                         ptr = malloc( (strlen(buf) + ((attachments != NULL) ? strlen(attachments) : 0)) ) ;
1579                         if (ptr != NULL) {
1580                                 ++num_attachments;
1581                                 sprintf(ptr, "%s%s\n",
1582                                         ((attachments != NULL) ? attachments : ""),
1583                                         &buf[5]
1584                                 );
1585                                 free(attachments);
1586                                 attachments = ptr;
1587                                 lprintf(9, "attachments=<%s>\n", attachments);
1588                         }
1589                 }
1590
1591         }
1592
1593         if (include_headers) {
1594                 wprintf("<br>");
1595
1596                 utf8ify_rfc822_string(m_subject);
1597                 if (!IsEmptyStr(m_subject)) {
1598                         wprintf(_("Subject:"));
1599                         wprintf(" ");
1600                         msgescputs(m_subject);
1601                         wprintf("<br />");
1602                 }
1603
1604                 /**
1605                  * Begin body
1606                  */
1607                 wprintf("<br />");
1608         }
1609
1610         /**
1611          * Learn the content type
1612          */
1613         strcpy(mime_content_type, "text/plain");
1614         while (serv_getln(buf, sizeof buf), (!IsEmptyStr(buf))) {
1615                 if (!strcmp(buf, "000")) {
1616                         wprintf("%s (4)", _("unexpected end of message"));
1617                         goto ENDBODY;
1618                 }
1619                 if (!strncasecmp(buf, "Content-type: ", 14)) {
1620                         int len;
1621                         safestrncpy(mime_content_type, &buf[14],
1622                                 sizeof(mime_content_type));
1623                         for (i=0; i<strlen(mime_content_type); ++i) {
1624                                 if (!strncasecmp(&mime_content_type[i], "charset=", 8)) {
1625                                         safestrncpy(mime_charset, &mime_content_type[i+8],
1626                                                 sizeof mime_charset);
1627                                 }
1628                         }
1629                         len = strlen(mime_content_type);
1630                         for (i=0; i<len; ++i) {
1631                                 if (mime_content_type[i] == ';') {
1632                                         mime_content_type[i] = 0;
1633                                         len = i - 1;
1634                                 }
1635                         }
1636                         len = strlen(mime_charset);
1637                         for (i=0; i<len; ++i) {
1638                                 if (mime_charset[i] == ';') {
1639                                         mime_charset[i] = 0;
1640                                         len = i - 1;
1641                                 }
1642                         }
1643                 }
1644         }
1645
1646         /** Set up a character set conversion if we need to (and if we can) */
1647 #ifdef HAVE_ICONV
1648         if ( (strcasecmp(mime_charset, "us-ascii"))
1649            && (strcasecmp(mime_charset, "UTF-8"))
1650            && (strcasecmp(mime_charset, ""))
1651         ) {
1652                 ic = ctdl_iconv_open("UTF-8", mime_charset);
1653                 if (ic == (iconv_t)(-1) ) {
1654                         lprintf(5, "%s:%d iconv_open(%s, %s) failed: %s\n",
1655                                 __FILE__, __LINE__, "UTF-8", mime_charset, strerror(errno));
1656                 }
1657         }
1658 #endif
1659
1660         /** Messages in legacy Citadel variformat get handled thusly... */
1661         if (!strcasecmp(mime_content_type, "text/x-citadel-variformat")) {
1662                 pullquote_fmout();
1663         }
1664
1665         /* Boring old 80-column fixed format text gets handled this way... */
1666         else if (!strcasecmp(mime_content_type, "text/plain")) {
1667                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1668                         int len;
1669                         len = strlen(buf);
1670                         if (buf[len-1] == '\n') buf[--len] = 0;
1671                         if (buf[len-1] == '\r') buf[--len] = 0;
1672
1673 #ifdef HAVE_ICONV
1674                         if (ic != (iconv_t)(-1) ) {
1675                                 ibuf = buf;
1676                                 ibuflen = len;
1677                                 obuflen = SIZ;
1678                                 obuf = (char *) malloc(obuflen);
1679                                 osav = obuf;
1680                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1681                                 osav[SIZ-obuflen] = 0;
1682                                 safestrncpy(buf, osav, sizeof buf);
1683                                 free(osav);
1684                         }
1685 #endif
1686
1687                         len = strlen(buf);
1688                         while ((!IsEmptyStr(buf)) && (isspace(buf[len - 1]))) 
1689                                 buf[--len] = 0;
1690                         if ((bq == 0) &&
1691                         ((!strncmp(buf, ">", 1)) || (!strncmp(buf, " >", 2)) )) {
1692                                 wprintf("<blockquote>");
1693                                 bq = 1;
1694                         } else if ((bq == 1) &&
1695                                 (strncmp(buf, ">", 1)) && (strncmp(buf, " >", 2)) ) {
1696                                 wprintf("</blockquote>");
1697                                 bq = 0;
1698                         }
1699                         wprintf("<tt>");
1700                         url(buf, sizeof(buf));
1701                         msgescputs1(buf);
1702                         wprintf("</tt><br />");
1703                 }
1704                 wprintf("</i><br />");
1705         }
1706
1707         /** HTML just gets escaped and stuffed back into the editor */
1708         else if (!strcasecmp(mime_content_type, "text/html")) {
1709                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1710                         strcat(buf, "\n");
1711                         msgescputs(buf);
1712                 }
1713         }//// TODO: charset? utf8?
1714
1715         /** Unknown weirdness ... don't know how to handle this content type */
1716         else {
1717                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) { }
1718         }
1719
1720 ENDBODY:
1721         /** end of body handler */
1722
1723         /*
1724          * If there were attachments, we have to download them and insert them
1725          * into the attachment chain for the forwarded message we are composing.
1726          */
1727         if ( (forward_attachments) && (num_attachments) ) {
1728                 for (i=0; i<num_attachments; ++i) {
1729                         extract_token(buf, attachments, i, '\n', sizeof buf);
1730                         extract_token(mime_filename, buf, 1, '|', sizeof mime_filename);
1731                         extract_token(mime_partnum, buf, 2, '|', sizeof mime_partnum);
1732                         extract_token(mime_disposition, buf, 3, '|', sizeof mime_disposition);
1733                         extract_token(mime_content_type, buf, 4, '|', sizeof mime_content_type);
1734                         mime_length = extract_int(buf, 5);
1735
1736                         /*
1737                          * tracing  ... uncomment if necessary
1738                          *
1739                          */
1740                         lprintf(9, "fwd filename: %s\n", mime_filename);
1741                         lprintf(9, "fwd partnum : %s\n", mime_partnum);
1742                         lprintf(9, "fwd conttype: %s\n", mime_content_type);
1743                         lprintf(9, "fwd dispose : %s\n", mime_disposition);
1744                         lprintf(9, "fwd length  : %d\n", mime_length);
1745
1746                         if ( (!strcasecmp(mime_disposition, "inline"))
1747                            || (!strcasecmp(mime_disposition, "attachment")) ) {
1748                 
1749                                 /* Create an attachment struct from this mime part... */
1750                                 att = malloc(sizeof(struct wc_attachment));
1751                                 memset(att, 0, sizeof(struct wc_attachment));
1752                                 att->length = mime_length;
1753                                 strcpy(att->content_type, mime_content_type);
1754                                 strcpy(att->filename, mime_filename);
1755                                 att->next = NULL;
1756                                 att->data = load_mimepart(msgnum, mime_partnum);
1757                 
1758                                 /* And add it to the list. */
1759                                 if (WC->first_attachment == NULL) {
1760                                         WC->first_attachment = att;
1761                                 }
1762                                 else {
1763                                         aptr = WC->first_attachment;
1764                                         while (aptr->next != NULL) aptr = aptr->next;
1765                                         aptr->next = att;
1766                                 }
1767                         }
1768
1769                 }
1770         }
1771
1772 #ifdef HAVE_ICONV
1773         if (ic != (iconv_t)(-1) ) {
1774                 iconv_close(ic);
1775         }
1776 #endif
1777
1778         if (attachments != NULL) {
1779                 free(attachments);
1780         }
1781 }
1782
1783 /**
1784  * \brief Display one row in the mailbox summary view
1785  *
1786  * \param num The row number to be displayed
1787  */
1788 void display_summarized(int num) {
1789         char datebuf[64];
1790
1791         wprintf("<tr id=\"m%ld\" style=\"font-weight:%s;\" "
1792                 "onMouseDown=\"CtdlMoveMsgMouseDown(event,%ld)\">",
1793                 WC->summ[num].msgnum,
1794                 (WC->summ[num].is_new ? "bold" : "normal"),
1795                 WC->summ[num].msgnum
1796         );
1797
1798         wprintf("<td width=%d%%>", SUBJ_COL_WIDTH_PCT);
1799
1800         escputs(WC->summ[num].subj);//////////////////////////////////TODO: QP DECODE
1801         wprintf("</td>");
1802
1803         wprintf("<td width=%d%%>", SENDER_COL_WIDTH_PCT);
1804         escputs(WC->summ[num].from);
1805         wprintf("</td>");
1806
1807         wprintf("<td width=%d%%>", DATE_PLUS_BUTTONS_WIDTH_PCT);
1808         webcit_fmt_date(datebuf, WC->summ[num].date, 1);        /* brief */
1809         escputs(datebuf);
1810         wprintf("</td>");
1811
1812         wprintf("</tr>\n");
1813 }
1814
1815
1816
1817 /**
1818  * \brief display the adressbook overview
1819  * \param msgnum the citadel message number
1820  * \param alpha what????
1821  */
1822 void display_addressbook(long msgnum, char alpha) {
1823         char buf[SIZ];
1824         char mime_partnum[SIZ];
1825         char mime_filename[SIZ];
1826         char mime_content_type[SIZ];
1827         char mime_disposition[SIZ];
1828         int mime_length;
1829         char vcard_partnum[SIZ];
1830         char *vcard_source = NULL;
1831         struct message_summary summ;
1832
1833         memset(&summ, 0, sizeof(summ));
1834         safestrncpy(summ.subj, _("(no subject)"), sizeof summ.subj);
1835
1836         sprintf(buf, "MSG0 %ld|1", msgnum);     /* ask for headers only */
1837         serv_puts(buf);
1838         serv_getln(buf, sizeof buf);
1839         if (buf[0] != '1') return;
1840
1841         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1842                 if (!strncasecmp(buf, "part=", 5)) {
1843                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
1844                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
1845                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
1846                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
1847                         mime_length = extract_int(&buf[5], 5);
1848
1849                         if (  (!strcasecmp(mime_content_type, "text/x-vcard"))
1850                            || (!strcasecmp(mime_content_type, "text/vcard")) ) {
1851                                 strcpy(vcard_partnum, mime_partnum);
1852                         }
1853
1854                 }
1855         }
1856
1857         if (!IsEmptyStr(vcard_partnum)) {
1858                 vcard_source = load_mimepart(msgnum, vcard_partnum);
1859                 if (vcard_source != NULL) {
1860
1861                         /** Display the summary line */
1862                         display_vcard(vcard_source, alpha, 0, NULL);
1863
1864                         /** If it's my vCard I can edit it */
1865                         if (    (!strcasecmp(WC->wc_roomname, USERCONFIGROOM))
1866                                 || (!strcasecmp(&WC->wc_roomname[11], USERCONFIGROOM))
1867                                 || (WC->wc_view == VIEW_ADDRESSBOOK)
1868                         ) {
1869                                 wprintf("<a href=\"edit_vcard?"
1870                                         "msgnum=%ld?partnum=%s\">",
1871                                         msgnum, vcard_partnum);
1872                                 wprintf("[%s]</a>", _("edit"));
1873                         }
1874
1875                         free(vcard_source);
1876                 }
1877         }
1878
1879 }
1880
1881
1882
1883 /**
1884  * \brief  If it's an old "Firstname Lastname" style record, try to convert it.
1885  * \param namebuf name to analyze, reverse if nescessary
1886  */
1887 void lastfirst_firstlast(char *namebuf) {
1888         char firstname[SIZ];
1889         char lastname[SIZ];
1890         int i;
1891
1892         if (namebuf == NULL) return;
1893         if (strchr(namebuf, ';') != NULL) return;
1894
1895         i = num_tokens(namebuf, ' ');
1896         if (i < 2) return;
1897
1898         extract_token(lastname, namebuf, i-1, ' ', sizeof lastname);
1899         remove_token(namebuf, i-1, ' ');
1900         strcpy(firstname, namebuf);
1901         sprintf(namebuf, "%s; %s", lastname, firstname);
1902 }
1903
1904 /**
1905  * \brief fetch what??? name
1906  * \param msgnum the citadel message number
1907  * \param namebuf where to put the name in???
1908  */
1909 void fetch_ab_name(long msgnum, char *namebuf) {
1910         char buf[SIZ];
1911         char mime_partnum[SIZ];
1912         char mime_filename[SIZ];
1913         char mime_content_type[SIZ];
1914         char mime_disposition[SIZ];
1915         int mime_length;
1916         char vcard_partnum[SIZ];
1917         char *vcard_source = NULL;
1918         int i, len;
1919         struct message_summary summ;
1920
1921         if (namebuf == NULL) return;
1922         strcpy(namebuf, "");
1923
1924         memset(&summ, 0, sizeof(summ));
1925         safestrncpy(summ.subj, "(no subject)", sizeof summ.subj);
1926
1927         sprintf(buf, "MSG0 %ld|0", msgnum);     /** unfortunately we need the mime info now */
1928         serv_puts(buf);
1929         serv_getln(buf, sizeof buf);
1930         if (buf[0] != '1') return;
1931
1932         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1933                 if (!strncasecmp(buf, "part=", 5)) {
1934                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
1935                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
1936                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
1937                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
1938                         mime_length = extract_int(&buf[5], 5);
1939
1940                         if (  (!strcasecmp(mime_content_type, "text/x-vcard"))
1941                            || (!strcasecmp(mime_content_type, "text/vcard")) ) {
1942                                 strcpy(vcard_partnum, mime_partnum);
1943                         }
1944
1945                 }
1946         }
1947
1948         if (!IsEmptyStr(vcard_partnum)) {
1949                 vcard_source = load_mimepart(msgnum, vcard_partnum);
1950                 if (vcard_source != NULL) {
1951
1952                         /* Grab the name off the card */
1953                         display_vcard(vcard_source, 0, 0, namebuf);
1954
1955                         free(vcard_source);
1956                 }
1957         }
1958
1959         lastfirst_firstlast(namebuf);
1960         striplt(namebuf);
1961         len = strlen(namebuf);
1962         for (i=0; i<len; ++i) {
1963                 if (namebuf[i] != ';') return;
1964         }
1965         strcpy(namebuf, _("(no name)"));
1966 }
1967
1968
1969
1970 /**
1971  * \brief Record compare function for sorting address book indices
1972  * \param ab1 adressbook one
1973  * \param ab2 adressbook two
1974  */
1975 int abcmp(const void *ab1, const void *ab2) {
1976         return(strcasecmp(
1977                 (((const struct addrbookent *)ab1)->ab_name),
1978                 (((const struct addrbookent *)ab2)->ab_name)
1979         ));
1980 }
1981
1982
1983 /**
1984  * \brief Helper function for do_addrbook_view()
1985  * Converts a name into a three-letter tab label
1986  * \param tabbuf the tabbuffer to add name to
1987  * \param name the name to add to the tabbuffer
1988  */
1989 void nametab(char *tabbuf, long len, char *name) {
1990         stresc(tabbuf, len, name, 0, 0);
1991         tabbuf[0] = toupper(tabbuf[0]);
1992         tabbuf[1] = tolower(tabbuf[1]);
1993         tabbuf[2] = tolower(tabbuf[2]);
1994         tabbuf[3] = 0;
1995 }
1996
1997
1998 /**
1999  * \brief Render the address book using info we gathered during the scan
2000  * \param addrbook the addressbook to render
2001  * \param num_ab the number of the addressbook
2002  */
2003 void do_addrbook_view(struct addrbookent *addrbook, int num_ab) {
2004         int i = 0;
2005         int displayed = 0;
2006         int bg = 0;
2007         static int NAMESPERPAGE = 60;
2008         int num_pages = 0;
2009         int tabfirst = 0;
2010         char tabfirst_label[64];
2011         int tablast = 0;
2012         char tablast_label[64];
2013         char this_tablabel[64];
2014         int page = 0;
2015         char **tablabels;
2016
2017         if (num_ab == 0) {
2018                 wprintf("<br /><br /><br /><div align=\"center\"><i>");
2019                 wprintf(_("This address book is empty."));
2020                 wprintf("</i></div>\n");
2021                 return;
2022         }
2023
2024         if (num_ab > 1) {
2025                 qsort(addrbook, num_ab, sizeof(struct addrbookent), abcmp);
2026         }
2027
2028         num_pages = (num_ab / NAMESPERPAGE) + 1;
2029
2030         tablabels = malloc(num_pages * sizeof (char *));
2031         if (tablabels == NULL) {
2032                 wprintf("<br /><br /><br /><div align=\"center\"><i>");
2033                 wprintf(_("An internal error has occurred."));
2034                 wprintf("</i></div>\n");
2035                 return;
2036         }
2037
2038         for (i=0; i<num_pages; ++i) {
2039                 tabfirst = i * NAMESPERPAGE;
2040                 tablast = tabfirst + NAMESPERPAGE - 1;
2041                 if (tablast > (num_ab - 1)) tablast = (num_ab - 1);
2042                 nametab(tabfirst_label, 64, addrbook[tabfirst].ab_name);
2043                 nametab(tablast_label, 64, addrbook[tablast].ab_name);
2044                 sprintf(this_tablabel, "%s&nbsp;-&nbsp;%s", tabfirst_label, tablast_label);
2045                 tablabels[i] = strdup(this_tablabel);
2046         }
2047
2048         tabbed_dialog(num_pages, tablabels);
2049         page = (-1);
2050
2051         for (i=0; i<num_ab; ++i) {
2052
2053                 if ((i / NAMESPERPAGE) != page) {       /* New tab */
2054                         page = (i / NAMESPERPAGE);
2055                         if (page > 0) {
2056                                 wprintf("</tr></table>\n");
2057                                 end_tab(page-1, num_pages);
2058                         }
2059                         begin_tab(page, num_pages);
2060                         wprintf("<table border=0 cellspacing=0 cellpadding=3 width=100%%>\n");
2061                         displayed = 0;
2062                 }
2063
2064                 if ((displayed % 4) == 0) {
2065                         if (displayed > 0) {
2066                                 wprintf("</tr>\n");
2067                         }
2068                         bg = 1 - bg;
2069                         wprintf("<tr bgcolor=\"#%s\">",
2070                                 (bg ? "DDDDDD" : "FFFFFF")
2071                         );
2072                 }
2073         
2074                 wprintf("<td>");
2075
2076                 wprintf("<a href=\"readfwd?startmsg=%ld&is_singlecard=1",
2077                         addrbook[i].ab_msgnum);
2078                 wprintf("?maxmsgs=1?is_summary=0?alpha=%s\">", bstr("alpha"));
2079                 vcard_n_prettyize(addrbook[i].ab_name);
2080                 escputs(addrbook[i].ab_name);
2081                 wprintf("</a></td>\n");
2082                 ++displayed;
2083         }
2084
2085         wprintf("</tr></table>\n");
2086         end_tab((num_pages-1), num_pages);
2087
2088         for (i=0; i<num_pages; ++i) {
2089                 free(tablabels[i]);
2090         }
2091         free(tablabels);
2092 }
2093
2094
2095
2096 /**
2097  * \brief load message pointers from the server
2098  * \param servcmd the citadel command to send to the citserver
2099  * \param with_headers what headers???
2100  */
2101 int load_msg_ptrs(char *servcmd, int with_headers)
2102 {
2103         char buf[1024];
2104         time_t datestamp;
2105         char fullname[128];
2106         char nodename[128];
2107         char inetaddr[128];
2108         char subject[1024];
2109         int nummsgs;
2110         int sbjlen;
2111         int maxload = 0;
2112
2113         int num_summ_alloc = 0;
2114
2115         if (WC->summ != NULL) {
2116                 free(WC->summ);
2117                 WC->num_summ = 0;
2118                 WC->summ = NULL;
2119         }
2120         num_summ_alloc = 100;
2121         WC->num_summ = 0;
2122         WC->summ = malloc(num_summ_alloc * sizeof(struct message_summary));
2123
2124         nummsgs = 0;
2125         maxload = sizeof(WC->msgarr) / sizeof(long) ;
2126         serv_puts(servcmd);
2127         serv_getln(buf, sizeof buf);
2128         if (buf[0] != '1') {
2129                 return (nummsgs);
2130         }
2131         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
2132                 if (nummsgs < maxload) {
2133                         WC->msgarr[nummsgs] = extract_long(buf, 0);
2134                         datestamp = extract_long(buf, 1);
2135                         extract_token(fullname, buf, 2, '|', sizeof fullname);
2136                         extract_token(nodename, buf, 3, '|', sizeof nodename);
2137                         extract_token(inetaddr, buf, 4, '|', sizeof inetaddr);
2138                         extract_token(subject, buf, 5, '|', sizeof subject);
2139                         ++nummsgs;
2140
2141                         if (with_headers) {
2142                                 if (nummsgs > num_summ_alloc) {
2143                                         num_summ_alloc *= 2;
2144                                         WC->summ = realloc(WC->summ,
2145                                                 num_summ_alloc * sizeof(struct message_summary));
2146                                 }
2147                                 ++WC->num_summ;
2148
2149                                 memset(&WC->summ[nummsgs-1], 0, sizeof(struct message_summary));
2150                                 WC->summ[nummsgs-1].msgnum = WC->msgarr[nummsgs-1];
2151                                 safestrncpy(WC->summ[nummsgs-1].subj,
2152                                         _("(no subject)"), sizeof WC->summ[nummsgs-1].subj);
2153                                 if (!IsEmptyStr(fullname)) {
2154                                 /** Handle senders with RFC2047 encoding */
2155                                         utf8ify_rfc822_string(fullname);
2156                                         safestrncpy(WC->summ[nummsgs-1].from,
2157                                                 fullname, sizeof WC->summ[nummsgs-1].from);
2158                                 }
2159                                 if (!IsEmptyStr(subject)) {
2160                                 /** Handle subjects with RFC2047 encoding */
2161                                         utf8ify_rfc822_string(subject);
2162                                         safestrncpy(WC->summ[nummsgs-1].subj, subject,
2163                                                     sizeof WC->summ[nummsgs-1].subj);
2164                                 }
2165                                 sbjlen = Ctdl_Utf8StrLen(WC->summ[nummsgs-1].subj);
2166                                 if (sbjlen > 75) {
2167                                         char *ptr;
2168                                         ptr = Ctdl_Utf8StrCut(WC->summ[nummsgs-1].subj, 72);
2169
2170                                         strcpy(ptr, "...");
2171                                 }
2172
2173                                 if (!IsEmptyStr(nodename)) {
2174                                         if ( ((WC->room_flags & QR_NETWORK)
2175                                            || ((strcasecmp(nodename, serv_info.serv_nodename)
2176                                            && (strcasecmp(nodename, serv_info.serv_fqdn)))))
2177                                         ) {
2178                                                 strcat(WC->summ[nummsgs-1].from, " @ ");
2179                                                 strcat(WC->summ[nummsgs-1].from, nodename);
2180                                         }
2181                                 }
2182
2183                                 WC->summ[nummsgs-1].date = datestamp;
2184         
2185                                 /** Handle senders with RFC2047 encoding */
2186                                 utf8ify_rfc822_string(WC->summ[nummsgs-1].from);
2187                                 if (strlen(WC->summ[nummsgs-1].from) > 25) {
2188                                         strcpy(&WC->summ[nummsgs-1].from[22], "...");
2189                                 }
2190                         }
2191                 }
2192         }
2193         return (nummsgs);
2194 }
2195
2196 /**
2197  * \brief qsort() compatible function to compare two longs in descending order.
2198  *
2199  * \param s1 first number to compare 
2200  * \param s2 second number to compare
2201  */
2202 int longcmp_r(const void *s1, const void *s2) {
2203         long l1;
2204         long l2;
2205
2206         l1 = *(long *)s1;
2207         l2 = *(long *)s2;
2208
2209         if (l1 > l2) return(-1);
2210         if (l1 < l2) return(+1);
2211         return(0);
2212 }
2213
2214  
2215 /**
2216  * \brief qsort() compatible function to compare two message summary structs by ascending subject.
2217  *
2218  * \param s1 first item to compare 
2219  * \param s2 second item to compare
2220  */
2221 int summcmp_subj(const void *s1, const void *s2) {
2222         struct message_summary *summ1;
2223         struct message_summary *summ2;
2224         
2225         summ1 = (struct message_summary *)s1;
2226         summ2 = (struct message_summary *)s2;
2227         return strcasecmp(summ1->subj, summ2->subj);
2228 }
2229
2230 /**
2231  * \brief qsort() compatible function to compare two message summary structs by descending subject.
2232  *
2233  * \param s1 first item to compare 
2234  * \param s2 second item to compare
2235  */
2236 int summcmp_rsubj(const void *s1, const void *s2) {
2237         struct message_summary *summ1;
2238         struct message_summary *summ2;
2239         
2240         summ1 = (struct message_summary *)s1;
2241         summ2 = (struct message_summary *)s2;
2242         return strcasecmp(summ2->subj, summ1->subj);
2243 }
2244
2245 /**
2246  * \brief qsort() compatible function to compare two message summary structs by ascending sender.
2247  *
2248  * \param s1 first item to compare 
2249  * \param s2 second item to compare
2250  */
2251 int summcmp_sender(const void *s1, const void *s2) {
2252         struct message_summary *summ1;
2253         struct message_summary *summ2;
2254         
2255         summ1 = (struct message_summary *)s1;
2256         summ2 = (struct message_summary *)s2;
2257         return strcasecmp(summ1->from, summ2->from);
2258 }
2259
2260 /**
2261  * \brief qsort() compatible function to compare two message summary structs by descending sender.
2262  *
2263  * \param s1 first item to compare 
2264  * \param s2 second item to compare
2265  */
2266 int summcmp_rsender(const void *s1, const void *s2) {
2267         struct message_summary *summ1;
2268         struct message_summary *summ2;
2269         
2270         summ1 = (struct message_summary *)s1;
2271         summ2 = (struct message_summary *)s2;
2272         return strcasecmp(summ2->from, summ1->from);
2273 }
2274
2275 /**
2276  * \brief qsort() compatible function to compare two message summary structs by ascending date.
2277  *
2278  * \param s1 first item to compare 
2279  * \param s2 second item to compare
2280  */
2281 int summcmp_date(const void *s1, const void *s2) {
2282         struct message_summary *summ1;
2283         struct message_summary *summ2;
2284         
2285         summ1 = (struct message_summary *)s1;
2286         summ2 = (struct message_summary *)s2;
2287
2288         if (summ1->date < summ2->date) return -1;
2289         else if (summ1->date > summ2->date) return +1;
2290         else return 0;
2291 }
2292
2293 /**
2294  * \brief qsort() compatible function to compare two message summary structs by descending date.
2295  *
2296  * \param s1 first item to compare 
2297  * \param s2 second item to compare
2298  */
2299 int summcmp_rdate(const void *s1, const void *s2) {
2300         struct message_summary *summ1;
2301         struct message_summary *summ2;
2302         
2303         summ1 = (struct message_summary *)s1;
2304         summ2 = (struct message_summary *)s2;
2305
2306         if (summ1->date < summ2->date) return +1;
2307         else if (summ1->date > summ2->date) return -1;
2308         else return 0;
2309 }
2310
2311
2312
2313 /**
2314  * \brief command loop for reading messages
2315  *
2316  * \param oper Set to "readnew" or "readold" or "readfwd" or "headers"
2317  */
2318 void readloop(char *oper)
2319 {
2320         char cmd[256] = "";
2321         char buf[SIZ];
2322         char old_msgs[SIZ];
2323         int a, b;
2324         int nummsgs;
2325         long startmsg;
2326         int maxmsgs;
2327         long *displayed_msgs = NULL;
2328         int num_displayed = 0;
2329         int is_summary = 0;
2330         int is_addressbook = 0;
2331         int is_singlecard = 0;
2332         int is_calendar = 0;
2333         int is_tasks = 0;
2334         int is_notes = 0;
2335         int is_bbview = 0;
2336         int lo, hi;
2337         int lowest_displayed = (-1);
2338         int highest_displayed = 0;
2339         struct addrbookent *addrbook = NULL;
2340         int num_ab = 0;
2341         char *sortby = NULL;
2342         char sortpref_name[128];
2343         char sortpref_value[128];
2344         char *subjsort_button;
2345         char *sendsort_button;
2346         char *datesort_button;
2347         int bbs_reverse = 0;
2348         struct wcsession *WCC = WC;     /* This is done to make it run faster; WC is a function */
2349
2350         if (WCC->wc_view == VIEW_WIKI) {
2351                 sprintf(buf, "wiki?room=%s?page=home", WCC->wc_roomname);
2352                 http_redirect(buf);
2353                 return;
2354         }
2355
2356         startmsg = lbstr("startmsg");
2357         maxmsgs = ibstr("maxmsgs");
2358         is_summary = ibstr("is_summary");
2359         if (maxmsgs == 0) maxmsgs = DEFAULT_MAXMSGS;
2360
2361         snprintf(sortpref_name, sizeof sortpref_name, "sort %s", WCC->wc_roomname);
2362         get_preference(sortpref_name, sortpref_value, sizeof sortpref_value);
2363
2364         sortby = bstr("sortby");
2365         if ( (!IsEmptyStr(sortby)) && (strcasecmp(sortby, sortpref_value)) ) {
2366                 set_preference(sortpref_name, sortby, 1);
2367         }
2368         if (IsEmptyStr(sortby)) sortby = sortpref_value;
2369
2370         /** mailbox sort */
2371         if (IsEmptyStr(sortby)) sortby = "rdate";
2372
2373         /** message board sort */
2374         if (!strcasecmp(sortby, "reverse")) {
2375                 bbs_reverse = 1;
2376         }
2377         else {
2378                 bbs_reverse = 0;
2379         }
2380
2381         output_headers(1, 1, 1, 0, 0, 0);
2382
2383         /**
2384          * When in summary mode, always show ALL messages instead of just
2385          * new or old.  Otherwise, show what the user asked for.
2386          */
2387         if (!strcmp(oper, "readnew")) {
2388                 strcpy(cmd, "MSGS NEW");
2389         }
2390         else if (!strcmp(oper, "readold")) {
2391                 strcpy(cmd, "MSGS OLD");
2392         }
2393         else if (!strcmp(oper, "do_search")) {
2394                 snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
2395         }
2396         else {
2397                 strcpy(cmd, "MSGS ALL");
2398         }
2399
2400         if ((WCC->wc_view == VIEW_MAILBOX) && (maxmsgs > 1)) {
2401                 is_summary = 1;
2402                 if (!strcmp(oper, "do_search")) {
2403                         snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
2404                 }
2405                 else {
2406                         strcpy(cmd, "MSGS ALL");
2407                 }
2408         }
2409
2410         if ((WCC->wc_view == VIEW_ADDRESSBOOK) && (maxmsgs > 1)) {
2411                 is_addressbook = 1;
2412                 if (!strcmp(oper, "do_search")) {
2413                         snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
2414                 }
2415                 else {
2416                         strcpy(cmd, "MSGS ALL");
2417                 }
2418                 maxmsgs = 9999999;
2419         }
2420
2421         if (is_summary) {                       /**< fetch header summary */
2422                 snprintf(cmd, sizeof(cmd), "MSGS %s|%s||1",
2423                         (!strcmp(oper, "do_search") ? "SEARCH" : "ALL"),
2424                         (!strcmp(oper, "do_search") ? bstr("query") : "")
2425                 );
2426                 startmsg = 1;
2427                 maxmsgs = 9999999;
2428         }
2429
2430         /**
2431          * Are we doing a summary view?  If so, we need to know old messages
2432          * and new messages, so we can do that pretty boldface thing for the
2433          * new messages.
2434          */
2435         strcpy(old_msgs, "");
2436         if ((is_summary) || (WCC->wc_default_view == VIEW_CALENDAR)){
2437                 serv_puts("GTSN");
2438                 serv_getln(buf, sizeof buf);
2439                 if (buf[0] == '2') {
2440                         strcpy(old_msgs, &buf[4]);
2441                 }
2442         }
2443
2444         is_singlecard = ibstr("is_singlecard");
2445
2446         if (WCC->wc_default_view == VIEW_CALENDAR) {            /**< calendar */
2447                 is_calendar = 1;
2448                 strcpy(cmd, "MSGS ALL|||1");
2449                 maxmsgs = 32767;
2450         }
2451         if (WCC->wc_default_view == VIEW_TASKS) {               /**< tasks */
2452                 is_tasks = 1;
2453                 strcpy(cmd, "MSGS ALL");
2454                 maxmsgs = 32767;
2455         }
2456         if (WCC->wc_default_view == VIEW_NOTES) {               /**< notes */
2457                 is_notes = 1;
2458                 strcpy(cmd, "MSGS ALL");
2459                 maxmsgs = 32767;
2460         }
2461
2462         if (is_notes) {
2463                 wprintf("<div align=center>%s</div>\n", _("Click on any note to edit it."));
2464                 wprintf("<div id=\"new_notes_here\"></div>\n");
2465         }
2466
2467         nummsgs = load_msg_ptrs(cmd, is_summary);
2468         if (nummsgs == 0) {
2469
2470                 if ((!is_tasks) && (!is_calendar) && (!is_notes) && (!is_addressbook)) {
2471                         wprintf("<div align=\"center\"><br /><em>");
2472                         if (!strcmp(oper, "readnew")) {
2473                                 wprintf(_("No new messages."));
2474                         } else if (!strcmp(oper, "readold")) {
2475                                 wprintf(_("No old messages."));
2476                         } else {
2477                                 wprintf(_("No messages here."));
2478                         }
2479                         wprintf("</em><br /></div>\n");
2480                 }
2481
2482                 goto DONE;
2483         }
2484
2485         if ((is_summary) || (WCC->wc_default_view == VIEW_CALENDAR)){
2486                 for (a = 0; a < nummsgs; ++a) {
2487                         /** Are you a new message, or an old message? */
2488                         if (is_summary) {
2489                                 if (is_msg_in_mset(old_msgs, WCC->msgarr[a])) {
2490                                         WCC->summ[a].is_new = 0;
2491                                 }
2492                                 else {
2493                                         WCC->summ[a].is_new = 1;
2494                                 }
2495                         }
2496                 }
2497         }
2498
2499         if (startmsg == 0L) {
2500                 if (bbs_reverse) {
2501                         startmsg = WCC->msgarr[(nummsgs >= maxmsgs) ? (nummsgs - maxmsgs) : 0];
2502                 }
2503                 else {
2504                         startmsg = WCC->msgarr[0];
2505                 }
2506         }
2507
2508         if (is_summary) {
2509                 if (!strcasecmp(sortby, "subject")) {
2510                         qsort(WCC->summ, WCC->num_summ,
2511                                 sizeof(struct message_summary), summcmp_subj);
2512                 }
2513                 else if (!strcasecmp(sortby, "rsubject")) {
2514                         qsort(WCC->summ, WCC->num_summ,
2515                                 sizeof(struct message_summary), summcmp_rsubj);
2516                 }
2517                 else if (!strcasecmp(sortby, "sender")) {
2518                         qsort(WCC->summ, WCC->num_summ,
2519                                 sizeof(struct message_summary), summcmp_sender);
2520                 }
2521                 else if (!strcasecmp(sortby, "rsender")) {
2522                         qsort(WCC->summ, WCC->num_summ,
2523                                 sizeof(struct message_summary), summcmp_rsender);
2524                 }
2525                 else if (!strcasecmp(sortby, "date")) {
2526                         qsort(WCC->summ, WCC->num_summ,
2527                                 sizeof(struct message_summary), summcmp_date);
2528                 }
2529                 else if (!strcasecmp(sortby, "rdate")) {
2530                         qsort(WCC->summ, WCC->num_summ,
2531                                 sizeof(struct message_summary), summcmp_rdate);
2532                 }
2533         }
2534
2535         if (!strcasecmp(sortby, "subject")) {
2536                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=rsubject\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2537         }
2538         else if (!strcasecmp(sortby, "rsubject")) {
2539                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=subject\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2540         }
2541         else {
2542                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=subject\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2543         }
2544
2545         if (!strcasecmp(sortby, "sender")) {
2546                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=rsender\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2547         }
2548         else if (!strcasecmp(sortby, "rsender")) {
2549                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=sender\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2550         }
2551         else {
2552                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=sender\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2553         }
2554
2555         if (!strcasecmp(sortby, "date")) {
2556                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=rdate\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2557         }
2558         else if (!strcasecmp(sortby, "rdate")) {
2559                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=date\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2560         }
2561         else {
2562                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=rdate\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2563         }
2564
2565         if (is_summary) {
2566
2567                 wprintf("<script language=\"javascript\" type=\"text/javascript\">"
2568                         " document.onkeydown = CtdlMsgListKeyPress;     "
2569                         " if (document.layers) {                        "
2570                         "       document.captureEvents(Event.KEYPRESS); "
2571                         " }                                             "
2572                         "</script>\n"
2573                 );
2574
2575                 /** note that Date and Delete are now in the same column */
2576                 wprintf("<div id=\"message_list_hdr\">"
2577                         "<div class=\"fix_scrollbar_bug\">"
2578                         "<table cellspacing=0 style=\"width:100%%\">"
2579                         "<tr>"
2580                 );
2581                 wprintf("<th width=%d%%>%s %s</th>"
2582                         "<th width=%d%%>%s %s</th>"
2583                         "<th width=%d%%>%s %s"
2584                         "&nbsp;"
2585                         "<input type=\"submit\" name=\"delete_button\" id=\"delbutton\" "
2586                         " onClick=\"CtdlDeleteSelectedMessages(event)\" "
2587                         " value=\"%s\">"
2588                         "</th>"
2589                         "</tr>\n"
2590                         ,
2591                         SUBJ_COL_WIDTH_PCT,
2592                         _("Subject"),   subjsort_button,
2593                         SENDER_COL_WIDTH_PCT,
2594                         _("Sender"),    sendsort_button,
2595                         DATE_PLUS_BUTTONS_WIDTH_PCT,
2596                         _("Date"),      datesort_button,
2597                         _("Delete")
2598                 );
2599                 wprintf("</table></div></div>\n");
2600
2601                 wprintf("<div id=\"message_list\">"
2602
2603                         "<div class=\"fix_scrollbar_bug\">\n"
2604
2605                         "<table class=\"mailbox_summary\" id=\"summary_headers\" "
2606                         "cellspacing=0 style=\"width:100%%;-moz-user-select:none;\">"
2607                 );
2608         }
2609
2610
2611         /**
2612          * Set the "is_bbview" variable if it appears that we are looking at
2613          * a classic bulletin board view.
2614          */
2615         if ((!is_tasks) && (!is_calendar) && (!is_addressbook)
2616               && (!is_notes) && (!is_singlecard) && (!is_summary)) {
2617                 is_bbview = 1;
2618         }
2619
2620         /**
2621          * If we're not currently looking at ALL requested
2622          * messages, then display the selector bar
2623          */
2624         if (is_bbview) {
2625                 /** begin bbview scroller */
2626                 wprintf("<form name=\"msgomatictop\" class=\"selector_top\" > \n <p>");
2627                 wprintf(_("Reading #"), lowest_displayed, highest_displayed);
2628
2629                 wprintf("<select name=\"whichones\" size=\"1\" "
2630                         "OnChange=\"location.href=msgomatictop.whichones.options"
2631                         "[selectedIndex].value\">\n");
2632
2633                 if (bbs_reverse) {
2634                         for (b=nummsgs-1; b>=0; b = b - maxmsgs) {
2635                                 hi = b + 1;
2636                                 lo = b - maxmsgs + 2;
2637                                 if (lo < 1) lo = 1;
2638                                 wprintf("<option %s value="
2639                                         "\"%s"
2640                                         "?startmsg=%ld"
2641                                         "?maxmsgs=%d"
2642                                         "?is_summary=%d\">"
2643                                         "%d-%d</option> \n",
2644                                         ((WCC->msgarr[lo-1] == startmsg) ? "selected" : ""),
2645                                         oper,
2646                                         WCC->msgarr[lo-1],
2647                                         maxmsgs,
2648                                         is_summary,
2649                                         hi, lo);
2650                         }
2651                 }
2652                 else {
2653                         for (b=0; b<nummsgs; b = b + maxmsgs) {
2654                                 lo = b + 1;
2655                                 hi = b + maxmsgs + 1;
2656                                 if (hi > nummsgs) hi = nummsgs;
2657                                 wprintf("<option %s value="
2658                                         "\"%s"
2659                                         "?startmsg=%ld"
2660                                         "?maxmsgs=%d"
2661                                         "?is_summary=%d\">"
2662                                         "%d-%d</option> \n",
2663                                         ((WCC->msgarr[b] == startmsg) ? "selected" : ""),
2664                                         oper,
2665                                         WCC->msgarr[lo-1],
2666                                         maxmsgs,
2667                                         is_summary,
2668                                         lo, hi);
2669                         }
2670                 }
2671
2672                 wprintf("<option value=\"%s?startmsg=%ld"
2673                         "?maxmsgs=9999999?is_summary=%d\">",
2674                         oper,
2675                         WCC->msgarr[0], is_summary);
2676                 wprintf(_("All"));
2677                 wprintf("</option>");
2678                 wprintf("</select> ");
2679                 wprintf(_("of %d messages."), nummsgs);
2680
2681                 /** forward/reverse */
2682                 wprintf("<input type=\"radio\" %s name=\"direction\" value=\"\""
2683                         "OnChange=\"location.href='%s?sortby=forward'\"",  
2684                         (bbs_reverse ? "" : "checked"),
2685                         oper
2686                 );
2687                 wprintf(">");
2688                 wprintf(_("oldest to newest"));
2689                 wprintf("&nbsp;&nbsp;&nbsp;&nbsp;");
2690
2691                 wprintf("<input type=\"radio\" %s name=\"direction\" value=\"\""
2692                         "OnChange=\"location.href='%s?sortby=reverse'\"", 
2693                         (bbs_reverse ? "checked" : ""),
2694                         oper
2695                 );
2696                 wprintf(">");
2697                 wprintf(_("newest to oldest"));
2698                 wprintf("\n");
2699         
2700                 wprintf("</p></form>\n");
2701                 /** end bbview scroller */
2702         }
2703
2704         if (is_notes)
2705         {
2706                 wprintf ("<script src=\"/static/dragdrop.js\" type=\"text/javascript\"></script>\n");
2707         }
2708
2709
2710
2711         for (a = 0; a < nummsgs; ++a) {
2712                 if ((WCC->msgarr[a] >= startmsg) && (num_displayed < maxmsgs)) {
2713
2714                         /** Display the message */
2715                         if (is_summary) {
2716                                 display_summarized(a);
2717                         }
2718                         else if (is_addressbook) {
2719                                 fetch_ab_name(WCC->msgarr[a], buf);
2720                                 ++num_ab;
2721                                 addrbook = realloc(addrbook,
2722                                         (sizeof(struct addrbookent) * num_ab) );
2723                                 safestrncpy(addrbook[num_ab-1].ab_name, buf,
2724                                         sizeof(addrbook[num_ab-1].ab_name));
2725                                 addrbook[num_ab-1].ab_msgnum = WCC->msgarr[a];
2726                         }
2727                         else if (is_calendar) {
2728                                 display_calendar(WCC->msgarr[a], WCC->summ[a].is_new);
2729                         }
2730                         else if (is_tasks) {
2731                                 display_task(WCC->msgarr[a], WCC->summ[a].is_new);
2732                         }
2733                         else if (is_notes) {
2734                                 display_note(WCC->msgarr[a], WCC->summ[a].is_new);
2735                         }
2736                         else {
2737                                 if (displayed_msgs == NULL) {
2738                                         displayed_msgs = malloc(sizeof(long) *
2739                                                                 (maxmsgs<nummsgs ? maxmsgs : nummsgs));
2740                                 }
2741                                 displayed_msgs[num_displayed] = WCC->msgarr[a];
2742                         }
2743
2744                         if (lowest_displayed < 0) lowest_displayed = a;
2745                         highest_displayed = a;
2746
2747                         ++num_displayed;
2748                 }
2749         }
2750
2751         /** Output loop */
2752         if (displayed_msgs != NULL) {
2753                 if (bbs_reverse) {
2754                         qsort(displayed_msgs, num_displayed, sizeof(long), longcmp_r);
2755                 }
2756
2757                 /** if we do a split bbview in the future, begin messages div here */
2758
2759                 for (a=0; a<num_displayed; ++a) {
2760                         read_message(displayed_msgs[a], 0, "");
2761                 }
2762
2763                 /** if we do a split bbview in the future, end messages div here */
2764
2765                 free(displayed_msgs);
2766                 displayed_msgs = NULL;
2767         }
2768
2769         if (is_summary) {
2770                 wprintf("</table>"
2771                         "</div>\n");                    /**< end of 'fix_scrollbar_bug' div */
2772                 wprintf("</div>");                      /**< end of 'message_list' div */
2773
2774                 /** Here's the grab-it-to-resize-the-message-list widget */
2775                 wprintf("<div id=\"resize_msglist\" "
2776                         "onMouseDown=\"CtdlResizeMsgListMouseDown(event)\">"
2777                         "<div class=\"fix_scrollbar_bug\"> <hr>"
2778                         "</div></div>\n"
2779                 );
2780
2781                 wprintf("<div id=\"preview_pane\">");   /**< The preview pane will initially be empty */
2782         }
2783
2784         /**
2785          * Bump these because although we're thinking in zero base, the user
2786          * is a drooling idiot and is thinking in one base.
2787          */
2788         ++lowest_displayed;
2789         ++highest_displayed;
2790
2791         /**
2792          * If we're not currently looking at ALL requested
2793          * messages, then display the selector bar
2794          */
2795         if (is_bbview) {
2796                 /** begin bbview scroller */
2797                 wprintf("<form name=\"msgomatic\" class=\"selector_bottom\" > \n <p>");
2798                 wprintf(_("Reading #"), lowest_displayed, highest_displayed);
2799
2800                 wprintf("<select name=\"whichones\" size=\"1\" "
2801                         "OnChange=\"location.href=msgomatic.whichones.options"
2802                         "[selectedIndex].value\">\n");
2803
2804                 if (bbs_reverse) {
2805                         for (b=nummsgs-1; b>=0; b = b - maxmsgs) {
2806                                 hi = b + 1;
2807                                 lo = b - maxmsgs + 2;
2808                                 if (lo < 1) lo = 1;
2809                                 wprintf("<option %s value="
2810                                         "\"%s"
2811                                         "?startmsg=%ld"
2812                                         "?maxmsgs=%d"
2813                                         "?is_summary=%d\">"
2814                                         "%d-%d</option> \n",
2815                                         ((WCC->msgarr[lo-1] == startmsg) ? "selected" : ""),
2816                                         oper,
2817                                         WCC->msgarr[lo-1],
2818                                         maxmsgs,
2819                                         is_summary,
2820                                         hi, lo);
2821                         }
2822                 }
2823                 else {
2824                         for (b=0; b<nummsgs; b = b + maxmsgs) {
2825                                 lo = b + 1;
2826                                 hi = b + maxmsgs + 1;
2827                                 if (hi > nummsgs) hi = nummsgs;
2828                                 wprintf("<option %s value="
2829                                         "\"%s"
2830                                         "?startmsg=%ld"
2831                                         "?maxmsgs=%d"
2832                                         "?is_summary=%d\">"
2833                                         "%d-%d</option> \n",
2834                                         ((WCC->msgarr[b] == startmsg) ? "selected" : ""),
2835                                         oper,
2836                                         WCC->msgarr[lo-1],
2837                                         maxmsgs,
2838                                         is_summary,
2839                                         lo, hi);
2840                         }
2841                 }
2842
2843                 wprintf("<option value=\"%s?startmsg=%ld"
2844                         "?maxmsgs=9999999?is_summary=%d\">",
2845                         oper,
2846                         WCC->msgarr[0], is_summary);
2847                 wprintf(_("All"));
2848                 wprintf("</option>");
2849                 wprintf("</select> ");
2850                 wprintf(_("of %d messages."), nummsgs);
2851
2852                 /** forward/reverse */
2853                 wprintf("<input type=\"radio\" %s name=\"direction\" value=\"\""
2854                         "OnChange=\"location.href='%s?sortby=forward'\"",  
2855                         (bbs_reverse ? "" : "checked"),
2856                         oper
2857                 );
2858                 wprintf(">");
2859                 wprintf(_("oldest to newest"));
2860                 wprintf("&nbsp;&nbsp;&nbsp;&nbsp;");
2861                 wprintf("<input type=\"radio\" %s name=\"direction\" value=\"\""
2862                         "OnChange=\"location.href='%s?sortby=reverse'\"", 
2863                         (bbs_reverse ? "checked" : ""),
2864                         oper
2865                 );
2866                 wprintf(">");
2867                 wprintf(_("newest to oldest"));
2868                 wprintf("\n");
2869
2870                 wprintf("</p></form>\n");
2871                 /** end bbview scroller */
2872         }
2873         
2874         if (is_notes)
2875         {
2876 //              wprintf ("</div>\n");
2877                 wprintf ("<div id=\"wastebin\" align=middle>Drop notes here to remove them.</div>\n");
2878                 wprintf ("<script type=\"text/javascript\">\n");
2879 //              wprintf ("//<![CDATA[\n");
2880                 wprintf ("Droppables.add(\"wastebin\",\n");
2881                 wprintf ("\t{\n");
2882                 wprintf ("\t\taccept:'notes',\n");
2883                 wprintf ("\t\tonDrop:function(element)\n");
2884                 wprintf ("\t\t{\n");
2885                 wprintf ("\t\t\tElement.hide(element);\n");
2886                 wprintf ("\t\t\tnew Ajax.Updater('notes', 'delnote',\n");
2887                 wprintf ("\t\t\t{\n");
2888                 wprintf ("\t\t\t\tasynchronous:true,\n");
2889                 wprintf ("\t\t\t\tevalScripts:true,\n");
2890                 wprintf ("\t\t\t\tonComplete:function(request)\n");
2891                 wprintf ("\t\t\t\t{\n");
2892                 wprintf ("\t\t\t\t\tElement.hide('indicator')\n");
2893                 wprintf ("\t\t\t\t},\n");
2894                 wprintf ("\t\t\t\tonLoading:function(request)\n");
2895                 wprintf ("\t\t\t\t{\n");
2896                 wprintf ("\t\t\t\t\tElement.show('indicator')\n");
2897                 wprintf ("\t\t\t\t},\n");
2898                 wprintf ("\t\t\t\tparameters:'id=' + encodeURIComponent(element.id)\n");
2899                 wprintf ("\t\t\t})\n");
2900                 wprintf ("\t\t}\n");
2901                 wprintf ("\t})\n");
2902 //              wprintf ("//]]>\n");
2903                 wprintf ("</script>\n");
2904         }
2905
2906
2907
2908 DONE:
2909         if (is_tasks) {
2910                 do_tasks_view();        /** Render the task list */
2911         }
2912
2913         if (is_calendar) {
2914                 do_calendar_view();     /** Render the calendar */
2915         }
2916
2917         if (is_addressbook) {
2918                 do_addrbook_view(addrbook, num_ab);     /** Render the address book */
2919         }
2920
2921         /** Note: wDumpContent() will output one additional </div> tag. */
2922         wprintf("</div>\n");            /** end of 'content' div */
2923         wDumpContent(1);
2924
2925         /** free the summary */
2926         if (WCC->summ != NULL) {
2927                 free(WCC->summ);
2928                 WCC->num_summ = 0;
2929                 WCC->summ = NULL;
2930         }
2931         if (addrbook != NULL) free(addrbook);
2932 }
2933
2934
2935 /*
2936  * Back end for post_message()
2937  * ... this is where the actual message gets transmitted to the server.
2938  */
2939 void post_mime_to_server(void) {
2940         char top_boundary[SIZ];
2941         char alt_boundary[SIZ];
2942         int is_multipart = 0;
2943         static int seq = 0;
2944         struct wc_attachment *att;
2945         char *encoded;
2946         size_t encoded_length;
2947         size_t encoded_strlen;
2948         char *txtmail = NULL;
2949
2950         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
2951                 serv_info.serv_fqdn,
2952                 getpid(),
2953                 ++seq
2954         );
2955         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
2956                 serv_info.serv_fqdn,
2957                 getpid(),
2958                 ++seq
2959         );
2960
2961         /* RFC2045 requires this, and some clients look for it... */
2962         serv_puts("MIME-Version: 1.0");
2963         serv_puts("X-Mailer: " PACKAGE_STRING);
2964
2965         /* If there are attachments, we have to do multipart/mixed */
2966         if (WC->first_attachment != NULL) {
2967                 is_multipart = 1;
2968         }
2969
2970         if (is_multipart) {
2971                 /* Remember, serv_printf() appends an extra newline */
2972                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
2973                 serv_printf("This is a multipart message in MIME format.\n");
2974                 serv_printf("--%s", top_boundary);
2975         }
2976
2977         /* Remember, serv_printf() appends an extra newline */
2978         serv_printf("Content-type: multipart/alternative; "
2979                 "boundary=\"%s\"\n", alt_boundary);
2980         serv_printf("This is a multipart message in MIME format.\n");
2981         serv_printf("--%s", alt_boundary);
2982
2983         serv_puts("Content-type: text/plain; charset=utf-8");
2984         serv_puts("Content-Transfer-Encoding: quoted-printable");
2985         serv_puts("");
2986         txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
2987         text_to_server_qp(txtmail);     /* Transmit message in quoted-printable encoding */
2988         free(txtmail);
2989
2990         serv_printf("--%s", alt_boundary);
2991
2992         serv_puts("Content-type: text/html; charset=utf-8");
2993         serv_puts("Content-Transfer-Encoding: quoted-printable");
2994         serv_puts("");
2995         serv_puts("<html><body>\r\n");
2996         text_to_server_qp(bstr("msgtext"));     /* Transmit message in quoted-printable encoding */
2997         serv_puts("</body></html>\r\n");
2998
2999         serv_printf("--%s--", alt_boundary);
3000         
3001         if (is_multipart) {
3002
3003                 /* Add in the attachments */
3004                 for (att = WC->first_attachment; att!=NULL; att=att->next) {
3005
3006                         encoded_length = ((att->length * 150) / 100);
3007                         encoded = malloc(encoded_length);
3008                         if (encoded == NULL) break;
3009                         encoded_strlen = CtdlEncodeBase64(encoded, att->data, att->length, 1);
3010
3011                         serv_printf("--%s", top_boundary);
3012                         serv_printf("Content-type: %s", att->content_type);
3013                         serv_printf("Content-disposition: attachment; filename=\"%s\"", att->filename);
3014                         serv_puts("Content-transfer-encoding: base64");
3015                         serv_puts("");
3016                         serv_write(encoded, encoded_strlen);
3017                         serv_puts("");
3018                         serv_puts("");
3019                         free(encoded);
3020                 }
3021                 serv_printf("--%s--", top_boundary);
3022         }
3023
3024         serv_puts("000");
3025 }
3026
3027
3028 /*
3029  * Post message (or don't post message)
3030  *
3031  * Note regarding the "dont_post" variable:
3032  * A random value (actually, it's just a timestamp) is inserted as a hidden
3033  * field called "postseq" when the display_enter page is generated.  This
3034  * value is checked when posting, using the static variable dont_post.  If a
3035  * user attempts to post twice using the same dont_post value, the message is
3036  * discarded.  This prevents the accidental double-saving of the same message
3037  * if the user happens to click the browser "back" button.
3038  */
3039 void post_message(void)
3040 {
3041         urlcontent *u;
3042         void *U;
3043         char buf[1024];
3044         char *encoded_subject = NULL;
3045         static long dont_post = (-1L);
3046         struct wc_attachment *att, *aptr;
3047         int is_anonymous = 0;
3048         const char *display_name;
3049         long dpLen = 0;
3050         struct wcsession *WCC = WC;
3051         char *ptr = NULL;
3052
3053         if (havebstr("force_room")) {
3054                 gotoroom(bstr("force_room"));
3055         }
3056
3057         if (GetHash(WCC->urlstrings, HKEY("display_name"), &U)) {
3058                 u = (urlcontent*) U;
3059                 display_name = u->url_data;
3060                 dpLen = u->url_data_size;
3061         }
3062         else {
3063                 display_name="";
3064         }
3065         if (!strcmp(display_name, "__ANONYMOUS__")) {
3066                 display_name = "";
3067                 is_anonymous = 1;
3068         }
3069
3070         if (WCC->upload_length > 0) {
3071
3072                 lprintf(9, "%s:%d: we are uploading %d bytes\n", __FILE__, __LINE__, WCC->upload_length);
3073                 /** There's an attachment.  Save it to this struct... */
3074                 att = malloc(sizeof(struct wc_attachment));
3075                 memset(att, 0, sizeof(struct wc_attachment));
3076                 att->length = WCC->upload_length;
3077                 strcpy(att->content_type, WCC->upload_content_type);
3078                 strcpy(att->filename, WCC->upload_filename);
3079                 att->next = NULL;
3080
3081                 /** And add it to the list. */
3082                 if (WCC->first_attachment == NULL) {
3083                         WCC->first_attachment = att;
3084                 }
3085                 else {
3086                         aptr = WCC->first_attachment;
3087                         while (aptr->next != NULL) aptr = aptr->next;
3088                         aptr->next = att;
3089                 }
3090
3091                 /**
3092                  * Mozilla sends a simple filename, which is what we want,
3093                  * but Satan's Browser sends an entire pathname.  Reduce
3094                  * the path to just a filename if we need to.
3095                  */
3096                 while (num_tokens(att->filename, '/') > 1) {
3097                         remove_token(att->filename, 0, '/');
3098                 }
3099                 while (num_tokens(att->filename, '\\') > 1) {
3100                         remove_token(att->filename, 0, '\\');
3101                 }
3102
3103                 /**
3104                  * Transfer control of this memory from the upload struct
3105                  * to the attachment struct.
3106                  */
3107                 att->data = WCC->upload;
3108                 WCC->upload_length = 0;
3109                 WCC->upload = NULL;
3110                 display_enter();
3111                 return;
3112         }
3113
3114         if (havebstr("cancel_button")) {
3115                 sprintf(WCC->ImportantMessage, 
3116                         _("Cancelled.  Message was not posted."));
3117         } else if (havebstr("attach_button")) {
3118                 display_enter();
3119                 return;
3120         } else if (lbstr("postseq") == dont_post) {
3121                 sprintf(WCC->ImportantMessage, 
3122                         _("Automatically cancelled because you have already "
3123                         "saved this message."));
3124         } else {
3125                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
3126                 const char *Recp = ""; 
3127                 const char *Cc = "";
3128                 const char *Bcc = "";
3129                 const char *Wikipage = "";
3130                 const char *my_email_addr = "";
3131                 char *CmdBuf = NULL;;
3132                 long len = 0;
3133                 size_t nLen;
3134                 char references[SIZ] = "";
3135                 size_t references_len = 0;
3136
3137                 safestrncpy(references, bstr("references"), sizeof references);
3138                 lprintf(9, "Converting: %s\n", references);
3139                 for (ptr=references; *ptr != 0; ++ptr) {
3140                         if (*ptr == '|') *ptr = '!';
3141                         ++references_len;
3142                 } 
3143                 lprintf(9, "Converted: %s\n", references);
3144
3145                 if (havebstr("subject")) {
3146                         char *Subj;
3147                         size_t SLen;
3148                         /*
3149                          * make enough room for the encoded string; 
3150                          * plus the QP header 
3151                          */
3152                         Subj = xbstr("subject", &SLen);
3153                         len = SLen * 3 + 32;
3154                         encoded_subject = malloc (len);
3155                         len = webcit_rfc2047encode(encoded_subject, len, Subj, SLen);
3156                         if (len < 0) {
3157                                 free (encoded_subject);
3158                                 return;
3159                         }
3160                 }
3161                 len += sizeof (CMD) + dpLen;
3162                 Recp = xbstr("recp", &nLen);
3163                 len += nLen;
3164                 Cc = xbstr("cc", &nLen);
3165                 len += nLen;
3166                 Bcc = xbstr("bcc", &nLen);
3167                 len += nLen;
3168                 Wikipage = xbstr("wikipage", &nLen);
3169                 len += nLen;
3170                 my_email_addr = xbstr("my_email_addr", &nLen);
3171                 len += nLen;
3172                 len += references_len;
3173
3174                 CmdBuf = (char*) malloc (len + 11);
3175
3176                 snprintf(CmdBuf, len + 1, CMD,
3177                         Recp,
3178                         is_anonymous,
3179                         (encoded_subject ? encoded_subject : ""),
3180                         display_name,
3181                         Cc,
3182                         Bcc,
3183                         Wikipage,
3184                         my_email_addr,
3185                         references);
3186                 lprintf(9, "%s\n", CmdBuf);
3187                 serv_puts(CmdBuf);
3188                 serv_getln(buf, sizeof buf);
3189                 free (CmdBuf);
3190                 if (encoded_subject) free(encoded_subject);
3191                 if (buf[0] == '4') {
3192                         post_mime_to_server();
3193                         if (  (havebstr("recp"))
3194                            || (havebstr("cc"  ))
3195                            || (havebstr("bcc" ))
3196                         ) {
3197                                 sprintf(WCC->ImportantMessage, _("Message has been sent.\n"));
3198                         }
3199                         else {
3200                                 sprintf(WC->ImportantMessage, _("Message has been posted.\n"));
3201                         }
3202                         dont_post = lbstr("postseq");
3203                 } else {
3204                         lprintf(9, "%s:%d: server post error: %s\n", __FILE__, __LINE__, buf);
3205                         sprintf(WC->ImportantMessage, "%s", &buf[4]);
3206                         display_enter();
3207                         return;
3208                 }
3209         }
3210
3211         free_attachments(WCC);
3212
3213         /**
3214          *  We may have been supplied with instructions regarding the location
3215          *  to which we must return after posting.  If found, go there.
3216          */
3217         if (havebstr("return_to")) {
3218                 http_redirect(bstr("return_to"));
3219         }
3220         /**
3221          *  If we were editing a page in a wiki room, go to that page now.
3222          */
3223         else if (havebstr("wikipage")) {
3224                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("wikipage"));
3225                 http_redirect(buf);
3226         }
3227         /**
3228          *  Otherwise, just go to the "read messages" loop.
3229          */
3230         else {
3231                 readloop("readnew");
3232         }
3233 }
3234
3235
3236
3237
3238 /**
3239  * \brief display the message entry screen
3240  */
3241 void display_enter(void)
3242 {
3243         char buf[SIZ];
3244         char ebuf[SIZ];
3245         long now;
3246         char *display_name;
3247         struct wc_attachment *att;
3248         int recipient_required = 0;
3249         int subject_required = 0;
3250         int recipient_bad = 0;
3251         int i;
3252         int is_anonymous = 0;
3253         long existing_page = (-1L);
3254         size_t dplen;
3255
3256         now = time(NULL);
3257
3258         if (havebstr("force_room")) {
3259                 gotoroom(bstr("force_room"));
3260         }
3261
3262         display_name = xbstr("display_name", &dplen);
3263         if (!strcmp(display_name, "__ANONYMOUS__")) {
3264                 display_name = "";
3265                 dplen = 0;
3266                 is_anonymous = 1;
3267         }
3268
3269         /** First test to see whether this is a room that requires recipients to be entered */
3270         serv_puts("ENT0 0");
3271         serv_getln(buf, sizeof buf);
3272
3273         if (!strncmp(buf, "570", 3)) {          /** 570 means that we need a recipient here */
3274                 recipient_required = 1;
3275         }
3276         else if (buf[0] != '2') {               /** Any other error means that we cannot continue */
3277                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
3278                 readloop("readnew");
3279                 return;
3280         }
3281
3282         /* Is the server strongly recommending that the user enter a message subject? */
3283         if ((buf[3] != '\0') && (buf[4] != '\0')) {
3284                 subject_required = extract_int(&buf[4], 1);
3285         }
3286
3287         /**
3288          * Are we perhaps in an address book view?  If so, then an "enter
3289          * message" command really means "add new entry."
3290          */
3291         if (WC->wc_default_view == VIEW_ADDRESSBOOK) {
3292                 do_edit_vcard(-1, "", "", WC->wc_roomname);
3293                 return;
3294         }
3295
3296         /*
3297          * Are we perhaps in a calendar room?  If so, then an "enter
3298          * message" command really means "add new calendar item."
3299          */
3300         if (WC->wc_default_view == VIEW_CALENDAR) {
3301                 display_edit_event();
3302                 return;
3303         }
3304
3305         /*
3306          * Are we perhaps in a tasks view?  If so, then an "enter
3307          * message" command really means "add new task."
3308          */
3309         if (WC->wc_default_view == VIEW_TASKS) {
3310                 display_edit_task();
3311                 return;
3312         }
3313
3314         /*
3315          * Otherwise proceed normally.
3316          * Do a custom room banner with no navbar...
3317          */
3318         output_headers(1, 1, 2, 0, 0, 0);
3319         wprintf("<div id=\"banner\">\n");
3320         embed_room_banner(NULL, navbar_none);
3321         wprintf("</div>\n");
3322         wprintf("<div id=\"content\">\n"
3323                 "<div class=\"fix_scrollbar_bug message \">");
3324
3325         /* Now check our actual recipients if there are any */
3326         if (recipient_required) {
3327                 const char *Recp = ""; 
3328                 const char *Cc = "";
3329                 const char *Bcc = "";
3330                 const char *Wikipage = "";
3331                 char *CmdBuf = NULL;;
3332                 size_t len = 0;
3333                 size_t nLen;
3334                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
3335                 
3336                 len = sizeof(CMD) + dplen;
3337                 Recp = xbstr("recp", &nLen);
3338                 len += nLen;
3339                 Cc = xbstr("cc", &nLen);
3340                 len += nLen;
3341                 Bcc = xbstr("bcc", &nLen);
3342                 len += nLen;
3343                 Wikipage = xbstr("wikipage", &nLen);
3344                 len += nLen;
3345                 
3346
3347                 CmdBuf = (char*) malloc (len + 1);
3348
3349                 snprintf(CmdBuf, len, CMD,
3350                          Recp, is_anonymous,
3351                          display_name,
3352                          Cc, Bcc, Wikipage);
3353                 serv_puts(CmdBuf);
3354                 serv_getln(buf, sizeof buf);
3355
3356                 if (!strncmp(buf, "570", 3)) {  /** 570 means we have an invalid recipient listed */
3357                         if (havebstr("recp") && 
3358                             havebstr("cc"  ) && 
3359                             havebstr("bcc" )) {
3360                                 recipient_bad = 1;
3361                         }
3362                 }
3363                 else if (buf[0] != '2') {       /** Any other error means that we cannot continue */
3364                         wprintf("<em>%s</em><br />\n", &buf[4]);
3365                         goto DONE;
3366                 }
3367         }
3368
3369         /** If we got this far, we can display the message entry screen. */
3370
3371         /* begin message entry screen */
3372         wprintf("<form "
3373                 "enctype=\"multipart/form-data\" "
3374                 "method=\"POST\" "
3375                 "accept-charset=\"UTF-8\" "
3376                 "action=\"post\" "
3377                 "name=\"enterform\""
3378                 ">\n");
3379         wprintf("<input type=\"hidden\" name=\"postseq\" value=\"%ld\">\n", now);
3380         if (WC->wc_view == VIEW_WIKI) {
3381                 wprintf("<input type=\"hidden\" name=\"wikipage\" value=\"%s\">\n", bstr("wikipage"));
3382         }
3383         wprintf("<input type=\"hidden\" name=\"return_to\" value=\"%s\">\n", bstr("return_to"));
3384         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%ld\">\n", WC->nonce);
3385         wprintf("<input type=\"hidden\" name=\"force_room\" value=\"");
3386         escputs(WC->wc_roomname);
3387         wprintf("\">\n");
3388         wprintf("<input type=\"hidden\" name=\"references\" value=\"");
3389         escputs(bstr("references"));
3390         wprintf("\">\n");
3391
3392         /** submit or cancel buttons */
3393         wprintf("<p class=\"send_edit_msg\">");
3394         wprintf("<input type=\"submit\" name=\"send_button\" value=\"");
3395         if (recipient_required) {
3396                 wprintf(_("Send message"));
3397         } else {
3398                 wprintf(_("Post message"));
3399         }
3400         wprintf("\">&nbsp;"
3401                 "<input type=\"submit\" name=\"cancel_button\" value=\"%s\">\n", _("Cancel"));
3402         wprintf("</p>");
3403
3404         /** header bar */
3405
3406         wprintf("<img src=\"static/newmess3_24x.gif\" class=\"imgedit\">");
3407         wprintf("  ");  /** header bar */
3408         webcit_fmt_date(buf, now, 0);
3409         wprintf("%s", buf);
3410         wprintf("\n");  /** header bar */
3411
3412         wprintf("<table width=\"100%%\" class=\"edit_msg_table\">");
3413         wprintf("<tr>");
3414         wprintf("<th><label for=\"from_id\" > ");
3415         wprintf(_(" <I>from</I> "));
3416         wprintf("</label></th>");
3417
3418         wprintf("<td colspan=\"2\">");
3419
3420         /* Allow the user to select any of his valid screen names */
3421
3422         wprintf("<select name=\"display_name\" size=1 id=\"from_id\">\n");
3423
3424         serv_puts("GVSN");
3425         serv_getln(buf, sizeof buf);
3426         if (buf[0] == '1') {
3427                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
3428                         wprintf("<option %s value=\"",
3429                                 ((!strcasecmp(bstr("display_name"), buf)) ? "selected" : "")
3430                         );
3431                         escputs(buf);
3432                         wprintf("\">");
3433                         escputs(buf);
3434                         wprintf("</option>\n");
3435                 }
3436         }
3437
3438         if (WC->room_flags & QR_ANONOPT) {
3439                 wprintf("<option %s value=\"__ANONYMOUS__\">%s</option>\n",
3440                         ((!strcasecmp(bstr("__ANONYMOUS__"), WC->wc_fullname)) ? "selected" : ""),
3441                         _("Anonymous")
3442                 );
3443         }
3444
3445         wprintf("</select>\n");
3446
3447         /* If this is an email (not a post), allow the user to select any of his
3448          * valid email addresses.
3449          */
3450         if (recipient_required) {
3451                 serv_puts("GVEA");
3452                 serv_getln(buf, sizeof buf);
3453                 if (buf[0] == '1') {
3454                         wprintf("<select name=\"my_email_addr\" size=1>\n");
3455                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
3456                                 wprintf("<option value=\"");
3457                                 escputs(buf);
3458                                 wprintf("\">&lt;");
3459                                 escputs(buf);
3460                                 wprintf("&gt;</option>\n");
3461                         }
3462                         wprintf("</select>\n");
3463                 }
3464         }
3465
3466         wprintf(_(" <I>in</I> "));
3467         escputs(WC->wc_roomname);
3468
3469         wprintf("</td></tr>");
3470
3471         if (recipient_required) {
3472                 char *ccraw;
3473                 char *copy;
3474                 size_t len;
3475                 wprintf("<tr><th><label for=\"recp_id\"> ");
3476                 wprintf(_("To:"));
3477                 wprintf("</label></th>"
3478                         "<td><input autocomplete=\"off\" type=\"text\" name=\"recp\" id=\"recp_id\" value=\"");
3479                 ccraw = xbstr("recp", &len);
3480                 copy = (char*) malloc(len * 2 + 1);
3481                 memcpy(copy, ccraw, len + 1); 
3482                 utf8ify_rfc822_string(copy);
3483                 escputs(copy);
3484                 free(copy);
3485                 wprintf("\" size=45 maxlength=1000 />");
3486                 wprintf("<div class=\"auto_complete\" id=\"recp_name_choices\"></div>");
3487                 wprintf("</td><td rowspan=\"3\" align=\"left\" valign=\"top\">");
3488
3489                 /** Pop open an address book -- begin **/
3490                 wprintf(
3491                         "<a href=\"javascript:PopOpenAddressBook('recp_id|%s|cc_id|%s|bcc_id|%s');\" "
3492                         "title=\"%s\">"
3493                         "<img align=middle border=0 width=24 height=24 src=\"static/viewcontacts_24x.gif\">"
3494                         "&nbsp;%s</a>",
3495                         _("To:"), _("CC:"), _("BCC:"),
3496                         _("Contacts"), _("Contacts")
3497                 );
3498                 /** Pop open an address book -- end **/
3499
3500                 wprintf("</td></tr>");
3501
3502                 wprintf("<tr><th><label for=\"cc_id\"> ");
3503                 wprintf(_("CC:"));
3504                 wprintf("</label></th>"
3505                         "<td><input autocomplete=\"off\" type=\"text\" name=\"cc\" id=\"cc_id\" value=\"");
3506                 ccraw = xbstr("cc", &len);
3507                 copy = (char*) malloc(len * 2 + 1);
3508                 memcpy(copy, ccraw, len + 1); 
3509                 utf8ify_rfc822_string(copy);
3510                 escputs(copy);
3511                 free(copy);
3512                 wprintf("\" size=45 maxlength=1000 />");
3513                 wprintf("<div class=\"auto_complete\" id=\"cc_name_choices\"></div>");
3514                 wprintf("</td></tr>");
3515
3516                 wprintf("<tr><th><label for=\"bcc_id\"> ");
3517                 wprintf(_("BCC:"));
3518                 wprintf("</label></th>"
3519                         "<td><input autocomplete=\"off\" type=\"text\" name=\"bcc\" id=\"bcc_id\" value=\"");
3520                 ccraw = xbstr("bcc", &len);
3521                 copy = (char*) malloc(len * 2 + 1);
3522                 memcpy(copy, ccraw, len + 1); 
3523                 utf8ify_rfc822_string(copy);
3524                 escputs(copy);
3525                 free(copy);
3526                 wprintf("\" size=45 maxlength=1000 />");
3527                 wprintf("<div class=\"auto_complete\" id=\"bcc_name_choices\"></div>");
3528                 wprintf("</td></tr>");
3529
3530                 /** Initialize the autocomplete ajax helpers (found in wclib.js) */
3531                 wprintf("<script type=\"text/javascript\">      \n"
3532                         " activate_entmsg_autocompleters();     \n"
3533                         "</script>                              \n"
3534                 );
3535
3536         }
3537
3538         wprintf("<tr><th><label for=\"subject_id\" > ");
3539         if (recipient_required || subject_required) {
3540                 wprintf(_("Subject:"));
3541         }
3542         else {
3543                 wprintf(_("Subject (optional):"));
3544         }
3545         wprintf("</label></th>"
3546                 "<td colspan=\"2\">"
3547                 "<input type=\"text\" name=\"subject\" id=\"subject_id\" value=\"");
3548         escputs(bstr("subject"));
3549         wprintf("\" size=45 maxlength=70>\n");
3550         wprintf("</td></tr>");
3551
3552         wprintf("<tr><td colspan=\"3\">\n");
3553
3554         wprintf("<textarea name=\"msgtext\" cols=\"80\" rows=\"15\">");
3555
3556         /** If we're continuing from a previous edit, put our partially-composed message back... */
3557         msgescputs(bstr("msgtext"));
3558
3559         /* If we're forwarding a message, insert it here... */
3560         if (lbstr("fwdquote") > 0L) {
3561                 wprintf("<br><div align=center><i>");
3562                 wprintf(_("--- forwarded message ---"));
3563                 wprintf("</i></div><br>");
3564                 pullquote_message(lbstr("fwdquote"), 1, 1);
3565         }
3566
3567         /** If we're replying quoted, insert the quote here... */
3568         else if (lbstr("replyquote") > 0L) {
3569                 wprintf("<br>"
3570                         "<blockquote>");
3571                 pullquote_message(lbstr("replyquote"), 0, 1);
3572                 wprintf("</blockquote><br>");
3573         }
3574
3575         /** If we're editing a wiki page, insert the existing page here... */
3576         else if (WC->wc_view == VIEW_WIKI) {
3577                 safestrncpy(buf, bstr("wikipage"), sizeof buf);
3578                 str_wiki_index(buf);
3579                 existing_page = locate_message_by_uid(buf);
3580                 if (existing_page >= 0L) {
3581                         pullquote_message(existing_page, 1, 0);
3582                 }
3583         }
3584
3585         /** Insert our signature if appropriate... */
3586         if ( (WC->is_mailbox) && yesbstr("sig_inserted") ) {
3587                 get_preference("use_sig", buf, sizeof buf);
3588                 if (!strcasecmp(buf, "yes")) {
3589                         int len;
3590                         get_preference("signature", ebuf, sizeof ebuf);
3591                         euid_unescapize(buf, ebuf);
3592                         wprintf("<br>--<br>");
3593                         len = strlen(buf);
3594                         for (i=0; i<len; ++i) {
3595                                 if (buf[i] == '\n') {
3596                                         wprintf("<br>");
3597                                 }
3598                                 else if (buf[i] == '<') {
3599                                         wprintf("&lt;");
3600                                 }
3601                                 else if (buf[i] == '>') {
3602                                         wprintf("&gt;");
3603                                 }
3604                                 else if (buf[i] == '&') {
3605                                         wprintf("&amp;");
3606                                 }
3607                                 else if (buf[i] == '\"') {
3608                                         wprintf("&quot;");
3609                                 }
3610                                 else if (buf[i] == '\'') {
3611                                         wprintf("&#39;");
3612                                 }
3613                                 else if (isprint(buf[i])) {
3614                                         wprintf("%c", buf[i]);
3615                                 }
3616                         }
3617                 }
3618         }
3619
3620         wprintf("</textarea>\n");
3621
3622         /** Make sure we only insert our signature once */
3623         /** We don't care if it was there or not before, it needs to be there now. */
3624         wprintf("<input type=\"hidden\" name=\"sig_inserted\" value=\"yes\">\n");
3625         
3626         /**
3627          * The following template embeds the TinyMCE richedit control, and automatically
3628          * transforms the textarea into a richedit textarea.
3629          */
3630         do_template("richedit");
3631
3632         /** Enumerate any attachments which are already in place... */
3633         wprintf("<div class=\"attachment buttons\"><img src=\"static/diskette_24x.gif\" class=\"imgedit\" > ");
3634         wprintf(_("Attachments:"));
3635         wprintf(" ");
3636         wprintf("<select name=\"which_attachment\" size=1>");
3637         for (att = WC->first_attachment; att != NULL; att = att->next) {
3638                 wprintf("<option value=\"");
3639                 urlescputs(att->filename);
3640                 wprintf("\">");
3641                 escputs(att->filename);
3642                 /* wprintf(" (%s, %d bytes)",att->content_type,att->length); */
3643                 wprintf("</option>\n");
3644         }
3645         wprintf("</select>");
3646
3647         /** Now offer the ability to attach additional files... */
3648         wprintf("&nbsp;&nbsp;&nbsp;");
3649         wprintf(_("Attach file:"));
3650         wprintf(" <input name=\"attachfile\" class=\"attachfile\" "
3651                 "size=16 type=\"file\">\n&nbsp;&nbsp;"
3652                 "<input type=\"submit\" name=\"attach_button\" value=\"%s\">\n", _("Add"));
3653         wprintf("</div>");      /* End of "attachment buttons" div */
3654
3655
3656         wprintf("</td></tr></table>");
3657         
3658         wprintf("</form>\n");
3659         wprintf("</div>\n");    /* end of "fix_scrollbar_bug" div */
3660
3661         /* NOTE: address_book_popup() will close the "content" div.  Don't close it here. */
3662 DONE:   address_book_popup();
3663         wDumpContent(1);
3664 }
3665
3666
3667 /**
3668  * \brief delete a message
3669  */
3670 void delete_msg(void)
3671 {
3672         long msgid;
3673         char buf[SIZ];
3674
3675         msgid = lbstr("msgid");
3676
3677         if (WC->wc_is_trash) {  /** Delete from Trash is a real delete */
3678                 serv_printf("DELE %ld", msgid); 
3679         }
3680         else {                  /** Otherwise move it to Trash */
3681                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
3682         }
3683
3684         serv_getln(buf, sizeof buf);
3685         sprintf(WC->ImportantMessage, "%s", &buf[4]);
3686
3687         readloop("readnew");
3688 }
3689
3690
3691 /**
3692  * \brief move a message to another folder
3693  */
3694 void move_msg(void)
3695 {
3696         long msgid;
3697         char buf[SIZ];
3698
3699         msgid = lbstr("msgid");
3700
3701         if (havebstr("move_button")) {
3702                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
3703                 serv_puts(buf);
3704                 serv_getln(buf, sizeof buf);
3705                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
3706         } else {
3707                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
3708         }
3709
3710         readloop("readnew");
3711 }
3712
3713
3714
3715
3716
3717 /**
3718  * \brief Confirm move of a message
3719  */
3720 void confirm_move_msg(void)
3721 {
3722         long msgid;
3723         char buf[SIZ];
3724         char targ[SIZ];
3725
3726         msgid = lbstr("msgid");
3727
3728
3729         output_headers(1, 1, 2, 0, 0, 0);
3730         wprintf("<div id=\"banner\">\n");
3731         wprintf("<h1>");
3732         wprintf(_("Confirm move of message"));
3733         wprintf("</h1>");
3734         wprintf("</div>\n");
3735
3736         wprintf("<div id=\"content\" class=\"service\">\n");
3737
3738         wprintf("<CENTER>");
3739
3740         wprintf(_("Move this message to:"));
3741         wprintf("<br />\n");
3742
3743         wprintf("<form METHOD=\"POST\" action=\"move_msg\">\n");
3744         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%ld\">\n", WC->nonce);
3745         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
3746
3747         wprintf("<SELECT NAME=\"target_room\" SIZE=5>\n");
3748         serv_puts("LKRA");
3749         serv_getln(buf, sizeof buf);
3750         if (buf[0] == '1') {
3751                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
3752                         extract_token(targ, buf, 0, '|', sizeof targ);
3753                         wprintf("<OPTION>");
3754                         escputs(targ);
3755                         wprintf("\n");
3756                 }
3757         }
3758         wprintf("</SELECT>\n");
3759         wprintf("<br />\n");
3760
3761         wprintf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
3762         wprintf("&nbsp;");
3763         wprintf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
3764         wprintf("</form></CENTER>\n");
3765
3766         wprintf("</CENTER>\n");
3767         wDumpContent(1);
3768 }
3769
3770
3771 /*@}*/