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