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