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