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