edbc64ba05064128c1be8e7854034e5953b4d448
[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         char *ptr = NULL;
1160         int num_attachments = 0;
1161         struct wc_attachment *att, *aptr;
1162         char m_subject[256];
1163         char from[256];
1164         char node[256];
1165         char rfca[256];
1166         char reply_to[512];
1167         char now[256];
1168         int format_type = 0;
1169         int nhdr = 0;
1170         int bq = 0;
1171         int i = 0;
1172 #ifdef HAVE_ICONV
1173         iconv_t ic = (iconv_t)(-1) ;
1174         char *ibuf;                /**< Buffer of characters to be converted */
1175         char *obuf;                /**< Buffer for converted characters      */
1176         size_t ibuflen;    /**< Length of input buffer         */
1177         size_t obuflen;    /**< Length of output buffer       */
1178         char *osav;                /**< Saved pointer to output buffer       */
1179 #endif
1180
1181         strcpy(from, "");
1182         strcpy(node, "");
1183         strcpy(rfca, "");
1184         strcpy(reply_to, "");
1185         strcpy(mime_http, "");
1186         strcpy(mime_content_type, "text/plain");
1187         strcpy(mime_charset, "us-ascii");
1188
1189         serv_printf("MSG4 %ld", msgnum);
1190         serv_getln(buf, sizeof buf);
1191         if (buf[0] != '1') {
1192                 wprintf(_("ERROR:"));
1193                 wprintf("%s<br />", &buf[4]);
1194                 return;
1195         }
1196
1197         strcpy(m_subject, "");
1198
1199         while (serv_getln(buf, sizeof buf), strcasecmp(buf, "text")) {
1200                 if (!strcmp(buf, "000")) {
1201                         wprintf(_("unexpected end of message"));
1202                         return;
1203                 }
1204                 if (include_headers) {
1205                         if (!strncasecmp(buf, "nhdr=yes", 8))
1206                                 nhdr = 1;
1207                         if (nhdr == 1)
1208                                 buf[0] = '_';
1209                         if (!strncasecmp(buf, "type=", 5))
1210                                 format_type = atoi(&buf[5]);
1211                         if (!strncasecmp(buf, "from=", 5)) {
1212                                 strcpy(from, &buf[5]);
1213                                 wprintf(_("from "));
1214 #ifdef HAVE_ICONV
1215                                 utf8ify_rfc822_string(from);
1216 #endif
1217                                 msgescputs(from);
1218                         }
1219                         if (!strncasecmp(buf, "subj=", 5)) {
1220                                 strcpy(m_subject, &buf[5]);
1221                         }
1222                         if ((!strncasecmp(buf, "hnod=", 5))
1223                             && (strcasecmp(&buf[5], serv_info.serv_humannode))) {
1224                                 wprintf("(%s) ", &buf[5]);
1225                         }
1226                         if ((!strncasecmp(buf, "room=", 5))
1227                             && (strcasecmp(&buf[5], WC->wc_roomname))
1228                             && (strlen(&buf[5])>0) ) {
1229                                 wprintf(_("in "));
1230                                 wprintf("%s&gt; ", &buf[5]);
1231                         }
1232                         if (!strncasecmp(buf, "rfca=", 5)) {
1233                                 strcpy(rfca, &buf[5]);
1234                                 wprintf("&lt;");
1235                                 msgescputs(rfca);
1236                                 wprintf("&gt; ");
1237                         }
1238         
1239                         if (!strncasecmp(buf, "node=", 5)) {
1240                                 strcpy(node, &buf[5]);
1241                                 if ( ((WC->room_flags & QR_NETWORK)
1242                                 || ((strcasecmp(&buf[5], serv_info.serv_nodename)
1243                                 && (strcasecmp(&buf[5], serv_info.serv_fqdn)))))
1244                                 && (strlen(rfca)==0)
1245                                 ) {
1246                                         wprintf("@%s ", &buf[5]);
1247                                 }
1248                         }
1249                         if (!strncasecmp(buf, "rcpt=", 5)) {
1250                                 wprintf(_("to "));
1251                                 wprintf("%s ", &buf[5]);
1252                         }
1253                         if (!strncasecmp(buf, "time=", 5)) {
1254                                 fmt_date(now, atol(&buf[5]), 0);
1255                                 wprintf("%s ", now);
1256                         }
1257                 }
1258
1259                 /**
1260                  * Save attachment info for later.  We can't start downloading them
1261                  * yet because we're in the middle of a server transaction.
1262                  */
1263                 if (!strncasecmp(buf, "part=", 5)) {
1264                         ptr = realloc(attachments, ((num_attachments+1) * 1024));
1265                         if (ptr != NULL) {
1266                                 ++num_attachments;
1267                                 attachments = ptr;
1268                                 strcat(attachments, &buf[5]);
1269                                 strcat(attachments, "\n");
1270                         }
1271                 }
1272
1273         }
1274
1275         if (include_headers) {
1276                 wprintf("<br>");
1277
1278 #ifdef HAVE_ICONV
1279                 utf8ify_rfc822_string(m_subject);
1280 #endif
1281                 if (strlen(m_subject) > 0) {
1282                         wprintf(_("Subject:"));
1283                         wprintf(" ");
1284                         msgescputs(m_subject);
1285                         wprintf("<br />");
1286                 }
1287
1288                 /**
1289                  * Begin body
1290                  */
1291                 wprintf("<br />");
1292         }
1293
1294         /**
1295          * Learn the content type
1296          */
1297         strcpy(mime_content_type, "text/plain");
1298         while (serv_getln(buf, sizeof buf), (strlen(buf) > 0)) {
1299                 if (!strcmp(buf, "000")) {
1300                         wprintf(_("unexpected end of message"));
1301                         goto ENDBODY;
1302                 }
1303                 if (!strncasecmp(buf, "Content-type: ", 14)) {
1304                         safestrncpy(mime_content_type, &buf[14],
1305                                 sizeof(mime_content_type));
1306                         for (i=0; i<strlen(mime_content_type); ++i) {
1307                                 if (!strncasecmp(&mime_content_type[i], "charset=", 8)) {
1308                                         safestrncpy(mime_charset, &mime_content_type[i+8],
1309                                                 sizeof mime_charset);
1310                                 }
1311                         }
1312                         for (i=0; i<strlen(mime_content_type); ++i) {
1313                                 if (mime_content_type[i] == ';') {
1314                                         mime_content_type[i] = 0;
1315                                 }
1316                         }
1317                 }
1318         }
1319
1320         /** Set up a character set conversion if we need to (and if we can) */
1321 #ifdef HAVE_ICONV
1322         if ( (strcasecmp(mime_charset, "us-ascii"))
1323            && (strcasecmp(mime_charset, "UTF-8"))
1324            && (strcasecmp(mime_charset, ""))
1325         ) {
1326                 ic = ctdl_iconv_open("UTF-8", mime_charset);
1327                 if (ic == (iconv_t)(-1) ) {
1328                         lprintf(5, "%s:%d iconv_open() failed: %s\n",
1329                                 __FILE__, __LINE__, strerror(errno));
1330                 }
1331         }
1332 #endif
1333
1334         /** Messages in legacy Citadel variformat get handled thusly... */
1335         if (!strcasecmp(mime_content_type, "text/x-citadel-variformat")) {
1336                 pullquote_fmout();
1337         }
1338
1339         /* Boring old 80-column fixed format text gets handled this way... */
1340         else if (!strcasecmp(mime_content_type, "text/plain")) {
1341                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1342                         if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = 0;
1343                         if (buf[strlen(buf)-1] == '\r') buf[strlen(buf)-1] = 0;
1344
1345 #ifdef HAVE_ICONV
1346                         if (ic != (iconv_t)(-1) ) {
1347                                 ibuf = buf;
1348                                 ibuflen = strlen(ibuf);
1349                                 obuflen = SIZ;
1350                                 obuf = (char *) malloc(obuflen);
1351                                 osav = obuf;
1352                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1353                                 osav[SIZ-obuflen] = 0;
1354                                 safestrncpy(buf, osav, sizeof buf);
1355                                 free(osav);
1356                         }
1357 #endif
1358
1359                         while ((strlen(buf) > 0) && (isspace(buf[strlen(buf) - 1])))
1360                                 buf[strlen(buf) - 1] = 0;
1361                         if ((bq == 0) &&
1362                         ((!strncmp(buf, ">", 1)) || (!strncmp(buf, " >", 2)) )) {
1363                                 wprintf("<blockquote>");
1364                                 bq = 1;
1365                         } else if ((bq == 1) &&
1366                                 (strncmp(buf, ">", 1)) && (strncmp(buf, " >", 2)) ) {
1367                                 wprintf("</blockquote>");
1368                                 bq = 0;
1369                         }
1370                         wprintf("<tt>");
1371                         url(buf);
1372                         msgescputs(buf);
1373                         wprintf("</tt><br />");
1374                 }
1375                 wprintf("</i><br />");
1376         }
1377
1378         /** HTML just gets escaped and stuffed back into the editor */
1379         else if (!strcasecmp(mime_content_type, "text/html")) {
1380                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1381                         strcat(buf, "\n");
1382                         msgescputs(buf);
1383                 }
1384         }
1385
1386         /** Unknown weirdness ... don't know how to handle this content type */
1387         else {
1388                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) { }
1389         }
1390
1391 ENDBODY:
1392         /** end of body handler */
1393
1394         /*
1395          * If there were attachments, we have to download them and insert them
1396          * into the attachment chain for the forwarded message we are composing.
1397          */
1398         if ( (forward_attachments) && (num_attachments) ) {
1399                 for (i=0; i<num_attachments; ++i) {
1400                         extract_token(buf, attachments, i, '\n', sizeof buf);
1401                         extract_token(mime_filename, buf, 1, '|', sizeof mime_filename);
1402                         extract_token(mime_partnum, buf, 2, '|', sizeof mime_partnum);
1403                         extract_token(mime_disposition, buf, 3, '|', sizeof mime_disposition);
1404                         extract_token(mime_content_type, buf, 4, '|', sizeof mime_content_type);
1405                         mime_length = extract_int(buf, 5);
1406
1407                         /*
1408                          * tracing  ... uncomment if necessary
1409                          *
1410                         lprintf(9, "fwd filename: %s\n", mime_filename);
1411                         lprintf(9, "fwd partnum : %s\n", mime_partnum);
1412                         lprintf(9, "fwd conttype: %s\n", mime_content_type);
1413                         lprintf(9, "fwd dispose : %s\n", mime_disposition);
1414                         lprintf(9, "fwd length  : %d\n", mime_length);
1415                          */
1416
1417                         if ( (!strcasecmp(mime_disposition, "inline"))
1418                            || (!strcasecmp(mime_disposition, "attachment")) ) {
1419                 
1420                                 /* Create an attachment struct from this mime part... */
1421                                 att = malloc(sizeof(struct wc_attachment));
1422                                 memset(att, 0, sizeof(struct wc_attachment));
1423                                 att->length = mime_length;
1424                                 strcpy(att->content_type, mime_content_type);
1425                                 strcpy(att->filename, mime_filename);
1426                                 att->next = NULL;
1427                                 att->data = load_mimepart(msgnum, mime_partnum);
1428                 
1429                                 /* And add it to the list. */
1430                                 if (WC->first_attachment == NULL) {
1431                                         WC->first_attachment = att;
1432                                 }
1433                                 else {
1434                                         aptr = WC->first_attachment;
1435                                         while (aptr->next != NULL) aptr = aptr->next;
1436                                         aptr->next = att;
1437                                 }
1438                         }
1439
1440                 }
1441                 if (attachments != NULL) {
1442                         free(attachments);
1443                 }
1444         }
1445
1446 #ifdef HAVE_ICONV
1447         if (ic != (iconv_t)(-1) ) {
1448                 iconv_close(ic);
1449         }
1450 #endif
1451 }
1452
1453 /**
1454  * \brief Display one row in the mailbox summary view
1455  *
1456  * \param num The row number to be displayed
1457  */
1458 void display_summarized(int num) {
1459         char datebuf[64];
1460
1461         wprintf("<tr id=\"m%ld\" style=\"width:100%%;font-weight:%s;background-color:#ffffff\" "
1462                 "onMouseDown=\"CtdlMoveMsgMouseDown(event,%ld)\">",
1463                 WC->summ[num].msgnum,
1464                 (WC->summ[num].is_new ? "bold" : "normal"),
1465                 WC->summ[num].msgnum
1466         );
1467
1468         wprintf("<td width=%d%%>", SUBJ_COL_WIDTH_PCT);
1469         escputs(WC->summ[num].subj);
1470         wprintf("</td>");
1471
1472         wprintf("<td width=%d%%>", SENDER_COL_WIDTH_PCT);
1473         escputs(WC->summ[num].from);
1474         wprintf("</td>");
1475
1476         wprintf("<td width=%d%%>", DATE_PLUS_BUTTONS_WIDTH_PCT);
1477         fmt_date(datebuf, WC->summ[num].date, 1);       /* brief */
1478         escputs(datebuf);
1479         wprintf("</td>");
1480
1481         wprintf("</tr>\n");
1482 }
1483
1484
1485
1486 /**
1487  * \brief display the adressbook overview
1488  * \param msgnum the citadel message number
1489  * \param alpha what????
1490  */
1491 void display_addressbook(long msgnum, char alpha) {
1492         char buf[SIZ];
1493         char mime_partnum[SIZ];
1494         char mime_filename[SIZ];
1495         char mime_content_type[SIZ];
1496         char mime_disposition[SIZ];
1497         int mime_length;
1498         char vcard_partnum[SIZ];
1499         char *vcard_source = NULL;
1500         struct message_summary summ;
1501
1502         memset(&summ, 0, sizeof(summ));
1503         safestrncpy(summ.subj, _("(no subject)"), sizeof summ.subj);
1504
1505         sprintf(buf, "MSG0 %ld|1", msgnum);     /* ask for headers only */
1506         serv_puts(buf);
1507         serv_getln(buf, sizeof buf);
1508         if (buf[0] != '1') return;
1509
1510         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1511                 if (!strncasecmp(buf, "part=", 5)) {
1512                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
1513                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
1514                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
1515                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
1516                         mime_length = extract_int(&buf[5], 5);
1517
1518                         if (!strcasecmp(mime_content_type, "text/x-vcard")) {
1519                                 strcpy(vcard_partnum, mime_partnum);
1520                         }
1521
1522                 }
1523         }
1524
1525         if (strlen(vcard_partnum) > 0) {
1526                 vcard_source = load_mimepart(msgnum, vcard_partnum);
1527                 if (vcard_source != NULL) {
1528
1529                         /** Display the summary line */
1530                         display_vcard(vcard_source, alpha, 0, NULL);
1531
1532                         /** If it's my vCard I can edit it */
1533                         if (    (!strcasecmp(WC->wc_roomname, USERCONFIGROOM))
1534                                 || (!strcasecmp(&WC->wc_roomname[11], USERCONFIGROOM))
1535                                 || (WC->wc_view == VIEW_ADDRESSBOOK)
1536                         ) {
1537                                 wprintf("<a href=\"edit_vcard?"
1538                                         "msgnum=%ld?partnum=%s\">",
1539                                         msgnum, vcard_partnum);
1540                                 wprintf("[%s]</a>", _("edit"));
1541                         }
1542
1543                         free(vcard_source);
1544                 }
1545         }
1546
1547 }
1548
1549
1550
1551 /**
1552  * \brief  If it's an old "Firstname Lastname" style record, try to convert it.
1553  * \param namebuf name to analyze, reverse if nescessary
1554  */
1555 void lastfirst_firstlast(char *namebuf) {
1556         char firstname[SIZ];
1557         char lastname[SIZ];
1558         int i;
1559
1560         if (namebuf == NULL) return;
1561         if (strchr(namebuf, ';') != NULL) return;
1562
1563         i = num_tokens(namebuf, ' ');
1564         if (i < 2) return;
1565
1566         extract_token(lastname, namebuf, i-1, ' ', sizeof lastname);
1567         remove_token(namebuf, i-1, ' ');
1568         strcpy(firstname, namebuf);
1569         sprintf(namebuf, "%s; %s", lastname, firstname);
1570 }
1571
1572 /**
1573  * \brief fetch what??? name
1574  * \param msgnum the citadel message number
1575  * \param namebuf where to put the name in???
1576  */
1577 void fetch_ab_name(long msgnum, char *namebuf) {
1578         char buf[SIZ];
1579         char mime_partnum[SIZ];
1580         char mime_filename[SIZ];
1581         char mime_content_type[SIZ];
1582         char mime_disposition[SIZ];
1583         int mime_length;
1584         char vcard_partnum[SIZ];
1585         char *vcard_source = NULL;
1586         int i;
1587         struct message_summary summ;
1588
1589         if (namebuf == NULL) return;
1590         strcpy(namebuf, "");
1591
1592         memset(&summ, 0, sizeof(summ));
1593         safestrncpy(summ.subj, "(no subject)", sizeof summ.subj);
1594
1595         sprintf(buf, "MSG0 %ld|1", msgnum);     /** ask for headers only */
1596         serv_puts(buf);
1597         serv_getln(buf, sizeof buf);
1598         if (buf[0] != '1') return;
1599
1600         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1601                 if (!strncasecmp(buf, "part=", 5)) {
1602                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
1603                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
1604                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
1605                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
1606                         mime_length = extract_int(&buf[5], 5);
1607
1608                         if (!strcasecmp(mime_content_type, "text/x-vcard")) {
1609                                 strcpy(vcard_partnum, mime_partnum);
1610                         }
1611
1612                 }
1613         }
1614
1615         if (strlen(vcard_partnum) > 0) {
1616                 vcard_source = load_mimepart(msgnum, vcard_partnum);
1617                 if (vcard_source != NULL) {
1618
1619                         /* Grab the name off the card */
1620                         display_vcard(vcard_source, 0, 0, namebuf);
1621
1622                         free(vcard_source);
1623                 }
1624         }
1625
1626         lastfirst_firstlast(namebuf);
1627         striplt(namebuf);
1628         for (i=0; i<strlen(namebuf); ++i) {
1629                 if (namebuf[i] != ';') return;
1630         }
1631         strcpy(namebuf, _("(no name)"));
1632 }
1633
1634
1635
1636 /**
1637  * \brief Record compare function for sorting address book indices
1638  * \param ab1 adressbook one
1639  * \param ab2 adressbook two
1640  */
1641 int abcmp(const void *ab1, const void *ab2) {
1642         return(strcasecmp(
1643                 (((const struct addrbookent *)ab1)->ab_name),
1644                 (((const struct addrbookent *)ab2)->ab_name)
1645         ));
1646 }
1647
1648
1649 /**
1650  * \brief Helper function for do_addrbook_view()
1651  * Converts a name into a three-letter tab label
1652  * \param tabbuf the tabbuffer to add name to
1653  * \param name the name to add to the tabbuffer
1654  */
1655 void nametab(char *tabbuf, char *name) {
1656         stresc(tabbuf, name, 0, 0);
1657         tabbuf[0] = toupper(tabbuf[0]);
1658         tabbuf[1] = tolower(tabbuf[1]);
1659         tabbuf[2] = tolower(tabbuf[2]);
1660         tabbuf[3] = 0;
1661 }
1662
1663
1664 /**
1665  * \brief Render the address book using info we gathered during the scan
1666  * \param addrbook the addressbook to render
1667  * \param num_ab the number of the addressbook
1668  */
1669 void do_addrbook_view(struct addrbookent *addrbook, int num_ab) {
1670         int i = 0;
1671         int displayed = 0;
1672         int bg = 0;
1673         static int NAMESPERPAGE = 60;
1674         int num_pages = 0;
1675         int page = 0;
1676         int tabfirst = 0;
1677         char tabfirst_label[SIZ];
1678         int tablast = 0;
1679         char tablast_label[SIZ];
1680
1681         if (num_ab == 0) {
1682                 wprintf("<br /><br /><br /><div align=\"center\"><i>");
1683                 wprintf(_("This address book is empty."));
1684                 wprintf("</i></div>\n");
1685                 return;
1686         }
1687
1688         if (num_ab > 1) {
1689                 qsort(addrbook, num_ab, sizeof(struct addrbookent), abcmp);
1690         }
1691
1692         num_pages = num_ab / NAMESPERPAGE;
1693
1694         page = atoi(bstr("page"));
1695
1696         wprintf("Page: ");
1697         for (i=0; i<=num_pages; ++i) {
1698                 if (i != page) {
1699                         wprintf("<a href=\"readfwd?page=%d\">", i);
1700                 }
1701                 else {
1702                         wprintf("<B>");
1703                 }
1704                 tabfirst = i * NAMESPERPAGE;
1705                 tablast = tabfirst + NAMESPERPAGE - 1;
1706                 if (tablast > (num_ab - 1)) tablast = (num_ab - 1);
1707                 nametab(tabfirst_label, addrbook[tabfirst].ab_name);
1708                 nametab(tablast_label, addrbook[tablast].ab_name);
1709                 wprintf("[%s&nbsp;-&nbsp;%s]",
1710                         tabfirst_label, tablast_label
1711                 );
1712                 if (i != page) {
1713                         wprintf("</A>\n");
1714                 }
1715                 else {
1716                         wprintf("</B>\n");
1717                 }
1718         }
1719         wprintf("<br />\n");
1720
1721         wprintf("<table border=0 cellspacing=0 "
1722                 "cellpadding=3 width=100%%>\n"
1723         );
1724
1725         for (i=0; i<num_ab; ++i) {
1726
1727                 if ((i / NAMESPERPAGE) == page) {
1728
1729                         if ((displayed % 4) == 0) {
1730                                 if (displayed > 0) {
1731                                         wprintf("</tr>\n");
1732                                 }
1733                                 bg = 1 - bg;
1734                                 wprintf("<tr bgcolor=\"#%s\">",
1735                                         (bg ? "DDDDDD" : "FFFFFF")
1736                                 );
1737                         }
1738         
1739                         wprintf("<td>");
1740         
1741                         wprintf("<a href=\"readfwd?startmsg=%ld&is_singlecard=1",
1742                                 addrbook[i].ab_msgnum);
1743                         wprintf("?maxmsgs=1?summary=0?alpha=%s\">", bstr("alpha"));
1744                         vcard_n_prettyize(addrbook[i].ab_name);
1745                         escputs(addrbook[i].ab_name);
1746                         wprintf("</a></td>\n");
1747                         ++displayed;
1748                 }
1749         }
1750
1751         wprintf("</tr></table>\n");
1752 }
1753
1754
1755
1756 /**
1757  * \brief load message pointers from the server
1758  * \param servcmd the citadel command to send to the citserver
1759  * \param with_headers what headers???
1760  */
1761 int load_msg_ptrs(char *servcmd, int with_headers)
1762 {
1763         char buf[1024];
1764         time_t datestamp;
1765         char fullname[128];
1766         char nodename[128];
1767         char inetaddr[128];
1768         char subject[256];
1769         int nummsgs;
1770         int maxload = 0;
1771
1772         int num_summ_alloc = 0;
1773
1774         if (WC->summ != NULL) {
1775                 free(WC->summ);
1776                 WC->num_summ = 0;
1777                 WC->summ = NULL;
1778         }
1779         num_summ_alloc = 100;
1780         WC->num_summ = 0;
1781         WC->summ = malloc(num_summ_alloc * sizeof(struct message_summary));
1782
1783         nummsgs = 0;
1784         maxload = sizeof(WC->msgarr) / sizeof(long) ;
1785         serv_puts(servcmd);
1786         serv_getln(buf, sizeof buf);
1787         if (buf[0] != '1') {
1788                 wprintf("<EM>%s</EM><br />\n", &buf[4]);
1789                 return (nummsgs);
1790         }
1791         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1792                 if (nummsgs < maxload) {
1793                         WC->msgarr[nummsgs] = extract_long(buf, 0);
1794                         datestamp = extract_long(buf, 1);
1795                         extract_token(fullname, buf, 2, '|', sizeof fullname);
1796                         extract_token(nodename, buf, 3, '|', sizeof nodename);
1797                         extract_token(inetaddr, buf, 4, '|', sizeof inetaddr);
1798                         extract_token(subject, buf, 5, '|', sizeof subject);
1799                         ++nummsgs;
1800
1801                         if (with_headers) {
1802                                 if (nummsgs > num_summ_alloc) {
1803                                         num_summ_alloc *= 2;
1804                                         WC->summ = realloc(WC->summ,
1805                                                 num_summ_alloc * sizeof(struct message_summary));
1806                                 }
1807                                 ++WC->num_summ;
1808
1809                                 memset(&WC->summ[nummsgs-1], 0, sizeof(struct message_summary));
1810                                 WC->summ[nummsgs-1].msgnum = WC->msgarr[nummsgs-1];
1811                                 safestrncpy(WC->summ[nummsgs-1].subj,
1812                                         _("(no subject)"), sizeof WC->summ[nummsgs-1].subj);
1813                                 if (strlen(fullname) > 0) {
1814                                         safestrncpy(WC->summ[nummsgs-1].from,
1815                                                 fullname, sizeof WC->summ[nummsgs-1].from);
1816                                 }
1817                                 if (strlen(subject) > 0) {
1818                                 safestrncpy(WC->summ[nummsgs-1].subj, subject,
1819                                         sizeof WC->summ[nummsgs-1].subj);
1820                                 }
1821 #ifdef HAVE_ICONV
1822                                 /** Handle subjects with RFC2047 encoding */
1823                                 utf8ify_rfc822_string(WC->summ[nummsgs-1].subj);
1824 #endif
1825                                 if (strlen(WC->summ[nummsgs-1].subj) > 75) {
1826                                         strcpy(&WC->summ[nummsgs-1].subj[72], "...");
1827                                 }
1828
1829                                 if (strlen(nodename) > 0) {
1830                                         if ( ((WC->room_flags & QR_NETWORK)
1831                                            || ((strcasecmp(nodename, serv_info.serv_nodename)
1832                                            && (strcasecmp(nodename, serv_info.serv_fqdn)))))
1833                                         ) {
1834                                                 strcat(WC->summ[nummsgs-1].from, " @ ");
1835                                                 strcat(WC->summ[nummsgs-1].from, nodename);
1836                                         }
1837                                 }
1838
1839                                 WC->summ[nummsgs-1].date = datestamp;
1840         
1841 #ifdef HAVE_ICONV
1842                                 /** Handle senders with RFC2047 encoding */
1843                                 utf8ify_rfc822_string(WC->summ[nummsgs-1].from);
1844 #endif
1845                                 if (strlen(WC->summ[nummsgs-1].from) > 25) {
1846                                         strcpy(&WC->summ[nummsgs-1].from[22], "...");
1847                                 }
1848                         }
1849                 }
1850         }
1851         return (nummsgs);
1852 }
1853
1854 /**
1855  * \brief qsort() compatible function to compare two longs in descending order.
1856  *
1857  * \param s1 first number to compare 
1858  * \param s2 second number to compare
1859  */
1860 int longcmp_r(const void *s1, const void *s2) {
1861         long l1;
1862         long l2;
1863
1864         l1 = *(long *)s1;
1865         l2 = *(long *)s2;
1866
1867         if (l1 > l2) return(-1);
1868         if (l1 < l2) return(+1);
1869         return(0);
1870 }
1871
1872  
1873 /**
1874  * \brief qsort() compatible function to compare two message summary structs by ascending subject.
1875  *
1876  * \param s1 first item to compare 
1877  * \param s2 second item to compare
1878  */
1879 int summcmp_subj(const void *s1, const void *s2) {
1880         struct message_summary *summ1;
1881         struct message_summary *summ2;
1882         
1883         summ1 = (struct message_summary *)s1;
1884         summ2 = (struct message_summary *)s2;
1885         return strcasecmp(summ1->subj, summ2->subj);
1886 }
1887
1888 /**
1889  * \brief qsort() compatible function to compare two message summary structs by descending subject.
1890  *
1891  * \param s1 first item to compare 
1892  * \param s2 second item to compare
1893  */
1894 int summcmp_rsubj(const void *s1, const void *s2) {
1895         struct message_summary *summ1;
1896         struct message_summary *summ2;
1897         
1898         summ1 = (struct message_summary *)s1;
1899         summ2 = (struct message_summary *)s2;
1900         return strcasecmp(summ2->subj, summ1->subj);
1901 }
1902
1903 /**
1904  * \brief qsort() compatible function to compare two message summary structs by ascending sender.
1905  *
1906  * \param s1 first item to compare 
1907  * \param s2 second item to compare
1908  */
1909 int summcmp_sender(const void *s1, const void *s2) {
1910         struct message_summary *summ1;
1911         struct message_summary *summ2;
1912         
1913         summ1 = (struct message_summary *)s1;
1914         summ2 = (struct message_summary *)s2;
1915         return strcasecmp(summ1->from, summ2->from);
1916 }
1917
1918 /**
1919  * \brief qsort() compatible function to compare two message summary structs by descending sender.
1920  *
1921  * \param s1 first item to compare 
1922  * \param s2 second item to compare
1923  */
1924 int summcmp_rsender(const void *s1, const void *s2) {
1925         struct message_summary *summ1;
1926         struct message_summary *summ2;
1927         
1928         summ1 = (struct message_summary *)s1;
1929         summ2 = (struct message_summary *)s2;
1930         return strcasecmp(summ2->from, summ1->from);
1931 }
1932
1933 /**
1934  * \brief qsort() compatible function to compare two message summary structs by ascending date.
1935  *
1936  * \param s1 first item to compare 
1937  * \param s2 second item to compare
1938  */
1939 int summcmp_date(const void *s1, const void *s2) {
1940         struct message_summary *summ1;
1941         struct message_summary *summ2;
1942         
1943         summ1 = (struct message_summary *)s1;
1944         summ2 = (struct message_summary *)s2;
1945
1946         if (summ1->date < summ2->date) return -1;
1947         else if (summ1->date > summ2->date) return +1;
1948         else return 0;
1949 }
1950
1951 /**
1952  * \brief qsort() compatible function to compare two message summary structs by descending date.
1953  *
1954  * \param s1 first item to compare 
1955  * \param s2 second item to compare
1956  */
1957 int summcmp_rdate(const void *s1, const void *s2) {
1958         struct message_summary *summ1;
1959         struct message_summary *summ2;
1960         
1961         summ1 = (struct message_summary *)s1;
1962         summ2 = (struct message_summary *)s2;
1963
1964         if (summ1->date < summ2->date) return +1;
1965         else if (summ1->date > summ2->date) return -1;
1966         else return 0;
1967 }
1968
1969
1970
1971 /**
1972  * \brief command loop for reading messages
1973  *
1974  * \param oper Set to "readnew" or "readold" or "readfwd" or "headers"
1975  */
1976 void readloop(char *oper)
1977 {
1978         char cmd[SIZ];
1979         char buf[SIZ];
1980         char old_msgs[SIZ];
1981         int a, b;
1982         int nummsgs;
1983         long startmsg;
1984         int maxmsgs;
1985         long *displayed_msgs = NULL;
1986         int num_displayed = 0;
1987         int is_summary = 0;
1988         int is_addressbook = 0;
1989         int is_singlecard = 0;
1990         int is_calendar = 0;
1991         int is_tasks = 0;
1992         int is_notes = 0;
1993         int is_bbview = 0;
1994         int lo, hi;
1995         int lowest_displayed = (-1);
1996         int highest_displayed = 0;
1997         struct addrbookent *addrbook = NULL;
1998         int num_ab = 0;
1999         char *sortby = NULL;
2000         char sortpref_name[128];
2001         char sortpref_value[128];
2002         char *subjsort_button;
2003         char *sendsort_button;
2004         char *datesort_button;
2005         int bbs_reverse = 0;
2006
2007         if (WC->wc_view == VIEW_WIKI) {
2008                 sprintf(buf, "wiki?room=%s?page=home", WC->wc_roomname);
2009                 http_redirect(buf);
2010                 return;
2011         }
2012
2013         startmsg = atol(bstr("startmsg"));
2014         maxmsgs = atoi(bstr("maxmsgs"));
2015         is_summary = atoi(bstr("summary"));
2016         if (maxmsgs == 0) maxmsgs = DEFAULT_MAXMSGS;
2017
2018         snprintf(sortpref_name, sizeof sortpref_name, "sort %s", WC->wc_roomname);
2019         get_preference(sortpref_name, sortpref_value, sizeof sortpref_value);
2020
2021         sortby = bstr("sortby");
2022         if ( (strlen(sortby) > 0) && (strcasecmp(sortby, sortpref_value)) ) {
2023                 set_preference(sortpref_name, sortby, 1);
2024         }
2025         if (strlen(sortby) == 0) sortby = sortpref_value;
2026
2027         /** mailbox sort */
2028         if (strlen(sortby) == 0) sortby = "rdate";
2029
2030         /** message board sort */
2031         if (!strcasecmp(sortby, "reverse")) {
2032                 bbs_reverse = 1;
2033         }
2034         else {
2035                 bbs_reverse = 0;
2036         }
2037
2038         output_headers(1, 1, 1, 0, 0, 0);
2039
2040         /**
2041          * When in summary mode, always show ALL messages instead of just
2042          * new or old.  Otherwise, show what the user asked for.
2043          */
2044         if (!strcmp(oper, "readnew")) {
2045                 strcpy(cmd, "MSGS NEW");
2046         }
2047         else if (!strcmp(oper, "readold")) {
2048                 strcpy(cmd, "MSGS OLD");
2049         }
2050         else {
2051                 strcpy(cmd, "MSGS ALL");
2052         }
2053
2054         if ((WC->wc_view == VIEW_MAILBOX) && (maxmsgs > 1)) {
2055                 is_summary = 1;
2056                 strcpy(cmd, "MSGS ALL");
2057         }
2058
2059         if ((WC->wc_view == VIEW_ADDRESSBOOK) && (maxmsgs > 1)) {
2060                 is_addressbook = 1;
2061                 strcpy(cmd, "MSGS ALL");
2062                 maxmsgs = 9999999;
2063         }
2064
2065         if (is_summary) {
2066                 strcpy(cmd, "MSGS ALL|||1");    /**< fetch header summary */
2067                 startmsg = 1;
2068                 maxmsgs = 9999999;
2069         }
2070
2071         /**
2072          * Are we doing a summary view?  If so, we need to know old messages
2073          * and new messages, so we can do that pretty boldface thing for the
2074          * new messages.
2075          */
2076         strcpy(old_msgs, "");
2077         if (is_summary) {
2078                 serv_puts("GTSN");
2079                 serv_getln(buf, sizeof buf);
2080                 if (buf[0] == '2') {
2081                         strcpy(old_msgs, &buf[4]);
2082                 }
2083         }
2084
2085         is_singlecard = atoi(bstr("is_singlecard"));
2086
2087         if (WC->wc_default_view == VIEW_CALENDAR) {             /**< calendar */
2088                 is_calendar = 1;
2089                 strcpy(cmd, "MSGS ALL");
2090                 maxmsgs = 32767;
2091         }
2092         if (WC->wc_default_view == VIEW_TASKS) {                /**< tasks */
2093                 is_tasks = 1;
2094                 strcpy(cmd, "MSGS ALL");
2095                 maxmsgs = 32767;
2096         }
2097         if (WC->wc_default_view == VIEW_NOTES) {                /**< notes */
2098                 is_notes = 1;
2099                 strcpy(cmd, "MSGS ALL");
2100                 maxmsgs = 32767;
2101         }
2102
2103         nummsgs = load_msg_ptrs(cmd, is_summary);
2104         if (nummsgs == 0) {
2105
2106                 if ((!is_tasks) && (!is_calendar) && (!is_notes) && (!is_addressbook)) {
2107                         wprintf("<em>");
2108                         if (!strcmp(oper, "readnew")) {
2109                                 wprintf(_("No new messages."));
2110                         } else if (!strcmp(oper, "readold")) {
2111                                 wprintf(_("No old messages."));
2112                         } else {
2113                                 wprintf(_("No messages here."));
2114                         }
2115                         wprintf("</em>\n");
2116                 }
2117
2118                 goto DONE;
2119         }
2120
2121         if (is_summary) {
2122                 for (a = 0; a < nummsgs; ++a) {
2123                         /** Are you a new message, or an old message? */
2124                         if (is_summary) {
2125                                 if (is_msg_in_mset(old_msgs, WC->msgarr[a])) {
2126                                         WC->summ[a].is_new = 0;
2127                                 }
2128                                 else {
2129                                         WC->summ[a].is_new = 1;
2130                                 }
2131                         }
2132                 }
2133         }
2134
2135         if (startmsg == 0L) {
2136                 if (bbs_reverse) {
2137                         startmsg = WC->msgarr[(nummsgs >= maxmsgs) ? (nummsgs - maxmsgs) : 0];
2138                 }
2139                 else {
2140                         startmsg = WC->msgarr[0];
2141                 }
2142         }
2143
2144         if (is_summary) {
2145                 if (!strcasecmp(sortby, "subject")) {
2146                         qsort(WC->summ, WC->num_summ,
2147                                 sizeof(struct message_summary), summcmp_subj);
2148                 }
2149                 else if (!strcasecmp(sortby, "rsubject")) {
2150                         qsort(WC->summ, WC->num_summ,
2151                                 sizeof(struct message_summary), summcmp_rsubj);
2152                 }
2153                 else if (!strcasecmp(sortby, "sender")) {
2154                         qsort(WC->summ, WC->num_summ,
2155                                 sizeof(struct message_summary), summcmp_sender);
2156                 }
2157                 else if (!strcasecmp(sortby, "rsender")) {
2158                         qsort(WC->summ, WC->num_summ,
2159                                 sizeof(struct message_summary), summcmp_rsender);
2160                 }
2161                 else if (!strcasecmp(sortby, "date")) {
2162                         qsort(WC->summ, WC->num_summ,
2163                                 sizeof(struct message_summary), summcmp_date);
2164                 }
2165                 else if (!strcasecmp(sortby, "rdate")) {
2166                         qsort(WC->summ, WC->num_summ,
2167                                 sizeof(struct message_summary), summcmp_rdate);
2168                 }
2169         }
2170
2171         if (!strcasecmp(sortby, "subject")) {
2172                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=rsubject\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2173         }
2174         else if (!strcasecmp(sortby, "rsubject")) {
2175                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=subject\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2176         }
2177         else {
2178                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=subject\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2179         }
2180
2181         if (!strcasecmp(sortby, "sender")) {
2182                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=rsender\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2183         }
2184         else if (!strcasecmp(sortby, "rsender")) {
2185                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=sender\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2186         }
2187         else {
2188                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=sender\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2189         }
2190
2191         if (!strcasecmp(sortby, "date")) {
2192                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=rdate\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2193         }
2194         else if (!strcasecmp(sortby, "rdate")) {
2195                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=date\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2196         }
2197         else {
2198                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=rdate\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2199         }
2200
2201         if (is_summary) {
2202                 wprintf("</div>\n");            /** end of 'content' div */
2203
2204                 wprintf("<script language=\"javascript\" type=\"text/javascript\">"
2205                         " document.onkeydown = CtdlMsgListKeyPress;     "
2206                         " if (document.layers) {                        "
2207                         "       document.captureEvents(Event.KEYPRESS); "
2208                         " }                                             "
2209                         "</script>\n"
2210                 );
2211
2212                 /** note that Date and Delete are now in the same column */
2213                 wprintf("<div id=\"message_list_hdr\">"
2214                         "<div class=\"fix_scrollbar_bug\">"
2215                         "<table cellspacing=0 style=\"width:100%%\">"
2216                         "<tr>"
2217                 );
2218                 wprintf("<td width=%d%%><b><i>%s</i></b> %s</td>"
2219                         "<td width=%d%%><b><i>%s</i></b> %s</td>"
2220                         "<td width=%d%%><b><i>%s</i></b> %s"
2221                         "&nbsp;"
2222                         "<input type=\"submit\" name=\"delete_button\" style=\"font-size:6pt\" "
2223                         " onClick=\"CtdlDeleteSelectedMessages(event)\" "
2224                         " value=\"%s\">"
2225                         "</td>"
2226                         "</tr>\n"
2227                         ,
2228                         SUBJ_COL_WIDTH_PCT,
2229                         _("Subject"),   subjsort_button,
2230                         SENDER_COL_WIDTH_PCT,
2231                         _("Sender"),    sendsort_button,
2232                         DATE_PLUS_BUTTONS_WIDTH_PCT,
2233                         _("Date"),      datesort_button,
2234                         _("Delete")
2235                 );
2236                 wprintf("</table></div></div>\n");
2237
2238                 wprintf("<div id=\"message_list\">"
2239
2240                         "<div class=\"fix_scrollbar_bug\">\n"
2241
2242                         "<table class=\"mailbox_summary\" id=\"summary_headers\" rules=rows "
2243                         "cellspacing=0 style=\"width:100%%;-moz-user-select:none;\">"
2244                 );
2245         }
2246
2247         if (is_notes) {
2248                 wprintf("<div align=center>%s</div>\n", _("Click on any note to edit it."));
2249                 wprintf("<div id=\"new_notes_here\"></div>\n");
2250         }
2251
2252         for (a = 0; a < nummsgs; ++a) {
2253                 if ((WC->msgarr[a] >= startmsg) && (num_displayed < maxmsgs)) {
2254
2255                         /** Display the message */
2256                         if (is_summary) {
2257                                 display_summarized(a);
2258                         }
2259                         else if (is_addressbook) {
2260                                 fetch_ab_name(WC->msgarr[a], buf);
2261                                 ++num_ab;
2262                                 addrbook = realloc(addrbook,
2263                                         (sizeof(struct addrbookent) * num_ab) );
2264                                 safestrncpy(addrbook[num_ab-1].ab_name, buf,
2265                                         sizeof(addrbook[num_ab-1].ab_name));
2266                                 addrbook[num_ab-1].ab_msgnum = WC->msgarr[a];
2267                         }
2268                         else if (is_calendar) {
2269                                 display_calendar(WC->msgarr[a]);
2270                         }
2271                         else if (is_tasks) {
2272                                 display_task(WC->msgarr[a]);
2273                         }
2274                         else if (is_notes) {
2275                                 display_note(WC->msgarr[a]);
2276                         }
2277                         else {
2278                                 if (displayed_msgs == NULL) {
2279                                         displayed_msgs = malloc(sizeof(long) *
2280                                                                 (maxmsgs<nummsgs ? maxmsgs : nummsgs));
2281                                 }
2282                                 displayed_msgs[num_displayed] = WC->msgarr[a];
2283                         }
2284
2285                         if (lowest_displayed < 0) lowest_displayed = a;
2286                         highest_displayed = a;
2287
2288                         ++num_displayed;
2289                 }
2290         }
2291
2292         /**
2293          * Set the "is_bbview" variable if it appears that we are looking at
2294          * a classic bulletin board view.
2295          */
2296         if ((!is_tasks) && (!is_calendar) && (!is_addressbook)
2297               && (!is_notes) && (!is_singlecard) && (!is_summary)) {
2298                 is_bbview = 1;
2299         }
2300
2301         /** Output loop */
2302         if (displayed_msgs != NULL) {
2303                 if (bbs_reverse) {
2304                         qsort(displayed_msgs, num_displayed, sizeof(long), longcmp_r);
2305                 }
2306
2307                 /** if we do a split bbview in the future, begin messages div here */
2308
2309                 for (a=0; a<num_displayed; ++a) {
2310                         read_message(displayed_msgs[a], 0, "");
2311                 }
2312
2313                 /** if we do a split bbview in the future, end messages div here */
2314
2315                 free(displayed_msgs);
2316                 displayed_msgs = NULL;
2317         }
2318
2319         if (is_summary) {
2320                 wprintf("</table>"
2321                         "</div>\n");                    /**< end of 'fix_scrollbar_bug' div */
2322                 wprintf("</div>");                      /**< end of 'message_list' div */
2323
2324                 /** Here's the grab-it-to-resize-the-message-list widget */
2325                 wprintf("<div id=\"resize_msglist\" "
2326                         "onMouseDown=\"CtdlResizeMsgListMouseDown(event)\">"
2327                         "<div class=\"fix_scrollbar_bug\">"
2328                         "<table width=100%% border=3 cellspacing=0 "
2329                         "bgcolor=\"#cccccc\" "
2330                         "cellpadding=0><TR><TD> </td></tr></table>"
2331                         "</div></div>\n"
2332                 );
2333
2334                 wprintf("<div id=\"preview_pane\">");   /**< The preview pane will initially be empty */
2335         }
2336
2337         /**
2338          * Bump these because although we're thinking in zero base, the user
2339          * is a drooling idiot and is thinking in one base.
2340          */
2341         ++lowest_displayed;
2342         ++highest_displayed;
2343
2344         /**
2345          * If we're not currently looking at ALL requested
2346          * messages, then display the selector bar
2347          */
2348         if (is_bbview) {
2349                 /** begin bbview scroller */
2350                 wprintf("<form name=\"msgomatic\">");
2351                 wprintf(_("Reading #"), lowest_displayed, highest_displayed);
2352
2353                 wprintf("<select name=\"whichones\" size=\"1\" "
2354                         "OnChange=\"location.href=msgomatic.whichones.options"
2355                         "[selectedIndex].value\">\n");
2356
2357                 if (bbs_reverse) {
2358                         for (b=nummsgs-1; b>=0; b = b - maxmsgs) {
2359                                 hi = b + 1;
2360                                 lo = b - maxmsgs + 2;
2361                                 if (lo < 1) lo = 1;
2362                                 wprintf("<option %s value="
2363                                         "\"%s"
2364                                         "?startmsg=%ld"
2365                                         "?maxmsgs=%d"
2366                                         "?summary=%d\">"
2367                                         "%d-%d</option> \n",
2368                                         ((WC->msgarr[lo-1] == startmsg) ? "selected" : ""),
2369                                         oper,
2370                                         WC->msgarr[lo-1],
2371                                         maxmsgs,
2372                                         is_summary,
2373                                         hi, lo);
2374                         }
2375                 }
2376                 else {
2377                         for (b=0; b<nummsgs; b = b + maxmsgs) {
2378                                 lo = b + 1;
2379                                 hi = b + maxmsgs + 1;
2380                                 if (hi > nummsgs) hi = nummsgs;
2381                                 wprintf("<option %s value="
2382                                         "\"%s"
2383                                         "?startmsg=%ld"
2384                                         "?maxmsgs=%d"
2385                                         "?summary=%d\">"
2386                                         "%d-%d</option> \n",
2387                                         ((WC->msgarr[b] == startmsg) ? "selected" : ""),
2388                                         oper,
2389                                         WC->msgarr[lo-1],
2390                                         maxmsgs,
2391                                         is_summary,
2392                                         lo, hi);
2393                         }
2394                 }
2395
2396                 wprintf("<option value=\"%s?startmsg=%ld"
2397                         "?maxmsgs=9999999?summary=%d\">"
2398                         "ALL"
2399                         "</option> ",
2400                         oper,
2401                         WC->msgarr[0], is_summary);
2402
2403                 wprintf("</select> ");
2404                 wprintf(_("of %d messages."), nummsgs);
2405
2406                 /** forward/reverse */
2407                 wprintf("&nbsp;<select name=\"direction\" size=\"1\" "
2408                         "OnChange=\"location.href=msgomatic.direction.options"
2409                         "[selectedIndex].value\">\n"
2410                 );
2411
2412                 wprintf("<option %s value=\"%s?sortby=forward\">oldest to newest</option>\n",
2413                         (bbs_reverse ? "" : "selected"),
2414                         oper
2415                 );
2416         
2417                 wprintf("<option %s value=\"%s?sortby=reverse\">newest to oldest</option>\n",
2418                         (bbs_reverse ? "selected" : ""),
2419                         oper
2420                 );
2421         
2422                 wprintf("</select></form>\n");
2423                 /** end bbview scroller */
2424         }
2425
2426 DONE:
2427         if (is_tasks) {
2428                 do_tasks_view();        /** Render the task list */
2429         }
2430
2431         if (is_calendar) {
2432                 do_calendar_view();     /** Render the calendar */
2433         }
2434
2435         if (is_addressbook) {
2436                 do_addrbook_view(addrbook, num_ab);     /** Render the address book */
2437         }
2438
2439         /** Note: wDumpContent() will output one additional </div> tag. */
2440         wDumpContent(1);
2441         if (addrbook != NULL) free(addrbook);
2442
2443         /** free the summary */
2444         if (WC->summ != NULL) {
2445                 free(WC->summ);
2446                 WC->num_summ = 0;
2447                 WC->summ = NULL;
2448         }
2449 }
2450
2451
2452 /**
2453  * \brief Back end for post_message()
2454  * ... this is where the actual message gets transmitted to the server.
2455  */
2456 void post_mime_to_server(void) {
2457         char boundary[SIZ];
2458         int is_multipart = 0;
2459         static int seq = 0;
2460         struct wc_attachment *att;
2461         char *encoded;
2462         size_t encoded_length;
2463
2464         /** RFC2045 requires this, and some clients look for it... */
2465         serv_puts("MIME-Version: 1.0");
2466
2467         /** If there are attachments, we have to do multipart/mixed */
2468         if (WC->first_attachment != NULL) {
2469                 is_multipart = 1;
2470         }
2471
2472         if (is_multipart) {
2473                 sprintf(boundary, "=_Citadel_Multipart_%s_%04x%04x",
2474                         serv_info.serv_fqdn,
2475                         getpid(),
2476                         ++seq
2477                 );
2478
2479                 /** Remember, serv_printf() appends an extra newline */
2480                 serv_printf("Content-type: multipart/mixed; "
2481                         "boundary=\"%s\"\n", boundary);
2482                 serv_printf("This is a multipart message in MIME format.\n");
2483                 serv_printf("--%s", boundary);
2484         }
2485
2486         serv_puts("Content-type: text/html; charset=utf-8");
2487         serv_puts("Content-Transfer-Encoding: quoted-printable");
2488         serv_puts("");
2489         serv_puts("<html><body>\r\n");
2490         text_to_server_qp(bstr("msgtext"));     /** Transmit message in quoted-printable encoding */
2491         serv_puts("</body></html>\r\n");
2492         
2493         if (is_multipart) {
2494
2495                 /** Add in the attachments */
2496                 for (att = WC->first_attachment; att!=NULL; att=att->next) {
2497
2498                         encoded_length = ((att->length * 150) / 100);
2499                         encoded = malloc(encoded_length);
2500                         if (encoded == NULL) break;
2501                         CtdlEncodeBase64(encoded, att->data, att->length);
2502
2503                         serv_printf("--%s", boundary);
2504                         serv_printf("Content-type: %s", att->content_type);
2505                         serv_printf("Content-disposition: attachment; "
2506                                 "filename=\"%s\"", att->filename);
2507                         serv_puts("Content-transfer-encoding: base64");
2508                         serv_puts("");
2509                         serv_write(encoded, strlen(encoded));
2510                         serv_puts("");
2511                         serv_puts("");
2512                         free(encoded);
2513                 }
2514                 serv_printf("--%s--", boundary);
2515         }
2516
2517         serv_puts("000");
2518 }
2519
2520
2521 /**
2522  * \brief Post message (or don't post message)
2523  *
2524  * Note regarding the "dont_post" variable:
2525  * A random value (actually, it's just a timestamp) is inserted as a hidden
2526  * field called "postseq" when the display_enter page is generated.  This
2527  * value is checked when posting, using the static variable dont_post.  If a
2528  * user attempts to post twice using the same dont_post value, the message is
2529  * discarded.  This prevents the accidental double-saving of the same message
2530  * if the user happens to click the browser "back" button.
2531  */
2532 void post_message(void)
2533 {
2534         char buf[SIZ];
2535         static long dont_post = (-1L);
2536         struct wc_attachment *att, *aptr;
2537         int is_anonymous = 0;
2538
2539         if (!strcasecmp(bstr("is_anonymous"), "yes")) {
2540                 is_anonymous = 1;
2541         }
2542
2543         if (WC->upload_length > 0) {
2544
2545                 /** There's an attachment.  Save it to this struct... */
2546                 att = malloc(sizeof(struct wc_attachment));
2547                 memset(att, 0, sizeof(struct wc_attachment));
2548                 att->length = WC->upload_length;
2549                 strcpy(att->content_type, WC->upload_content_type);
2550                 strcpy(att->filename, WC->upload_filename);
2551                 att->next = NULL;
2552
2553                 /** And add it to the list. */
2554                 if (WC->first_attachment == NULL) {
2555                         WC->first_attachment = att;
2556                 }
2557                 else {
2558                         aptr = WC->first_attachment;
2559                         while (aptr->next != NULL) aptr = aptr->next;
2560                         aptr->next = att;
2561                 }
2562
2563                 /**
2564                  * Mozilla sends a simple filename, which is what we want,
2565                  * but Satan's Browser sends an entire pathname.  Reduce
2566                  * the path to just a filename if we need to.
2567                  */
2568                 while (num_tokens(att->filename, '/') > 1) {
2569                         remove_token(att->filename, 0, '/');
2570                 }
2571                 while (num_tokens(att->filename, '\\') > 1) {
2572                         remove_token(att->filename, 0, '\\');
2573                 }
2574
2575                 /**
2576                  * Transfer control of this memory from the upload struct
2577                  * to the attachment struct.
2578                  */
2579                 att->data = WC->upload;
2580                 WC->upload_length = 0;
2581                 WC->upload = NULL;
2582                 display_enter();
2583                 return;
2584         }
2585
2586         if (strlen(bstr("cancel_button")) > 0) {
2587                 sprintf(WC->ImportantMessage, 
2588                         _("Cancelled.  Message was not posted."));
2589         } else if (strlen(bstr("attach_button")) > 0) {
2590                 display_enter();
2591                 return;
2592         } else if (atol(bstr("postseq")) == dont_post) {
2593                 sprintf(WC->ImportantMessage, 
2594                         _("Automatically cancelled because you have already "
2595                         "saved this message."));
2596         } else {
2597                 sprintf(buf, "ENT0 1|%s|%d|4|%s|||%s|%s|%s",
2598                         bstr("recp"),
2599                         is_anonymous,
2600                         bstr("subject"),
2601                         bstr("cc"),
2602                         bstr("bcc"),
2603                         bstr("wikipage")
2604                 );
2605                 serv_puts(buf);
2606                 serv_getln(buf, sizeof buf);
2607                 if (buf[0] == '4') {
2608                         post_mime_to_server();
2609                         if ( (strlen(bstr("recp")) > 0)
2610                            || (strlen(bstr("cc")) > 0)
2611                            || (strlen(bstr("bcc")) > 0)
2612                         ) {
2613                                 sprintf(WC->ImportantMessage, _("Message has been sent.\n"));
2614                         }
2615                         else {
2616                                 sprintf(WC->ImportantMessage, _("Message has been posted.\n"));
2617                         }
2618                         dont_post = atol(bstr("postseq"));
2619                 } else {
2620                         sprintf(WC->ImportantMessage, "%s", &buf[4]);
2621                         display_enter();
2622                         return;
2623                 }
2624         }
2625
2626         free_attachments(WC);
2627
2628         /**
2629          *  We may have been supplied with instructions regarding the location
2630          *  to which we must return after posting.  If found, go there.
2631          */
2632         if (strlen(bstr("return_to")) > 0) {
2633                 http_redirect(bstr("return_to"));
2634         }
2635         /**
2636          *  If we were editing a page in a wiki room, go to that page now.
2637          */
2638         else if (strlen(bstr("wikipage")) > 0) {
2639                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("wikipage"));
2640                 http_redirect(buf);
2641         }
2642         /**
2643          *  Otherwise, just go to the "read messages" loop.
2644          */
2645         else {
2646                 readloop("readnew");
2647         }
2648 }
2649
2650
2651
2652
2653 /**
2654  * \brief display the message entry screen
2655  */
2656 void display_enter(void)
2657 {
2658         char buf[SIZ];
2659         char ebuf[SIZ];
2660         long now;
2661         struct wc_attachment *att;
2662         int recipient_required = 0;
2663         int recipient_bad = 0;
2664         int i;
2665         int is_anonymous = 0;
2666         long existing_page = (-1L);
2667
2668         if (strlen(bstr("force_room")) > 0) {
2669                 gotoroom(bstr("force_room"));
2670         }
2671
2672         if (!strcasecmp(bstr("is_anonymous"), "yes")) {
2673                 is_anonymous = 1;
2674         }
2675
2676         /**
2677          * Are we perhaps in an address book view?  If so, then an "enter
2678          * message" command really means "add new entry."
2679          */
2680         if (WC->wc_default_view == VIEW_ADDRESSBOOK) {
2681                 do_edit_vcard(-1, "", "");
2682                 return;
2683         }
2684
2685 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
2686         /**
2687          * Are we perhaps in a calendar room?  If so, then an "enter
2688          * message" command really means "add new calendar item."
2689          */
2690         if (WC->wc_default_view == VIEW_CALENDAR) {
2691                 display_edit_event();
2692                 return;
2693         }
2694
2695         /**
2696          * Are we perhaps in a tasks view?  If so, then an "enter
2697          * message" command really means "add new task."
2698          */
2699         if (WC->wc_default_view == VIEW_TASKS) {
2700                 display_edit_task();
2701                 return;
2702         }
2703 #endif
2704
2705         /**
2706          * Otherwise proceed normally.
2707          * Do a custom room banner with no navbar...
2708          */
2709         output_headers(1, 1, 2, 0, 0, 0);
2710         wprintf("<div id=\"banner\">\n");
2711         embed_room_banner(NULL, navbar_none);
2712         wprintf("</div>\n");
2713         wprintf("<div id=\"content\">\n"
2714                 "<div class=\"fix_scrollbar_bug\">"
2715                 "<table width=100%% border=0 bgcolor=\"#ffffff\"><tr><td>");
2716
2717         /** First test to see whether this is a room that requires recipients to be entered */
2718         serv_puts("ENT0 0");
2719         serv_getln(buf, sizeof buf);
2720         if (!strncmp(buf, "570", 3)) {          /** 570 means that we need a recipient here */
2721                 recipient_required = 1;
2722         }
2723         else if (buf[0] != '2') {               /** Any other error means that we cannot continue */
2724                 wprintf("<EM>%s</EM><br />\n", &buf[4]);
2725                 goto DONE;
2726         }
2727
2728         /** Now check our actual recipients if there are any */
2729         if (recipient_required) {
2730                 sprintf(buf, "ENT0 0|%s|%d|0||||%s|%s|%s", bstr("recp"), is_anonymous,
2731                         bstr("cc"), bstr("bcc"), bstr("wikipage"));
2732                 serv_puts(buf);
2733                 serv_getln(buf, sizeof buf);
2734
2735                 if (!strncmp(buf, "570", 3)) {  /** 570 means we have an invalid recipient listed */
2736                         if (strlen(bstr("recp")) + strlen(bstr("cc")) + strlen(bstr("bcc")) > 0) {
2737                                 recipient_bad = 1;
2738                         }
2739                 }
2740                 else if (buf[0] != '2') {       /** Any other error means that we cannot continue */
2741                         wprintf("<EM>%s</EM><br />\n", &buf[4]);
2742                         goto DONE;
2743                 }
2744         }
2745
2746         /** If we got this far, we can display the message entry screen. */
2747
2748         now = time(NULL);
2749         fmt_date(buf, now, 0);
2750         strcat(&buf[strlen(buf)], _(" <I>from</I> "));
2751         stresc(&buf[strlen(buf)], WC->wc_fullname, 1, 1);
2752
2753         /* Don't need this anymore, it's in the input box below
2754         if (strlen(bstr("recp")) > 0) {
2755                 strcat(&buf[strlen(buf)], _(" <I>to</I> "));
2756                 stresc(&buf[strlen(buf)], bstr("recp"), 1, 1);
2757         }
2758         */
2759
2760         strcat(&buf[strlen(buf)], _(" <I>in</I> "));
2761         stresc(&buf[strlen(buf)], WC->wc_roomname, 1, 1);
2762
2763         /** begin message entry screen */
2764         wprintf("<form "
2765                 "enctype=\"multipart/form-data\" "
2766                 "method=\"POST\" "
2767                 "accept-charset=\"UTF-8\" "
2768                 "action=\"post\" "
2769                 "name=\"enterform\""
2770                 ">\n");
2771         wprintf("<input type=\"hidden\" name=\"postseq\" value=\"%ld\">\n", now);
2772         if (WC->wc_view == VIEW_WIKI) {
2773                 wprintf("<input type=\"hidden\" name=\"wikipage\" value=\"%s\">\n", bstr("wikipage"));
2774         }
2775         wprintf("<input type=\"hidden\" name=\"return_to\" value=\"%s\">\n", bstr("return_to"));
2776
2777         wprintf("<img src=\"static/newmess3_24x.gif\" align=middle alt=\" \">");
2778         wprintf("%s\n", buf);   /** header bar */
2779         if (WC->room_flags & QR_ANONOPT) {
2780                 wprintf("&nbsp;"
2781                         "<input type=\"checkbox\" name=\"is_anonymous\" value=\"yes\" %s>",
2782                                 (is_anonymous ? "checked" : "")
2783                 );
2784                 wprintf("Anonymous");
2785         }
2786         wprintf("<br>\n");      /** header bar */
2787
2788         wprintf("<table border=\"0\" width=\"100%%\">\n");
2789         if (recipient_required) {
2790
2791                 wprintf("<tr><td>");
2792                 wprintf("<font size=-1>");
2793                 wprintf(_("To:"));
2794                 wprintf("</font>");
2795                 wprintf("</td><td>"
2796                         "<input autocomplete=\"off\" type=\"text\" name=\"recp\" id=\"recp_id\" value=\"");
2797                 escputs(bstr("recp"));
2798                 wprintf("\" size=50 maxlength=1000 />");
2799                 wprintf("<div class=\"auto_complete\" id=\"recp_name_choices\"></div>");
2800                 wprintf("</td><td></td></tr>\n");
2801
2802                 wprintf("<tr><td>");
2803                 wprintf("<font size=-1>");
2804                 wprintf(_("CC:"));
2805                 wprintf("</font>");
2806                 wprintf("</td><td>"
2807                         "<input autocomplete=\"off\" type=\"text\" name=\"cc\" id=\"cc_id\" value=\"");
2808                 escputs(bstr("cc"));
2809                 wprintf("\" size=50 maxlength=1000 />");
2810                 wprintf("<div class=\"auto_complete\" id=\"cc_name_choices\"></div>");
2811                 wprintf("</td><td></td></tr>\n");
2812
2813                 wprintf("<tr><td>");
2814                 wprintf("<font size=-1>");
2815                 wprintf(_("BCC:"));
2816                 wprintf("</font>");
2817                 wprintf("</td><td>"
2818                         "<input autocomplete=\"off\" type=\"text\" name=\"bcc\" id=\"bcc_id\" value=\"");
2819                 escputs(bstr("bcc"));
2820                 wprintf("\" size=50 maxlength=1000 />");
2821                 wprintf("<div class=\"auto_complete\" id=\"bcc_name_choices\"></div>");
2822                 wprintf("</td><td></td></tr>\n");
2823
2824                 /** Initialize the autocomplete ajax helpers (found in wclib.js) */
2825                 wprintf("<script type=\"text/javascript\">      \n"
2826                         " activate_entmsg_autocompleters();     \n"
2827                         "</script>                              \n"
2828                 );
2829         }
2830
2831         wprintf("<tr><td>");
2832         wprintf("<font size=-1>");
2833         wprintf(_("Subject (optional):"));
2834         wprintf("</font>");
2835         wprintf("</td><td>"
2836                 "<input type=\"text\" name=\"subject\" value=\"");
2837         escputs(bstr("subject"));
2838         wprintf("\" size=50 maxlength=70></td><td>\n");
2839
2840         wprintf("<input type=\"submit\" name=\"send_button\" value=\"");
2841         if (recipient_required) {
2842                 wprintf(_("Send message"));
2843         } else {
2844                 wprintf(_("Post message"));
2845         }
2846         wprintf("\">&nbsp;"
2847                 "<input type=\"submit\" name=\"cancel_button\" value=\"%s\">\n", _("Cancel"));
2848         wprintf("</td></tr></table>\n");
2849
2850         wprintf("<center>");
2851
2852         wprintf("<textarea name=\"msgtext\" cols=\"80\" rows=\"15\">");
2853
2854         /** If we're continuing from a previous edit, put our partially-composed message back... */
2855         msgescputs(bstr("msgtext"));
2856
2857         /* If we're forwarding a message, insert it here... */
2858         if (atol(bstr("fwdquote")) > 0L) {
2859                 wprintf("<br><div align=center><i>");
2860                 wprintf(_("--- forwarded message ---"));
2861                 wprintf("</i></div><br>");
2862                 pullquote_message(atol(bstr("fwdquote")), 1, 1);
2863         }
2864
2865         /** If we're replying quoted, insert the quote here... */
2866         else if (atol(bstr("replyquote")) > 0L) {
2867                 wprintf("<br>"
2868                         "<blockquote>");
2869                 pullquote_message(atol(bstr("replyquote")), 0, 1);
2870                 wprintf("</blockquote>\n\n");
2871         }
2872
2873         /** If we're editing a wiki page, insert the existing page here... */
2874         else if (WC->wc_view == VIEW_WIKI) {
2875                 safestrncpy(buf, bstr("wikipage"), sizeof buf);
2876                 str_wiki_index(buf);
2877                 existing_page = locate_message_by_uid(buf);
2878                 if (existing_page >= 0L) {
2879                         pullquote_message(existing_page, 1, 0);
2880                 }
2881         }
2882
2883         /** Insert our signature if appropriate... */
2884         if ( (WC->is_mailbox) && (strcmp(bstr("sig_inserted"), "yes")) ) {
2885                 get_preference("use_sig", buf, sizeof buf);
2886                 if (!strcasecmp(buf, "yes")) {
2887                         get_preference("signature", ebuf, sizeof ebuf);
2888                         euid_unescapize(buf, ebuf);
2889                         wprintf("<br>--<br>");
2890                         for (i=0; i<strlen(buf); ++i) {
2891                                 if (buf[i] == '\n') {
2892                                         wprintf("<br>");
2893                                 }
2894                                 else if (buf[i] == '<') {
2895                                         wprintf("&lt;");
2896                                 }
2897                                 else if (buf[i] == '>') {
2898                                         wprintf("&gt;");
2899                                 }
2900                                 else if (buf[i] == '&') {
2901                                         wprintf("&amp;");
2902                                 }
2903                                 else if (buf[i] == '\"') {
2904                                         wprintf("&quot;");
2905                                 }
2906                                 else if (buf[i] == '\'') {
2907                                         wprintf("&#39;");
2908                                 }
2909                                 else if (isprint(buf[i])) {
2910                                         wprintf("%c", buf[i]);
2911                                 }
2912                         }
2913                 }
2914         }
2915
2916         wprintf("</textarea>");
2917         wprintf("</center><br />\n");
2918
2919         /**
2920          * The following script embeds the TinyMCE richedit control, and automatically
2921          * transforms the textarea into a richedit textarea.
2922          */
2923         wprintf(
2924                 "<script language=\"javascript\" type=\"text/javascript\" src=\"tiny_mce/tiny_mce.js\"></script>\n"
2925                 "<script language=\"javascript\" type=\"text/javascript\">"
2926                 "tinyMCE.init({"
2927                 "       mode : \"textareas\", width : \"100%%\", browsers : \"msie,gecko\", "
2928                 "       theme : \"advanced\", plugins : \"iespell\", "
2929                 "       theme_advanced_buttons1 : \"bold, italic, underline, strikethrough, justifyleft, justifycenter, justifyright, justifyfull, bullist, numlist, cut, copy, paste, link, image, help, forecolor, iespell, code\", "
2930                 "       theme_advanced_buttons2 : \"\", "
2931                 "       theme_advanced_buttons3 : \"\" "
2932                 "});"
2933                 "</script>\n"
2934         );
2935
2936
2937         /** Enumerate any attachments which are already in place... */
2938         wprintf("<img src=\"static/diskette_24x.gif\" border=0 "
2939                 "align=middle height=16 width=16> ");
2940         wprintf(_("Attachments:"));
2941         wprintf(" ");
2942         wprintf("<select name=\"which_attachment\" size=1>");
2943         for (att = WC->first_attachment; att != NULL; att = att->next) {
2944                 wprintf("<option value=\"");
2945                 urlescputs(att->filename);
2946                 wprintf("\">");
2947                 escputs(att->filename);
2948                 /* wprintf(" (%s, %d bytes)",att->content_type,att->length); */
2949                 wprintf("</option>\n");
2950         }
2951         wprintf("</select>");
2952
2953         /** Now offer the ability to attach additional files... */
2954         wprintf("&nbsp;&nbsp;&nbsp;");
2955         wprintf(_("Attach file:"));
2956         wprintf(" <input NAME=\"attachfile\" "
2957                 "SIZE=16 TYPE=\"file\">\n&nbsp;&nbsp;"
2958                 "<input type=\"submit\" name=\"attach_button\" value=\"%s\">\n", _("Add"));
2959
2960         /** Seth asked for these to be at the top *and* bottom... */
2961         wprintf("<input type=\"submit\" name=\"send_button\" value=\"");
2962         if (recipient_required) {
2963                 wprintf(_("Send message"));
2964         } else {
2965                 wprintf(_("Post message"));
2966         }
2967         wprintf("\">&nbsp;"
2968                 "<input type=\"submit\" name=\"cancel_button\" value=\"%s\">\n", _("Cancel"));
2969
2970         /** Make sure we only insert our signature once */
2971         if (strcmp(bstr("sig_inserted"), "yes")) {
2972                 wprintf("<INPUT TYPE=\"hidden\" NAME=\"sig_inserted\" VALUE=\"yes\">\n");
2973         }
2974
2975         wprintf("</form>\n");
2976
2977         wprintf("</td></tr></table></div>\n");
2978 DONE:   wDumpContent(1);
2979 }
2980
2981
2982
2983 /**
2984  * \brief delete a message
2985  */
2986 void delete_msg(void)
2987 {
2988         long msgid;
2989         char buf[SIZ];
2990
2991         msgid = atol(bstr("msgid"));
2992
2993         output_headers(1, 1, 1, 0, 0, 0);
2994
2995         if (WC->wc_is_trash) {  /** Delete from Trash is a real delete */
2996                 serv_printf("DELE %ld", msgid); 
2997         }
2998         else {                  /** Otherwise move it to Trash */
2999                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
3000         }
3001
3002         serv_getln(buf, sizeof buf);
3003         wprintf("<EM>%s</EM><br />\n", &buf[4]);
3004
3005         wDumpContent(1);
3006 }
3007
3008
3009
3010
3011 /**
3012  * \brief Confirm move of a message
3013  */
3014 void confirm_move_msg(void)
3015 {
3016         long msgid;
3017         char buf[SIZ];
3018         char targ[SIZ];
3019
3020         msgid = atol(bstr("msgid"));
3021
3022
3023         output_headers(1, 1, 2, 0, 0, 0);
3024         wprintf("<div id=\"banner\">\n");
3025         wprintf("<TABLE WIDTH=100%% BORDER=0><TR><TD>");
3026         wprintf("<SPAN CLASS=\"titlebar\">");
3027         wprintf(_("Confirm move of message"));
3028         wprintf("</SPAN>\n");
3029         wprintf("</TD></TR></TABLE>\n");
3030         wprintf("</div>\n<div id=\"content\">\n");
3031
3032         wprintf("<CENTER>");
3033
3034         wprintf(_("Move this message to:"));
3035         wprintf("<br />\n");
3036
3037         wprintf("<form METHOD=\"POST\" action=\"move_msg\">\n");
3038         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
3039
3040         wprintf("<SELECT NAME=\"target_room\" SIZE=5>\n");
3041         serv_puts("LKRA");
3042         serv_getln(buf, sizeof buf);
3043         if (buf[0] == '1') {
3044                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
3045                         extract_token(targ, buf, 0, '|', sizeof targ);
3046                         wprintf("<OPTION>");
3047                         escputs(targ);
3048                         wprintf("\n");
3049                 }
3050         }
3051         wprintf("</SELECT>\n");
3052         wprintf("<br />\n");
3053
3054         wprintf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
3055         wprintf("&nbsp;");
3056         wprintf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
3057         wprintf("</form></CENTER>\n");
3058
3059         wprintf("</CENTER>\n");
3060         wDumpContent(1);
3061 }
3062
3063
3064 /**
3065  * \brief move a message to another folder
3066  */
3067 void move_msg(void)
3068 {
3069         long msgid;
3070         char buf[SIZ];
3071
3072         msgid = atol(bstr("msgid"));
3073
3074         if (strlen(bstr("move_button")) > 0) {
3075                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
3076                 serv_puts(buf);
3077                 serv_getln(buf, sizeof buf);
3078                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
3079         } else {
3080                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
3081         }
3082
3083         readloop("readnew");
3084
3085 }
3086
3087
3088 /*@}*/