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