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