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