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