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