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