732ef03b8093686eecdac97baf7a9d3a21b60a9e
[citadel.git] / webcit / messages.c
1 /*
2  * Functions which deal with the fetching and displaying of messages.
3  *
4  * Copyright (c) 1996-2012 by the citadel.org team
5  *
6  * This program is open source software.  You can redistribute it and/or
7  * modify it under the terms of the GNU General Public License, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include "webcit.h"
16 #include "webserver.h"
17 #include "dav.h"
18 #include "calendar.h"
19
20 HashList *MimeRenderHandler = NULL;
21 HashList *ReadLoopHandler = NULL;
22 int dbg_analyze_msg = 0;
23
24 #define SUBJ_COL_WIDTH_PCT              50      /* Mailbox view column width */
25 #define SENDER_COL_WIDTH_PCT            30      /* Mailbox view column width */
26 #define DATE_PLUS_BUTTONS_WIDTH_PCT     20      /* Mailbox view column width */
27
28 void jsonMessageListHdr(void);
29
30 void display_enter(void);
31
32 void fixview()
33 {
34         /* workaround for json listview; its not useable directly */
35         if (WC->CurRoom.view == VIEW_JSON_LIST) {
36                 StrBuf *View = NewStrBuf();
37                 StrBufPrintf(View, "%d", VIEW_MAILBOX);
38                 putbstr("view", View);;
39         }
40 }
41 int load_message(message_summary *Msg, 
42                  StrBuf *FoundCharset,
43                  StrBuf **Error)
44 {
45         StrBuf *Buf;
46         StrBuf *HdrToken;
47         char buf[SIZ];
48         int Done = 0;
49         int state=0;
50         int rc;
51
52         Buf = NewStrBuf();
53         if (Msg->PartNum != NULL) {
54                 serv_printf("MSG4 %ld|%s", Msg->msgnum, ChrPtr(Msg->PartNum));
55         }
56         else {
57                 serv_printf("MSG4 %ld", Msg->msgnum);
58         }
59
60         StrBuf_ServGetln(Buf);
61         if (GetServerStatus(Buf, NULL) != 1) {
62                 *Error = NewStrBuf();
63                 StrBufAppendPrintf(*Error, "<strong>");
64                 StrBufAppendPrintf(*Error, _("ERROR:"));
65                 StrBufAppendPrintf(*Error, "</strong> %s<br>\n", &buf[4]);
66                 FreeStrBuf(&Buf);
67                 return 0;
68         }
69
70         /* begin everythingamundo table */
71         HdrToken = NewStrBuf();
72         while (!Done && StrBuf_ServGetln(Buf)>=0) {
73                 if ( (StrLength(Buf)==3) && 
74                     !strcmp(ChrPtr(Buf), "000")) 
75                 {
76                         Done = 1;
77                         if (state < 2) {
78                                 if (Msg->MsgBody->Data == NULL)
79                                         Msg->MsgBody->Data = NewStrBuf();
80                                 Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/html"));
81                                 StrBufAppendPrintf(Msg->MsgBody->Data, "<div><i>");
82                                 StrBufAppendPrintf(Msg->MsgBody->Data, _("Empty message"));
83                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</i><br><br>\n");
84                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</div>\n");
85                         }
86                         break;
87                 }
88                 switch (state) {
89                 case 0:/* Citadel Message Headers */
90                         if (StrLength(Buf) == 0) {
91                                 state ++;
92                                 break;
93                         }
94                         StrBufExtract_token(HdrToken, Buf, 0, '=');
95                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
96                         
97                         /* look up one of the examine_* functions to parse the content */
98                         rc =  EvaluateMsgHdr(SKEY(HdrToken), Msg, Buf, FoundCharset);
99                         if (rc == 1) {
100                                 state++;
101                         }
102                         /* TODO: 
103                         else LogError(Target, 
104                                       __FUNCTION__,  
105                                       "don't know how to handle message header[%s]\n", 
106                                       ChrPtr(HdrToken));
107                          */
108                         break;
109                 case 1:/* Message Mime Header */
110                         if (StrLength(Buf) == 0) {
111                                 state++;
112                                 if (Msg->MsgBody->ContentType == NULL)
113                                         /* end of header or no header? */
114                                         Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/plain"));
115                                  /* usual end of mime header */
116                         }
117                         else
118                         {
119                                 StrBufExtract_token(HdrToken, Buf, 0, ':');
120                                 if (StrLength(HdrToken) > 0) {
121                                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
122                                         /* the examine*'s know how to do with mime headers too... */
123                                         EvaluateMsgHdr(SKEY(HdrToken), Msg, Buf, FoundCharset);
124                                         
125                                         break;
126                                 }
127                         }
128                 case 2: /* Message Body */
129                         
130                         if (Msg->MsgBody->size_known > 0) {
131                                 StrBuf_ServGetBLOBBuffered(Msg->MsgBody->Data, Msg->MsgBody->length);
132                                 state ++;
133                                 /*/ todo: check next line, if not 000, append following lines */
134                         }
135                         else if (1){
136                                 if (StrLength(Msg->MsgBody->Data) > 0)
137                                         StrBufAppendBufPlain(Msg->MsgBody->Data, "\n", 1, 0);
138                                 StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
139                         }
140                         break;
141                 case 3:
142                         StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
143                         break;
144                 }
145         }
146
147         if (Msg->AllAttach == NULL)
148                 Msg->AllAttach = NewHash(1,NULL);
149         /* now we put the body mimepart we read above into the mimelist */
150         Put(Msg->AllAttach, SKEY(Msg->MsgBody->PartNum), Msg->MsgBody, DestroyMime);
151         
152         FreeStrBuf(&Buf);
153         FreeStrBuf(&HdrToken);
154         return 1;
155 }
156
157
158
159 /*
160  * I wanna SEE that message!
161  *
162  * msgnum               Message number to display
163  * printable_view       Nonzero to display a printable view
164  * section              Optional for encapsulated message/rfc822 submessage
165  */
166 int read_message(StrBuf *Target, const char *tmpl, long tmpllen, long msgnum, const StrBuf *PartNum, const StrBuf **OutMime, WCTemplputParams *TP) 
167 {
168         StrBuf *Buf;
169         StrBuf *FoundCharset;
170         HashPos  *it;
171         void *vMime;
172         message_summary *Msg = NULL;
173         void *vHdr;
174         long len;
175         const char *Key;
176         WCTemplputParams SuperTP;
177         WCTemplputParams SubTP;
178         StrBuf *Error = NULL;
179
180         memset(&SuperTP, 0, sizeof(WCTemplputParams));
181         memset(&SubTP, 0, sizeof(WCTemplputParams));
182
183         Buf = NewStrBuf();
184         FoundCharset = NewStrBuf();
185         Msg = (message_summary *)malloc(sizeof(message_summary));
186         memset(Msg, 0, sizeof(message_summary));
187         Msg->msgnum = msgnum;
188         Msg->PartNum = PartNum;
189         Msg->MsgBody =  (wc_mime_attachment*) malloc(sizeof(wc_mime_attachment));
190         memset(Msg->MsgBody, 0, sizeof(wc_mime_attachment));
191         Msg->MsgBody->msgnum = msgnum;
192
193         if (!load_message(Msg, FoundCharset, &Error)) {
194                 StrBufAppendBuf(Target, Error, 0);
195                 FreeStrBuf(&Error);
196         }
197
198         /* Extract just the content-type (omit attributes such as "charset") */
199         StrBufExtract_token(Buf, Msg->MsgBody->ContentType, 0, ';');
200         StrBufTrim(Buf);
201         StrBufLowerCase(Buf);
202
203         StackContext(TP, &SuperTP, Msg, CTX_MAILSUM, 0, NULL);
204         {
205                 /* Locate a renderer capable of converting this MIME part into HTML */
206                 if (GetHash(MimeRenderHandler, SKEY(Buf), &vHdr) &&
207                     (vHdr != NULL)) {
208                         RenderMimeFuncStruct *Render;
209                         
210                         StackContext(&SuperTP, &SubTP, Msg->MsgBody, CTX_MIME_ATACH, 0, NULL);
211                         {
212                                 Render = (RenderMimeFuncStruct*)vHdr;
213                                 Render->f(Target, &SubTP, FoundCharset);
214                         }
215                         UnStackContext(&SubTP);
216                 }
217                 
218                 if (StrLength(Msg->reply_references)> 0) {
219                         /* Trim down excessively long lists of thread references.  We eliminate the
220                          * second one in the list so that the thread root remains intact.
221                          */
222                         int rrtok = num_tokens(ChrPtr(Msg->reply_references), '|');
223                         int rrlen = StrLength(Msg->reply_references);
224                         if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
225                                 StrBufRemove_token(Msg->reply_references, 1, '|');
226                         }
227                 }
228
229                 /* now check if we need to translate some mimeparts, and remove the duplicate */
230                 it = GetNewHashPos(Msg->AllAttach, 0);
231                 while (GetNextHashPos(Msg->AllAttach, it, &len, &Key, &vMime) && 
232                        (vMime != NULL)) {
233                         StackContext(&SuperTP, &SubTP, vMime, CTX_MIME_ATACH, 0, NULL);
234                         {
235                                 evaluate_mime_part(Target, &SubTP);
236                         }
237                         UnStackContext(&SubTP);
238                 }
239                 DeleteHashPos(&it);
240                 *OutMime = DoTemplate(tmpl, tmpllen, Target, &SuperTP);
241         }
242         UnStackContext(&SuperTP);
243
244         DestroyMessageSummary(Msg);
245         FreeStrBuf(&FoundCharset);
246         FreeStrBuf(&Buf);
247         return 1;
248 }
249
250
251 long
252 HttpStatus(long CitadelStatus)
253 {
254         long httpstatus = 502;
255         
256         switch (MAJORCODE(CitadelStatus))
257         {
258         case LISTING_FOLLOWS:
259         case CIT_OK:
260                 httpstatus = 201;
261                 break;
262         case ERROR:
263                 switch (MINORCODE(CitadelStatus))
264                 {
265                 case INTERNAL_ERROR:
266                         httpstatus = 403;
267                         break;
268                         
269                 case TOO_BIG:
270                 case ILLEGAL_VALUE:
271                 case HIGHER_ACCESS_REQUIRED:
272                 case MAX_SESSIONS_EXCEEDED:
273                 case RESOURCE_BUSY:
274                 case RESOURCE_NOT_OPEN:
275                 case NOT_HERE:
276                 case INVALID_FLOOR_OPERATION:
277                 case FILE_NOT_FOUND:
278                 case ROOM_NOT_FOUND:
279                         httpstatus = 409;
280                         break;
281
282                 case MESSAGE_NOT_FOUND:
283                 case ALREADY_EXISTS:
284                         httpstatus = 403;
285                         break;
286
287                 case NO_SUCH_SYSTEM:
288                         httpstatus = 502;
289                         break;
290
291                 default:
292                 case CMD_NOT_SUPPORTED:
293                 case PASSWORD_REQUIRED:
294                 case ALREADY_LOGGED_IN:
295                 case USERNAME_REQUIRED:
296                 case NOT_LOGGED_IN:
297                 case SERVER_SHUTTING_DOWN:
298                 case NO_SUCH_USER:
299                 case ASYNC_GEXP:
300                         httpstatus = 502;
301                         break;
302                 }
303                 break;
304
305         default:
306         case BINARY_FOLLOWS:
307         case SEND_BINARY:
308         case START_CHAT_MODE:
309         case ASYNC_MSG:
310         case MORE_DATA:
311         case SEND_LISTING:
312                 httpstatus = 502; /* aeh... whut? */
313                 break;
314         }
315
316         return httpstatus;
317 }
318
319 /*
320  * Unadorned HTML output of an individual message, suitable
321  * for placing in a hidden iframe, for printing, or whatever
322  */
323 void handle_one_message(void) 
324 {
325         long CitStatus = ERROR + NOT_HERE;
326         int CopyMessage = 0;
327         const StrBuf *Destination;
328         void *vLine;
329         const StrBuf *Mime;
330         long msgnum = 0L;
331         wcsession *WCC = WC;
332         const StrBuf *Tmpl;
333         StrBuf *CmdBuf = NULL;
334         const char *pMsg;
335
336
337         pMsg = strchr(ChrPtr(WCC->Hdr->HR.ReqLine), '/');
338         if (pMsg == NULL) {
339                 HttpStatus(CitStatus);
340                 return;
341         }
342
343         msgnum = atol(pMsg + 1);
344         StrBufCutAt(WCC->Hdr->HR.ReqLine, 0, pMsg);
345         gotoroom(WCC->Hdr->HR.ReqLine);
346         switch (WCC->Hdr->HR.eReqType)
347         {
348         case eGET:
349         case ePOST:
350                 Tmpl = sbstr("template");
351                 if (StrLength(Tmpl) > 0) 
352                         read_message(WCC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime, NULL);
353                 else 
354                         read_message(WCC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime, NULL);
355                 http_transmit_thing(ChrPtr(Mime), 0);
356                 break;
357         case eDELETE:
358                 CmdBuf = NewStrBuf ();
359                 if ((WCC->CurRoom.RAFlags & UA_ISTRASH) != 0) { /* Delete from Trash is a real delete */
360                         serv_printf("DELE %ld", msgnum);        
361                 }
362                 else {                  /* Otherwise move it to Trash */
363                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
364                 }
365                 StrBuf_ServGetln(CmdBuf);
366                 GetServerStatusMsg(CmdBuf, &CitStatus, 1, 0);
367                 HttpStatus(CitStatus);
368                 break;
369         case eCOPY:
370                 CopyMessage = 1;
371         case eMOVE:
372                 if (GetHash(WCC->Hdr->HTTPHeaders, HKEY("DESTINATION"), &vLine) &&
373                     (vLine!=NULL)) {
374                         Destination = (StrBuf*) vLine;
375                         serv_printf("MOVE %ld|%s|%d", msgnum, ChrPtr(Destination), CopyMessage);
376                         StrBuf_ServGetln(CmdBuf);
377                         GetServerStatusMsg(CmdBuf, NULL, 1, 0);
378                         GetServerStatus(CmdBuf, &CitStatus);
379                         HttpStatus(CitStatus);
380                 }
381                 else
382                         HttpStatus(500);
383                 break;
384         default:
385                 break;
386
387         }
388 }
389
390
391 /*
392  * Unadorned HTML output of an individual message, suitable
393  * for placing in a hidden iframe, for printing, or whatever
394  */
395 void embed_message(void) {
396         const StrBuf *Mime;
397         long msgnum = 0L;
398         wcsession *WCC = WC;
399         const StrBuf *Tmpl;
400         StrBuf *CmdBuf = NULL;
401
402         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
403         if (msgnum <= 0) return;
404
405         switch (WCC->Hdr->HR.eReqType)
406         {
407         case eGET:
408         case ePOST:
409                 Tmpl = sbstr("template");
410                 if (StrLength(Tmpl) > 0) 
411                         read_message(WCC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime, NULL);
412                 else 
413                         read_message(WCC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime, NULL);
414                 http_transmit_thing(ChrPtr(Mime), 0);
415                 break;
416         case eDELETE:
417                 CmdBuf = NewStrBuf ();
418                 if ((WCC->CurRoom.RAFlags & UA_ISTRASH) != 0) { /* Delete from Trash is a real delete */
419                         serv_printf("DELE %ld", msgnum);        
420                 }
421                 else {                  /* Otherwise move it to Trash */
422                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
423                 }
424                 StrBuf_ServGetln(CmdBuf);
425                 GetServerStatusMsg(CmdBuf, NULL, 1, 0);
426                 break;
427         default:
428                 break;
429
430         }
431 }
432
433
434 /*
435  * Printable view of a message
436  */
437 void print_message(void) {
438         long msgnum = 0L;
439         const StrBuf *Mime;
440
441         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
442         output_headers(0, 0, 0, 0, 0, 0);
443
444         hprintf("Content-type: text/html\r\n"
445                 "Server: " PACKAGE_STRING "\r\n"
446                 "Connection: close\r\n");
447
448         begin_burst();
449
450         read_message(WC->WBuf, HKEY("view_message_print"), msgnum, NULL, &Mime, NULL);
451
452         wDumpContent(0);
453 }
454
455 /*
456  * Display a message's headers
457  */
458 void display_headers(void) {
459         long msgnum = 0L;
460         char buf[1024];
461
462         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
463         output_headers(0, 0, 0, 0, 0, 0);
464
465         hprintf("Content-type: text/plain\r\n"
466                 "Server: %s\r\n"
467                 "Connection: close\r\n",
468                 PACKAGE_STRING);
469         begin_burst();
470
471         serv_printf("MSG2 %ld|1", msgnum);
472         serv_getln(buf, sizeof buf);
473         if (buf[0] == '1') {
474                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
475                         wc_printf("%s\n", buf);
476                 }
477         }
478
479         wDumpContent(0);
480 }
481
482
483
484 /*
485  * load message pointers from the server for a "read messages" operation
486  *
487  * servcmd:             the citadel command to send to the citserver
488  */
489 int load_msg_ptrs(const char *servcmd,
490                   const char *filter,
491                   SharedMessageStatus *Stat, 
492                   load_msg_ptrs_detailheaders LH)
493 {
494         wcsession *WCC = WC;
495         message_summary *Msg;
496         StrBuf *Buf, *Buf2;
497         long len;
498         int n;
499         int skipit;
500         const char *Ptr = NULL;
501         int StatMajor;
502
503         Stat->lowest_found = LONG_MAX;
504         Stat->highest_found = LONG_MIN;
505
506         if (WCC->summ != NULL) {
507                 DeleteHash(&WCC->summ);
508         }
509         WCC->summ = NewHash(1, Flathash);
510         
511         Buf = NewStrBuf();
512         serv_puts(servcmd);
513         StrBuf_ServGetln(Buf);
514         StatMajor = GetServerStatus(Buf, NULL);
515         switch (StatMajor) {
516         case 1:
517                 break;
518         case 8:
519                 if (filter != NULL) {
520                         serv_puts(filter);
521                         serv_puts("000");
522                         break;
523                 }
524                 /* fall back to empty filter in case of we were fooled... */
525                 serv_puts("");
526                 serv_puts("000");
527                 break;
528         default:
529                 FreeStrBuf(&Buf);
530                 return (Stat->nummsgs);
531         }
532         Buf2 = NewStrBuf();
533         while (len = StrBuf_ServGetln(Buf), 
534                ((len >= 0) &&
535                 ((len != 3) || 
536                  strcmp(ChrPtr(Buf), "000")!= 0)))
537         {
538                 if (Stat->nummsgs < Stat->maxload) {
539                         skipit = 0;
540                         Ptr = NULL;
541                         Msg = (message_summary*)malloc(sizeof(message_summary));
542                         memset(Msg, 0, sizeof(message_summary));
543
544                         Msg->msgnum = StrBufExtractNext_long(Buf, &Ptr, '|');
545                         Msg->date = StrBufExtractNext_long(Buf, &Ptr, '|');
546
547                         if (Stat->nummsgs == 0) {
548                                 if (Msg->msgnum < Stat->lowest_found) {
549                                         Stat->lowest_found = Msg->msgnum;
550                                 }
551                                 if (Msg->msgnum > Stat->highest_found) {
552                                         Stat->highest_found = Msg->msgnum;
553                                 }
554                         }
555
556                         if ((Msg->msgnum == 0) && (StrLength(Buf) < 32)) {
557                                 free(Msg);
558                                 continue;
559                         }
560
561                         /* 
562                          * as citserver probably gives us messages in forward date sorting
563                          * nummsgs should be the same order as the message date.
564                          */
565                         if (Msg->date == 0) {
566                                 Msg->date = Stat->nummsgs;
567                                 if (StrLength(Buf) < 32) 
568                                         skipit = 1;
569                         }
570                         if ((!skipit) && (LH != NULL)) {
571                                 if (!LH(Buf, &Ptr, Msg, Buf2)){
572                                         free(Msg);
573                                         continue;
574                                 }                                       
575                         }
576                         n = Msg->msgnum;
577                         Put(WCC->summ, (const char *)&n, sizeof(n), Msg, DestroyMessageSummary);
578                 }
579                 Stat->nummsgs++;
580         }
581         FreeStrBuf(&Buf2);
582         FreeStrBuf(&Buf);
583         return (Stat->nummsgs);
584 }
585
586
587
588 /**
589  * \brief sets FlagToSet for each of ScanMe that appears in MatchMSet
590  * \param ScanMe List of BasicMsgStruct to be searched it MatchSet
591  * \param MatchMSet MSet we want to flag
592  * \param FlagToSet Flag to set on each BasicMsgStruct->Flags if in MSet
593  */
594 long SetFlagsFromMSet(HashList *ScanMe, MSet *MatchMSet, int FlagToSet, int Reverse)
595 {
596         const char *HashKey;
597         long HKLen;
598         long count = 0;
599         HashPos *at;
600         void *vMsg;
601         message_summary *Msg;
602
603         at = GetNewHashPos(ScanMe, 0);
604         while (GetNextHashPos(ScanMe, at, &HKLen, &HashKey, &vMsg)) {
605                 /* Are you a new message, or an old message? */
606                 Msg = (message_summary*) vMsg;
607                 if (Reverse && IsInMSetList(MatchMSet, Msg->msgnum)) {
608                         Msg->Flags = Msg->Flags | FlagToSet;
609                         count++;
610                 }
611                 else if (!Reverse && !IsInMSetList(MatchMSet, Msg->msgnum)) {
612                         Msg->Flags = Msg->Flags | FlagToSet;
613                         count++;
614                 }
615         }
616         DeleteHashPos(&at);
617         return count;
618 }
619
620
621 long load_seen_flags(void)
622 {
623         long count = 0;
624         StrBuf *OldMsg;
625         wcsession *WCC = WC;
626         MSet *MatchMSet;
627
628         OldMsg = NewStrBuf();
629         serv_puts("GTSN");
630         StrBuf_ServGetln(OldMsg);
631         if (GetServerStatus(OldMsg, NULL) == 2) {
632                 StrBufCutLeft(OldMsg, 4);
633         }
634         else {
635                 FreeStrBuf(&OldMsg);
636                 return 0;
637         }
638
639         if (ParseMSet(&MatchMSet, OldMsg))
640         {
641                 count = SetFlagsFromMSet(WCC->summ, MatchMSet, MSGFLAG_READ, 0);
642         }
643         DeleteMSet(&MatchMSet);
644         FreeStrBuf(&OldMsg);
645         return count;
646 }
647
648 extern readloop_struct rlid[];
649
650 typedef struct _RoomRenderer{
651         int RoomType;
652
653         GetParamsGetServerCall_func GetParamsGetServerCall;
654         
655         PrintViewHeader_func PrintPageHeader;
656         PrintViewHeader_func PrintViewHeader;
657         LoadMsgFromServer_func LoadMsgFromServer;
658         RenderView_or_Tail_func RenderView_or_Tail;
659         View_Cleanup_func ViewCleanup;
660         load_msg_ptrs_detailheaders LHParse;
661 } RoomRenderer;
662
663
664 /*
665  * command loop for reading messages
666  *
667  * Set oper to "readnew" or "readold" or "readfwd" or "headers" or "readgt" or "readlt" or "do_search"
668  */
669 void readloop(long oper, eCustomRoomRenderer ForceRenderer)
670 {
671         RoomRenderer *ViewMsg;
672         void *vViewMsg;
673         void *vMsg;
674         message_summary *Msg;
675         char cmd[256] = "";
676         char filter[256] = "";
677         int i, r;
678         wcsession *WCC = WC;
679         HashPos *at;
680         const char *HashKey;
681         long HKLen;
682         WCTemplputParams SubTP;
683         SharedMessageStatus Stat;
684         void *ViewSpecific = NULL;
685
686         if (havebstr("is_summary") && (1 == (ibstr("is_summary")))) {
687                 WCC->CurRoom.view = VIEW_MAILBOX;
688         }
689
690         if (havebstr("view")) {
691                 WCC->CurRoom.view = ibstr("view");
692         }
693
694         memset(&Stat, 0, sizeof(SharedMessageStatus));
695         Stat.maxload = 10000;
696         Stat.lowest_found = (-1);
697         Stat.highest_found = (-1);
698         if (ForceRenderer == eUseDefault)
699                 GetHash(ReadLoopHandler, IKEY(WCC->CurRoom.view), &vViewMsg);
700         else 
701                 GetHash(ReadLoopHandler, IKEY(ForceRenderer), &vViewMsg);
702         if (vViewMsg == NULL) {
703                 WCC->CurRoom.view = VIEW_BBS;
704                 GetHash(ReadLoopHandler, IKEY(WCC->CurRoom.view), &vViewMsg);
705         }
706         if (vViewMsg == NULL) {
707                 return;                 /* TODO: print message */
708         }
709
710         ViewMsg = (RoomRenderer*) vViewMsg;
711         if (ViewMsg->PrintPageHeader == NULL)
712                 output_headers(1, 1, 1, 0, 0, 0);
713         else 
714                 ViewMsg->PrintPageHeader(&Stat, ViewSpecific);
715
716         if (ViewMsg->GetParamsGetServerCall != NULL) {
717                 r = ViewMsg->GetParamsGetServerCall(
718                        &Stat,
719                        &ViewSpecific,
720                        oper,
721                        cmd, sizeof(cmd),
722                        filter, sizeof(filter)
723                 );
724         } else {
725                 r = 0;
726         }
727
728         switch(r)
729         {
730         case 400:
731         case 404:
732
733                 return;
734         case 300: /* the callback hook should do the work for us here, since he knows what to do. */
735                 return;
736         case 200:
737         default:
738                 break;
739         }
740         if (!IsEmptyStr(cmd)) {
741                 const char *p = NULL;
742                 if (!IsEmptyStr(filter))
743                         p = filter;
744                 Stat.nummsgs = load_msg_ptrs(cmd, p, &Stat, ViewMsg->LHParse);
745         }
746
747         if (Stat.sortit) {
748                 CompareFunc SortIt;
749                 StackContext(NULL, &SubTP, NULL, CTX_MAILSUM, 0, NULL);
750                 {
751                         SortIt =  RetrieveSort(&SubTP,
752                                                NULL, 0,
753                                                HKEY("date"),
754                                                Stat.defaultsortorder);
755                 }
756                 UnStackContext(&SubTP);
757                 if (SortIt != NULL)
758                         SortByPayload(WCC->summ, SortIt);
759         }
760         if (Stat.startmsg < 0) {
761                 Stat.startmsg =  0;
762         }
763
764         if (Stat.load_seen) Stat.numNewmsgs = load_seen_flags();
765         
766         /*
767          * Print any inforation above the message list...
768          */
769         if (ViewMsg->PrintViewHeader != NULL)
770                 ViewMsg->PrintViewHeader(&Stat, &ViewSpecific);
771
772         WCC->startmsg =  Stat.startmsg;
773         WCC->maxmsgs = Stat.maxmsgs;
774         WCC->num_displayed = 0;
775
776         /* Put some helpful data in vars for mailsummary_json */
777         {
778                 StrBuf *Foo;
779                 
780                 Foo = NewStrBuf ();
781                 StrBufPrintf(Foo, "%ld", Stat.nummsgs);
782                 PutBstr(HKEY("__READLOOP:TOTALMSGS"), NewStrBufDup(Foo)); /* keep Foo! */
783
784                 StrBufPrintf(Foo, "%ld", Stat.numNewmsgs);
785                 PutBstr(HKEY("__READLOOP:NEWMSGS"), NewStrBufDup(Foo)); /* keep Foo! */
786
787                 StrBufPrintf(Foo, "%ld", Stat.startmsg);
788                 PutBstr(HKEY("__READLOOP:STARTMSG"), Foo); /* store Foo elsewhere, descope it here. */
789         }
790
791         /*
792          * iterate over each message. if we need to load an attachment, do it here. 
793          */
794
795         if ((ViewMsg->LoadMsgFromServer != NULL) && 
796             (!IsEmptyStr(cmd)))
797         {
798                 at = GetNewHashPos(WCC->summ, 0);
799                 Stat.num_displayed = i = 0;
800                 while ( GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
801                         Msg = (message_summary*) vMsg;          
802                         if ((Msg->msgnum >= Stat.startmsg) && (Stat.num_displayed <= Stat.maxmsgs)) {
803                                 ViewMsg->LoadMsgFromServer(&Stat, 
804                                                            &ViewSpecific, 
805                                                            Msg, 
806                                                            (Msg->Flags & MSGFLAG_READ) != 0, 
807                                                            i);
808                         } 
809                         i++;
810                 }
811                 DeleteHashPos(&at);
812         }
813
814         /*
815          * Done iterating the message list. now tasks we want to do after.
816          */
817         if (ViewMsg->RenderView_or_Tail != NULL)
818                 ViewMsg->RenderView_or_Tail(&Stat, &ViewSpecific, oper);
819
820         if (ViewMsg->ViewCleanup != NULL)
821                 ViewMsg->ViewCleanup(&ViewSpecific);
822
823         WCC->startmsg = 0;
824         WCC->maxmsgs = 0;
825         if (WCC->summ != NULL) {
826                 DeleteHash(&WCC->summ);
827         }
828 }
829
830
831 /*
832  * Back end for post_message()
833  * ... this is where the actual message gets transmitted to the server.
834  */
835 void post_mime_to_server(void) {
836         wcsession *WCC = WC;
837         char top_boundary[SIZ];
838         char alt_boundary[SIZ];
839         int is_multipart = 0;
840         static int seq = 0;
841         wc_mime_attachment *att;
842         char *encoded;
843         size_t encoded_length;
844         size_t encoded_strlen;
845         char *txtmail = NULL;
846         int include_text_alt = 0;       /* Set to nonzero to include multipart/alternative text/plain */
847
848         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
849                 ChrPtr(WCC->serv_info->serv_fqdn),
850                 getpid(),
851                 ++seq
852         );
853         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
854                 ChrPtr(WCC->serv_info->serv_fqdn),
855                 getpid(),
856                 ++seq
857         );
858
859         /* RFC2045 requires this, and some clients look for it... */
860         serv_puts("MIME-Version: 1.0");
861         serv_puts("X-Mailer: " PACKAGE_STRING);
862
863         /* If there are attachments, we have to do multipart/mixed */
864         if (GetCount(WCC->attachments) > 0) {
865                 is_multipart = 1;
866         }
867
868         /* Only do multipart/alternative for mailboxes.  BBS and Wiki rooms don't need it. */
869         if ((WCC->CurRoom.view == VIEW_MAILBOX) ||
870             (WCC->CurRoom.view == VIEW_JSON_LIST))
871         {
872                 include_text_alt = 1;
873         }
874
875         if (is_multipart) {
876                 /* Remember, serv_printf() appends an extra newline */
877                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
878                 serv_printf("This is a multipart message in MIME format.\n");
879                 serv_printf("--%s", top_boundary);
880         }
881
882         /* Remember, serv_printf() appends an extra newline */
883         if (include_text_alt) {
884                 StrBuf *Buf;
885                 serv_printf("Content-type: multipart/alternative; "
886                         "boundary=\"%s\"\n", alt_boundary);
887                 serv_printf("This is a multipart message in MIME format.\n");
888                 serv_printf("--%s", alt_boundary);
889
890                 serv_puts("Content-type: text/plain; charset=utf-8");
891                 serv_puts("Content-Transfer-Encoding: quoted-printable");
892                 serv_puts("");
893                 txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
894                 Buf = NewStrBufPlain(txtmail, -1);
895                 free(txtmail);
896
897                 text_to_server_qp(Buf);     /* Transmit message in quoted-printable encoding */
898                 FreeStrBuf(&Buf);
899                 serv_printf("\n--%s", alt_boundary);
900         }
901
902         if (havebstr("markdown"))
903         {
904                 serv_puts("Content-type: text/x-markdown; charset=utf-8");
905                 serv_puts("Content-Transfer-Encoding: quoted-printable");
906                 serv_puts("");
907                 text_to_server_qp(sbstr("msgtext"));    /* Transmit message in quoted-printable encoding */
908         }
909         else
910         {
911                 serv_puts("Content-type: text/html; charset=utf-8");
912                 serv_puts("Content-Transfer-Encoding: quoted-printable");
913                 serv_puts("");
914                 serv_puts("<html><body>\r\n");
915                 text_to_server_qp(sbstr("msgtext"));    /* Transmit message in quoted-printable encoding */
916                 serv_puts("</body></html>\r\n");
917         }
918
919         if (include_text_alt) {
920                 serv_printf("--%s--", alt_boundary);
921         }
922         
923         if (is_multipart) {
924                 long len;
925                 const char *Key; 
926                 void *vAtt;
927                 HashPos  *it;
928
929                 /* Add in the attachments */
930                 it = GetNewHashPos(WCC->attachments, 0);
931                 while (GetNextHashPos(WCC->attachments, it, &len, &Key, &vAtt)) {
932                         att = (wc_mime_attachment *)vAtt;
933                         if (att->length == 0)
934                                 continue;
935                         encoded_length = ((att->length * 150) / 100);
936                         encoded = malloc(encoded_length);
937                         if (encoded == NULL) break;
938                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
939
940                         serv_printf("--%s", top_boundary);
941                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
942                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
943                         serv_puts("Content-transfer-encoding: base64");
944                         serv_puts("");
945                         serv_write(encoded, encoded_strlen);
946                         serv_puts("");
947                         serv_puts("");
948                         free(encoded);
949                 }
950                 serv_printf("--%s--", top_boundary);
951                 DeleteHashPos(&it);
952         }
953
954         serv_puts("000");
955 }
956
957
958 /*
959  * Post message (or don't post message)
960  *
961  * Note regarding the "dont_post" variable:
962  * A random value (actually, it's just a timestamp) is inserted as a hidden
963  * field called "postseq" when the display_enter page is generated.  This
964  * value is checked when posting, using the static variable dont_post.  If a
965  * user attempts to post twice using the same dont_post value, the message is
966  * discarded.  This prevents the accidental double-saving of the same message
967  * if the user happens to click the browser "back" button.
968  */
969 void post_message(void)
970 {
971         StrBuf *UserName;
972         StrBuf *EmailAddress;
973         StrBuf *EncBuf;
974         char buf[1024];
975         StrBuf *encoded_subject = NULL;
976         static long dont_post = (-1L);
977         int is_anonymous = 0;
978         const StrBuf *display_name = NULL;
979         wcsession *WCC = WC;
980         StrBuf *Buf;
981         
982         if (havebstr("force_room")) {
983                 gotoroom(sbstr("force_room"));
984         }
985
986         if (havebstr("display_name")) {
987                 display_name = sbstr("display_name");
988                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
989                         display_name = NULL;
990                         is_anonymous = 1;
991                 }
992         }
993
994         if (!strcasecmp(bstr("submit_action"), "cancel")) {
995                 AppendImportantMessage(_("Cancelled.  Message was not posted."), -1);
996         } else if (lbstr("postseq") == dont_post) {
997                 AppendImportantMessage(
998                         _("Automatically cancelled because you have already "
999                           "saved this message."), -1);
1000         } else {
1001                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1002                 StrBuf *Recp = NULL; 
1003                 StrBuf *Cc = NULL;
1004                 StrBuf *Bcc = NULL;
1005                 char *wikipage = NULL;
1006                 const StrBuf *my_email_addr = NULL;
1007                 StrBuf *CmdBuf = NULL;
1008                 StrBuf *references = NULL;
1009                 int saving_to_drafts = 0;
1010                 long HeaderLen = 0;
1011
1012                 saving_to_drafts = !strcasecmp(bstr("submit_action"), "draft");
1013                 Buf = NewStrBuf();
1014
1015                 if (saving_to_drafts) {
1016                         /* temporarily change to the drafts room */
1017                         serv_puts("GOTO _DRAFTS_");
1018                         StrBuf_ServGetln(Buf);
1019                         if (GetServerStatusMsg(Buf, NULL, 1, 2) != 2) {
1020                                 /* You probably don't even have a dumb Drafts folder */
1021                                 syslog(LOG_DEBUG, "%s:%d: server save to drafts error: %s\n", __FILE__, __LINE__, ChrPtr(Buf) + 4);
1022                                 AppendImportantMessage(_("Saved to Drafts failed: "), -1);
1023                                 display_enter();
1024                                 FreeStrBuf(&Buf);
1025                                 return;
1026                         }
1027                 }
1028
1029                 if (havebstr("references"))
1030                 {
1031                         const StrBuf *ref = sbstr("references");
1032                         references = NewStrBufDup(ref);
1033                         if (*ChrPtr(references) == '|') {       /* remove leading '|' if present */
1034                                 StrBufCutLeft(references, 1);
1035                         }
1036                         StrBufReplaceChars(references, '|', '!');
1037                 }
1038                 if (havebstr("subject")) {
1039                         const StrBuf *Subj;
1040                         /*
1041                          * make enough room for the encoded string; 
1042                          * plus the QP header 
1043                          */
1044                         Subj = sbstr("subject");
1045                         
1046                         StrBufRFC2047encode(&encoded_subject, Subj);
1047                 }
1048                 UserName = NewStrBuf();
1049                 EmailAddress = NewStrBuf();
1050                 EncBuf = NewStrBuf();
1051
1052                 Recp = StrBufSanitizeEmailRecipientVector(sbstr("recp"), UserName, EmailAddress, EncBuf);
1053                 Cc = StrBufSanitizeEmailRecipientVector(sbstr("cc"), UserName, EmailAddress, EncBuf);
1054                 Bcc = StrBufSanitizeEmailRecipientVector(sbstr("bcc"), UserName, EmailAddress, EncBuf);
1055
1056                 FreeStrBuf(&UserName);
1057                 FreeStrBuf(&EmailAddress);
1058                 FreeStrBuf(&EncBuf);
1059
1060                 wikipage = strdup(bstr("page"));
1061                 str_wiki_index(wikipage);
1062                 my_email_addr = sbstr("my_email_addr");
1063                 
1064                 HeaderLen = StrLength(Recp) + 
1065                         StrLength(encoded_subject) +
1066                         StrLength(Cc) +
1067                         StrLength(Bcc) + 
1068                         strlen(wikipage) +
1069                         StrLength(my_email_addr) + 
1070                         StrLength(references);
1071                 CmdBuf = NewStrBufPlain(NULL, sizeof (CMD) + HeaderLen);
1072                 StrBufPrintf(CmdBuf, 
1073                              CMD,
1074                              saving_to_drafts?"":ChrPtr(Recp),
1075                              is_anonymous,
1076                              ChrPtr(encoded_subject),
1077                              ChrPtr(display_name),
1078                              saving_to_drafts?"":ChrPtr(Cc),
1079                              saving_to_drafts?"":ChrPtr(Bcc),
1080                              wikipage,
1081                              ChrPtr(my_email_addr),
1082                              ChrPtr(references));
1083                 FreeStrBuf(&references);
1084                 FreeStrBuf(&encoded_subject);
1085                 free(wikipage);
1086
1087                 if ((HeaderLen + StrLength(sbstr("msgtext")) < 10) && 
1088                     (GetCount(WCC->attachments) == 0)){
1089                         AppendImportantMessage(_("Refusing to post empty message.\n"), -1);
1090                         FreeStrBuf(&CmdBuf);
1091                                 
1092                 }
1093                 else 
1094                 {
1095                         syslog(LOG_DEBUG, "%s\n", ChrPtr(CmdBuf));
1096                         serv_puts(ChrPtr(CmdBuf));
1097                         FreeStrBuf(&CmdBuf);
1098
1099                         StrBuf_ServGetln(Buf);
1100                         if (GetServerStatus(Buf, NULL) == 4) {
1101                                 if (saving_to_drafts) {
1102                                         if (  (havebstr("recp"))
1103                                               || (havebstr("cc"  ))
1104                                               || (havebstr("bcc" )) ) {
1105                                                 /* save recipient headers or room to post to */
1106                                                 serv_printf("To: %s", ChrPtr(Recp));
1107                                                 serv_printf("Cc: %s", ChrPtr(Cc));
1108                                                 serv_printf("Bcc: %s", ChrPtr(Bcc));
1109                                         } else {
1110                                                 serv_printf("X-Citadel-Room: %s", ChrPtr(WCC->CurRoom.name));
1111                                         }
1112                                 }
1113                                 post_mime_to_server();
1114                                 if (saving_to_drafts) {
1115                                         AppendImportantMessage(_("Message has been saved to Drafts.\n"), -1);
1116                                         gotoroom(WCC->CurRoom.name);
1117                                         fixview();
1118                                         readloop(readnew, eUseDefault);
1119                                         FreeStrBuf(&Buf);
1120                                         return;
1121                                 } else if (  (havebstr("recp"))
1122                                              || (havebstr("cc"  ))
1123                                              || (havebstr("bcc" ))
1124                                         ) {
1125                                         AppendImportantMessage(_("Message has been sent.\n"), -1);
1126                                 }
1127                                 else {
1128                                         AppendImportantMessage(_("Message has been posted.\n"), -1);
1129                                 }
1130                                 dont_post = lbstr("postseq");
1131                         } else {
1132                                 syslog(LOG_DEBUG, "%s:%d: server post error: %s", __FILE__, __LINE__, ChrPtr(Buf) + 4);
1133                                 AppendImportantMessage(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
1134                                 display_enter();
1135                                 if (saving_to_drafts) gotoroom(WCC->CurRoom.name);
1136                                 FreeStrBuf(&Recp);
1137                                 FreeStrBuf(&Buf);
1138                                 FreeStrBuf(&Cc);
1139                                 FreeStrBuf(&Bcc);
1140                                 return;
1141                         }
1142                 }
1143                 FreeStrBuf(&Recp);
1144                 FreeStrBuf(&Buf);
1145                 FreeStrBuf(&Cc);
1146                 FreeStrBuf(&Bcc);
1147         }
1148
1149         DeleteHash(&WCC->attachments);
1150
1151         /*
1152          *  We may have been supplied with instructions regarding the location
1153          *  to which we must return after posting.  If found, go there.
1154          */
1155         if (havebstr("return_to")) {
1156                 http_redirect(bstr("return_to"));
1157         }
1158         /*
1159          *  If we were editing a page in a wiki room, go to that page now.
1160          */
1161         else if (havebstr("page")) {
1162                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("page"));
1163                 http_redirect(buf);
1164         }
1165         /*
1166          *  Otherwise, just go to the "read messages" loop.
1167          */
1168         else {
1169                 fixview();
1170                 readloop(readnew, eUseDefault);
1171         }
1172 }
1173
1174
1175 /*
1176  * Client is uploading an attachment
1177  */
1178 void upload_attachment(void) {
1179         wcsession *WCC = WC;
1180         const char *pch;
1181         int n;
1182         const char *newn;
1183         long newnlen;
1184         void *v;
1185         wc_mime_attachment *att;
1186         const StrBuf *Tmpl = sbstr("template");
1187         const StrBuf *MimeType = NULL;
1188         const StrBuf *UID;
1189
1190         begin_burst();
1191         syslog(LOG_DEBUG, "upload_attachment()\n");
1192         if (!Tmpl) wc_printf("upload_attachment()<br>\n");
1193
1194         if (WCC->upload_length <= 0) {
1195                 syslog(LOG_DEBUG, "ERROR no attachment was uploaded\n");
1196                 if (Tmpl)
1197                 {
1198                         putlbstr("UPLOAD_ERROR", 1);
1199                         MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
1200                 }
1201                 else      wc_printf("ERROR no attachment was uploaded<br>\n");
1202                 http_transmit_thing(ChrPtr(MimeType), 0);
1203
1204                 return;
1205         }
1206
1207         syslog(LOG_DEBUG, "Client is uploading %d bytes\n", WCC->upload_length);
1208         if (Tmpl) putlbstr("UPLOAD_LENGTH", WCC->upload_length);
1209         else wc_printf("Client is uploading %d bytes<br>\n", WCC->upload_length);
1210
1211         att = (wc_mime_attachment*)malloc(sizeof(wc_mime_attachment));
1212         memset(att, 0, sizeof(wc_mime_attachment ));
1213         att->length = WCC->upload_length;
1214         att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1215         att->FileName = NewStrBufDup(WCC->upload_filename);
1216         UID = sbstr("qquuid");
1217         if (UID)
1218                 att->PartNum = NewStrBufDup(UID);
1219
1220         if (WCC->attachments == NULL) {
1221                 WCC->attachments = NewHash(1, Flathash);
1222         }
1223
1224         /* And add it to the list. */
1225         n = 0;
1226         if ((GetCount(WCC->attachments) > 0) && 
1227             GetHashAt(WCC->attachments, 
1228                       GetCount(WCC->attachments) -1, 
1229                       &newnlen, &newn, &v))
1230             n = *((int*) newn) + 1;
1231         Put(WCC->attachments, IKEY(n), att, DestroyMime);
1232
1233         /*
1234          * Mozilla sends a simple filename, which is what we want,
1235          * but Satan's Browser sends an entire pathname.  Reduce
1236          * the path to just a filename if we need to.
1237          */
1238         pch = strrchr(ChrPtr(att->FileName), '/');
1239         if (pch != NULL) {
1240                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1241         }
1242         pch = strrchr(ChrPtr(att->FileName), '\\');
1243         if (pch != NULL) {
1244                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1245         }
1246
1247         /*
1248          * Transfer control of this memory from the upload struct
1249          * to the attachment struct.
1250          */
1251         att->Data = WCC->upload;
1252         WCC->upload = NULL;
1253         WCC->upload_length = 0;
1254         
1255         if (Tmpl) MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
1256         http_transmit_thing(ChrPtr(MimeType), 0);
1257 }
1258
1259
1260 /*
1261  * Remove an attachment from the message currently being composed.
1262  *
1263  * Currently we identify the attachment to be removed by its filename.
1264  * There is probably a better way to do this.
1265  */
1266 void remove_attachment(void) {
1267         wcsession *WCC = WC;
1268         wc_mime_attachment *att;
1269         void *vAtt;
1270         StrBuf *WhichAttachment;
1271         HashPos *at;
1272         long len;
1273         int found=0;
1274         const char *key;
1275
1276         WhichAttachment = NewStrBufDup(sbstr("which_attachment"));
1277         if (ChrPtr(WhichAttachment)[0] == '/')
1278                 StrBufCutLeft(WhichAttachment, 1);
1279         StrBufUnescape(WhichAttachment, 0);
1280         at = GetNewHashPos(WCC->attachments, 0);
1281         do {
1282                 vAtt = NULL;
1283                 GetHashPos(WCC->attachments, at, &len, &key, &vAtt);
1284
1285                 att = (wc_mime_attachment*) vAtt;
1286                 if ((att != NULL) &&
1287                     (
1288                             !strcmp(ChrPtr(WhichAttachment), ChrPtr(att->FileName)) ||
1289                     ((att->PartNum != NULL) &&
1290                      !strcmp(ChrPtr(WhichAttachment), ChrPtr(att->PartNum)))
1291                             ))
1292                 {
1293                         DeleteEntryFromHash(WCC->attachments, at);
1294                         found=1;
1295                         break;
1296                 }
1297         }
1298         while (NextHashPos(WCC->attachments, at));
1299
1300         FreeStrBuf(&WhichAttachment);
1301         wc_printf("remove_attachment(%d) completed\n", found);
1302 }
1303
1304
1305 const char *ReplyToModeStrings [3] = {
1306         "reply",
1307         "replyall",
1308         "forward"
1309 };
1310 typedef enum _eReplyToNodes {
1311         eReply,
1312         eReplyAll,
1313         eForward
1314 }eReplyToNodes;
1315         
1316 /*
1317  * display the message entry screen
1318  */
1319 void display_enter(void)
1320 {
1321         const char *ReplyingModeStr;
1322         eReplyToNodes ReplyMode = eReply;
1323         StrBuf *Line;
1324         long Result;
1325         int rc;
1326         const StrBuf *display_name = NULL;
1327         int recipient_required = 0;
1328         int subject_required = 0;
1329         int is_anonymous = 0;
1330         wcsession *WCC = WC;
1331         int i = 0;
1332         long replying_to;
1333
1334         int prefer_md;
1335
1336         get_pref_yesno("markdown", &prefer_md, 0);
1337
1338         if (havebstr("force_room")) {
1339                 gotoroom(sbstr("force_room"));
1340         }
1341
1342         display_name = sbstr("display_name");
1343         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1344                 display_name = NULL;
1345                 is_anonymous = 1;
1346         }
1347
1348         /*
1349          * First, do we have permission to enter messages in this room at all?
1350          */
1351         Line = NewStrBuf();
1352         serv_puts("ENT0 0");
1353         StrBuf_ServGetln(Line);
1354         rc = GetServerStatusMsg(Line, &Result, 0, 2);
1355
1356         if (Result == 570) {            /* 570 means that we need a recipient here */
1357                 recipient_required = 1;
1358         }
1359         else if (rc != 2) {             /* Any other error means that we cannot continue */
1360                 rc = GetServerStatusMsg(Line, &Result, 0, 2);
1361                 fixview();
1362                 readloop(readnew, eUseDefault);
1363                 FreeStrBuf(&Line);
1364                 return;
1365         }
1366
1367         /* Is the server strongly recommending that the user enter a message subject? */
1368         if (StrLength(Line) > 4) {
1369                 subject_required = extract_int(ChrPtr(Line) + 4, 1);
1370         }
1371
1372         /*
1373          * Are we perhaps in an address book view?  If so, then an "enter
1374          * message" command really means "add new entry."
1375          */
1376         if (WCC->CurRoom.defview == VIEW_ADDRESSBOOK) {
1377                 do_edit_vcard(-1, "", NULL, NULL, "",  ChrPtr(WCC->CurRoom.name));
1378                 FreeStrBuf(&Line);
1379                 return;
1380         }
1381
1382         /*
1383          * Are we perhaps in a calendar room?  If so, then an "enter
1384          * message" command really means "add new calendar item."
1385          */
1386         if (WCC->CurRoom.defview == VIEW_CALENDAR) {
1387                 display_edit_event();
1388                 FreeStrBuf(&Line);
1389                 return;
1390         }
1391
1392         /*
1393          * Are we perhaps in a tasks view?  If so, then an "enter
1394          * message" command really means "add new task."
1395          */
1396         if (WCC->CurRoom.defview == VIEW_TASKS) {
1397                 display_edit_task();
1398                 FreeStrBuf(&Line);
1399                 return;
1400         }
1401
1402
1403         ReplyingModeStr = bstr("replying_mode");
1404         if (ReplyingModeStr != NULL) for (i = 0; i < 3; i++) {
1405                         if (strcmp(ReplyingModeStr, ReplyToModeStrings[i]) == 0) {
1406                                 ReplyMode = (eReplyToNodes) i;
1407                                 break;
1408                         }
1409                 }
1410                 
1411
1412         /*
1413          * If the "replying_to" variable is set, it refers to a message
1414          * number from which we must extract some header fields...
1415          */
1416         replying_to = lbstr("replying_to");
1417         if (replying_to > 0) {
1418                 long len;
1419                 StrBuf *wefw = NULL;
1420                 StrBuf *msgn = NULL;
1421                 StrBuf *from = NULL;
1422                 StrBuf *node = NULL;
1423                 StrBuf *rfca = NULL;
1424                 StrBuf *rcpt = NULL;
1425                 StrBuf *cccc = NULL;
1426                 StrBuf *replyto = NULL;
1427                 StrBuf *nvto = NULL;
1428                 serv_printf("MSG0 %ld|1", replying_to); 
1429
1430                 StrBuf_ServGetln(Line);
1431                 if (GetServerStatusMsg(Line, NULL, 0, 0) == 1)
1432                         while (len = StrBuf_ServGetln(Line),
1433                                (len >= 0) && 
1434                                ((len != 3)  ||
1435                                 strcmp(ChrPtr(Line), "000")))
1436                         {
1437                                 eMessageField which;
1438                                 if ((StrLength(Line) > 4) && 
1439                                     (ChrPtr(Line)[4] == '=') &&
1440                                     GetFieldFromMnemonic(&which, ChrPtr(Line)))
1441                                         switch (which) {
1442                                         case eMsgSubject: {
1443                                                 StrBuf *subj = NewStrBuf();
1444                                                 StrBuf *FlatSubject;
1445
1446                                                 if (ReplyMode == eForward) {
1447                                                         if (strncasecmp(ChrPtr(Line) + 5, "Fw:", 3)) {
1448                                                                 StrBufAppendBufPlain(subj, HKEY("Fw: "), 0);
1449                                                         }
1450                                                 }
1451                                                 else {
1452                                                         if (strncasecmp(ChrPtr(Line) + 5, "Re:", 3)) {
1453                                                                 StrBufAppendBufPlain(subj, HKEY("Re: "), 0);
1454                                                         }
1455                                                 }
1456                                                 StrBufAppendBufPlain(subj, 
1457                                                                      ChrPtr(Line) + 5, 
1458                                                                      StrLength(Line) - 5, 0);
1459                                                 FlatSubject = NewStrBufPlain(NULL, StrLength(subj));
1460                                                 StrBuf_RFC822_to_Utf8(FlatSubject, subj, NULL, NULL);
1461
1462                                                 PutBstr(HKEY("subject"), FlatSubject);
1463                                         }
1464                                                 break;
1465
1466                                         case eWeferences:
1467                                         {
1468                                                 int rrtok;
1469                                                 int rrlen;
1470
1471                                                 wefw = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1472                                         
1473                                                 /* Trim down excessively long lists of thread references.  We eliminate the
1474                                                  * second one in the list so that the thread root remains intact.
1475                                                  */
1476                                                 rrtok = num_tokens(ChrPtr(wefw), '|');
1477                                                 rrlen = StrLength(wefw);
1478                                                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
1479                                                         StrBufRemove_token(wefw, 1, '|');
1480                                                 }
1481                                                 break;
1482                                         }
1483
1484                                         case emessageId:
1485                                                 msgn = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1486                                                 break;
1487
1488                                         case eAuthor: {
1489                                                 StrBuf *FlatFrom;
1490                                                 from = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1491                                                 FlatFrom = NewStrBufPlain(NULL, StrLength(from));
1492                                                 StrBuf_RFC822_to_Utf8(FlatFrom, from, NULL, NULL);
1493                                                 FreeStrBuf(&from);
1494                                                 from = FlatFrom;
1495                                                 for (i=0; i<StrLength(from); ++i) {
1496                                                         if (ChrPtr(from)[i] == ',')
1497                                                                 StrBufPeek(from, NULL, i, ' ');
1498                                                 }
1499                                                 break;
1500                                         }
1501                                 
1502                                         case eRecipient:
1503                                                 rcpt = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1504                                                 break;
1505                         
1506                                 
1507                                         case eCarbonCopY:
1508                                                 cccc = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1509                                                 break;
1510
1511                                 
1512                                         case eNodeName:
1513                                                 node = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1514                                                 break;
1515                                         case eReplyTo:
1516                                                 replyto = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1517                                                 break;
1518                                         case erFc822Addr: {
1519                                                 StrBuf *FlatRFCA;
1520                                                 rfca = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1521                                                 FlatRFCA = NewStrBufPlain(NULL, StrLength(rfca));
1522                                                 StrBuf_RFC822_to_Utf8(FlatRFCA, rfca, NULL, NULL);
1523                                                 FreeStrBuf(&rfca);
1524                                                 rfca = FlatRFCA;
1525                                                 break;
1526                                         }
1527                                         case eenVelopeTo:
1528                                                 nvto = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1529                                                 putbstr("nvto", nvto);
1530                                                 break;
1531                                         case eXclusivID:
1532                                         case eHumanNode:
1533                                         case eJournal:
1534                                         case eListID:
1535                                         case eMesageText:
1536                                         case eOriginalRoom:
1537                                         case eMessagePath:
1538                                         case eSpecialField:
1539                                         case eTimestamp:
1540                                                 break;
1541
1542                                         }
1543                         }
1544
1545
1546                 if (StrLength(wefw) + StrLength(msgn) > 0) {
1547                         StrBuf *refs = NewStrBuf();
1548                         if (StrLength(wefw) > 0) {
1549                                 StrBufAppendBuf(refs, wefw, 0);
1550                         }
1551                         if ( (StrLength(wefw) > 0) && 
1552                              (StrLength(msgn) > 0) ) 
1553                         {
1554                                 StrBufAppendBufPlain(refs, HKEY("|"), 0);
1555                         }
1556                         if (StrLength(msgn) > 0) {
1557                                 StrBufAppendBuf(refs, msgn, 0);
1558                         }
1559                         PutBstr(HKEY("references"), refs);
1560                 }
1561
1562                 /*
1563                  * If this is a Reply or a ReplyAll, copy the sender's email into the To: field
1564                  */
1565                 if ((ReplyMode == eReply) || (ReplyMode == eReplyAll))
1566                 {
1567                         StrBuf *to_rcpt;
1568                         if ((StrLength(replyto) > 0) && (ReplyMode == eReplyAll)) {
1569                                 to_rcpt = NewStrBuf();
1570                                 StrBufAppendBuf(to_rcpt, replyto, 0);
1571                         }
1572                         else if (StrLength(rfca) > 0) {
1573                                 to_rcpt = NewStrBuf();
1574                                 StrBufAppendBuf(to_rcpt, from, 0);
1575                                 StrBufAppendBufPlain(to_rcpt, HKEY(" <"), 0);
1576                                 StrBufAppendBuf(to_rcpt, rfca, 0);
1577                                 StrBufAppendBufPlain(to_rcpt, HKEY(">"), 0);
1578                         }
1579                         else {
1580                                 to_rcpt =  from;
1581                                 from = NULL;
1582                                 if (    (StrLength(node) > 0)
1583                                         && (strcasecmp(ChrPtr(node), ChrPtr(WCC->serv_info->serv_nodename)))
1584                                 ) {
1585                                         StrBufAppendBufPlain(to_rcpt, HKEY(" @ "), 0);
1586                                         StrBufAppendBuf(to_rcpt, node, 0);
1587                                 }
1588                         }
1589                         PutBstr(HKEY("recp"), to_rcpt);
1590                 }
1591
1592                 /*
1593                  * Only if this is a ReplyAll, copy all recipients into the Cc: field
1594                  */
1595                 if (ReplyMode == eReplyAll)
1596                 {
1597                         StrBuf *cc_rcpt = rcpt;
1598                         rcpt = NULL;
1599                         if ((StrLength(cccc) > 0) && (StrLength(replyto) == 0))
1600                         {
1601                                 if (cc_rcpt != NULL)  {
1602                                         StrBufAppendPrintf(cc_rcpt, ", ");
1603                                         StrBufAppendBuf(cc_rcpt, cccc, 0);
1604                                 } else {
1605                                         cc_rcpt = cccc;
1606                                         cccc = NULL;
1607                                 }
1608                         }
1609                         if (cc_rcpt != NULL)
1610                                 PutBstr(HKEY("cc"), cc_rcpt);
1611                 }
1612                 FreeStrBuf(&wefw);
1613                 FreeStrBuf(&msgn);
1614                 FreeStrBuf(&from);
1615                 FreeStrBuf(&node);
1616                 FreeStrBuf(&rfca);
1617                 FreeStrBuf(&rcpt);
1618                 FreeStrBuf(&cccc);
1619         }
1620         FreeStrBuf(&Line);
1621         /*
1622          * Otherwise proceed normally.
1623          * Do a custom room banner with no navbar...
1624          */
1625
1626         if (recipient_required) {
1627                 const StrBuf *Recp = NULL; 
1628                 const StrBuf *Cc = NULL;
1629                 const StrBuf *Bcc = NULL;
1630                 char *wikipage = NULL;
1631                 StrBuf *CmdBuf = NULL;
1632                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1633                 
1634                 Recp = sbstr("recp");
1635                 Cc = sbstr("cc");
1636                 Bcc = sbstr("bcc");
1637                 wikipage = strdup(bstr("page"));
1638                 str_wiki_index(wikipage);
1639                 
1640                 CmdBuf = NewStrBufPlain(NULL, 
1641                                         sizeof (CMD) + 
1642                                         StrLength(Recp) + 
1643                                         StrLength(display_name) +
1644                                         StrLength(Cc) +
1645                                         StrLength(Bcc) + 
1646                                         strlen(wikipage));
1647
1648                 StrBufPrintf(CmdBuf, 
1649                              CMD,
1650                              ChrPtr(Recp), 
1651                              is_anonymous,
1652                              ChrPtr(display_name),
1653                              ChrPtr(Cc), 
1654                              ChrPtr(Bcc), 
1655                              wikipage
1656                 );
1657                 serv_puts(ChrPtr(CmdBuf));
1658                 StrBuf_ServGetln(CmdBuf);
1659                 free(wikipage);
1660
1661                 rc = GetServerStatusMsg(CmdBuf, &Result, 0, 0);
1662
1663                 if (    (Result == 570)         /* invalid or missing recipient(s) */
1664                         || (Result == 550)      /* higher access required to send Internet mail */
1665                 ) {
1666                         /* These errors will have been displayed and are excusable */
1667                 }
1668                 else if (rc != 2) {     /* Any other error means that we cannot continue */
1669                         AppendImportantMessage(ChrPtr(CmdBuf) + 4, StrLength(CmdBuf) - 4);
1670                         FreeStrBuf(&CmdBuf);
1671                         fixview();
1672                         readloop(readnew, eUseDefault);
1673                         return;
1674                 }
1675                 FreeStrBuf(&CmdBuf);
1676         }
1677         if (recipient_required)
1678                 PutBstr(HKEY("__RCPTREQUIRED"), NewStrBufPlain(HKEY("1")));
1679         if (recipient_required || subject_required)
1680                 PutBstr(HKEY("__SUBJREQUIRED"), NewStrBufPlain(HKEY("1")));
1681
1682         begin_burst();
1683         output_headers(1, 0, 0, 0, 1, 0);
1684         if ((WCC->CurRoom.defview == VIEW_WIKIMD) || prefer_md)
1685                 DoTemplate(HKEY("edit_markdown_epic"), NULL, &NoCtx);
1686         else
1687                 DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1688         end_burst();
1689
1690         return;
1691 }
1692
1693 /*
1694  * delete a message
1695  */
1696 void delete_msg(void)
1697 {
1698         long msgid;
1699         StrBuf *Line;
1700         
1701         msgid = lbstr("msgid");
1702         Line = NewStrBuf();
1703         if ((WC->CurRoom.RAFlags & UA_ISTRASH) != 0) {  /* Delete from Trash is a real delete */
1704                 serv_printf("DELE %ld", msgid); 
1705         }
1706         else {                  /* Otherwise move it to Trash */
1707                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1708         }
1709
1710         StrBuf_ServGetln(Line);
1711         GetServerStatusMsg(Line, NULL, 1, 0);
1712
1713         fixview();
1714
1715         readloop(readnew, eUseDefault);
1716 }
1717
1718
1719 /*
1720  * move a message to another room
1721  */
1722 void move_msg(void)
1723 {
1724         long msgid;
1725
1726         msgid = lbstr("msgid");
1727
1728         if (havebstr("move_button")) {
1729                 StrBuf *Line;
1730                 serv_printf("MOVE %ld|%s", msgid, bstr("target_room"));
1731                 Line = NewStrBuf();
1732                 StrBuf_ServGetln(Line);
1733                 GetServerStatusMsg(Line, NULL, 1, 0);
1734                 FreeStrBuf(&Line);
1735         } else {
1736                 AppendImportantMessage(_("The message was not moved."), -1);
1737         }
1738
1739         fixview();
1740         readloop(readnew, eUseDefault);
1741 }
1742
1743
1744
1745 /*
1746  * Generic function to output an arbitrary MIME attachment from
1747  * message being composed
1748  *
1749  * partnum              The MIME part to be output
1750  * filename             Fake filename to give
1751  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1752  */
1753 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1754 {
1755         void *vPart;
1756         StrBuf *content_type;
1757         wc_mime_attachment *part;
1758         int i;
1759
1760         i = StrToi(partnum);
1761         if (GetHash(WC->attachments, IKEY(i), &vPart) &&
1762             (vPart != NULL)) {
1763                 part = (wc_mime_attachment*) vPart;
1764                 if (force_download) {
1765                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1766                 }
1767                 else {
1768                         content_type = NewStrBufDup(part->ContentType);
1769                 }
1770                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1771                 http_transmit_thing(ChrPtr(content_type), 0);
1772         } else {
1773                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1774                 output_headers(0, 0, 0, 0, 0, 0);
1775                 hprintf("Content-Type: text/plain\r\n");
1776                 begin_burst();
1777                 wc_printf(_("An error occurred while retrieving this part: %s/%s\n"), 
1778                         ChrPtr(partnum), ChrPtr(filename));
1779                 end_burst();
1780         }
1781         FreeStrBuf(&content_type);
1782 }
1783
1784
1785 /*
1786  * Generic function to output an arbitrary MIME part from an arbitrary
1787  * message number on the server.
1788  *
1789  * msgnum               Number of the item on the citadel server
1790  * partnum              The MIME part to be output
1791  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1792  */
1793 void mimepart(int force_download)
1794 {
1795         int detect_mime = 0;
1796         long msgnum;
1797         long ErrorDetail;
1798         StrBuf *att;
1799         wcsession *WCC = WC;
1800         StrBuf *Buf;
1801         off_t bytes;
1802         StrBuf *ContentType = NewStrBufPlain(HKEY("application/octet-stream"));
1803         const char *CT;
1804
1805         att = Buf = NewStrBuf();
1806         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
1807         StrBufExtract_token(att, WCC->Hdr->HR.ReqLine, 1, '/');
1808
1809         serv_printf("OPNA %ld|%s", msgnum, ChrPtr(att));
1810         StrBuf_ServGetln(Buf);
1811         if (GetServerStatus(Buf, &ErrorDetail) == 2) {
1812                 StrBufCutLeft(Buf, 4);
1813                 bytes = StrBufExtract_long(Buf, 0, '|');
1814                 StrBufExtract_token(ContentType, Buf, 3, '|');
1815                 CheckGZipCompressionAllowed (SKEY(ContentType));
1816                 if (force_download)
1817                 {
1818                         FlushStrBuf(ContentType);
1819                         detect_mime = 0;
1820                 }
1821                 else
1822                 {
1823                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream"))
1824                         {
1825                                 StrBufExtract_token(Buf, WCC->Hdr->HR.ReqLine, 2, '/');
1826                                 CT = GuessMimeByFilename(SKEY(Buf));
1827                                 StrBufPlain(ContentType, CT, -1);
1828                         }
1829                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream"))
1830                         {
1831                                 detect_mime = 1;
1832                         }
1833                 }
1834                 serv_read_binary_to_http(ContentType, bytes, 0, detect_mime);
1835
1836                 serv_read_binary(WCC->WBuf, bytes, Buf);
1837                 serv_puts("CLOS");
1838                 StrBuf_ServGetln(Buf);
1839                 CT = ChrPtr(ContentType);
1840         } else {
1841                 StrBufCutLeft(Buf, 4);
1842                 switch (ErrorDetail) {
1843                 default:
1844                 case ERROR + MESSAGE_NOT_FOUND:
1845                         hprintf("HTTP/1.1 404 %s\n", ChrPtr(Buf));
1846                         break;
1847                 case ERROR + NOT_LOGGED_IN:
1848                         hprintf("HTTP/1.1 401 %s\n", ChrPtr(Buf));
1849                         break;
1850
1851                 case ERROR + HIGHER_ACCESS_REQUIRED:
1852                         hprintf("HTTP/1.1 403 %s\n", ChrPtr(Buf));
1853                         break;
1854                 case ERROR + INTERNAL_ERROR:
1855                 case ERROR + TOO_BIG:
1856                         hprintf("HTTP/1.1 500 %s\n", ChrPtr(Buf));
1857                         break;
1858                 }
1859
1860                 hprintf("Pragma: no-cache\r\n"
1861                         "Cache-Control: no-store\r\n"
1862                         "Expires: -1\r\n"
1863                 );
1864
1865                 hprintf("Content-Type: text/plain\r\n");
1866                 begin_burst();
1867                 wc_printf(_("An error occurred while retrieving this part: %s\n"), 
1868                         ChrPtr(Buf));
1869                 end_burst();
1870         }
1871         FreeStrBuf(&ContentType);
1872         FreeStrBuf(&Buf);
1873 }
1874
1875
1876 /*
1877  * Read any MIME part of a message, from the server, into memory.
1878  */
1879 StrBuf *load_mimepart(long msgnum, char *partnum)
1880 {
1881         off_t bytes;
1882         StrBuf *Buf;
1883         
1884         Buf = NewStrBuf();
1885         serv_printf("DLAT %ld|%s", msgnum, partnum);
1886         StrBuf_ServGetln(Buf);
1887         if (GetServerStatus(Buf, NULL) == 6) {
1888                 StrBufCutLeft(Buf, 4);
1889                 bytes = StrBufExtract_long(Buf, 0, '|');
1890                 FreeStrBuf(&Buf);
1891                 Buf = NewStrBuf();
1892                 StrBuf_ServGetBLOBBuffered(Buf, bytes);
1893                 return(Buf);
1894         }
1895         else {
1896                 FreeStrBuf(&Buf);
1897                 return(NULL);
1898         }
1899 }
1900
1901 /*
1902  * Read any MIME part of a message, from the server, into memory.
1903  */
1904 void MimeLoadData(wc_mime_attachment *Mime)
1905 {
1906         StrBuf *Buf;
1907         const char *Ptr;
1908         off_t bytes;
1909         /* TODO: is there a chance the content type is different from the one we know? */
1910
1911         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1912         Buf = NewStrBuf();
1913         StrBuf_ServGetln(Buf);
1914         if (GetServerStatus(Buf, NULL) == 6) {
1915                 Ptr = &(ChrPtr(Buf)[4]);
1916                 bytes = StrBufExtractNext_long(Buf, &Ptr, '|');
1917                 StrBufSkip_NTokenS(Buf, &Ptr, '|', 3);  /* filename, cbtype, mimetype */
1918                 if (Mime->Charset == NULL) Mime->Charset = NewStrBuf();
1919                 StrBufExtract_NextToken(Mime->Charset, Buf, &Ptr, '|');
1920                 
1921                 if (Mime->Data == NULL)
1922                         Mime->Data = NewStrBufPlain(NULL, bytes);
1923                 StrBuf_ServGetBLOBBuffered(Mime->Data, bytes);
1924         }
1925         else {
1926                 FlushStrBuf(Mime->Data);
1927                 /* TODO XImportant message */
1928         }
1929         FreeStrBuf(&Buf);
1930 }
1931
1932
1933 void view_mimepart(void) {
1934         mimepart(0);
1935 }
1936
1937 void download_mimepart(void) {
1938         mimepart(1);
1939 }
1940
1941 void view_postpart(void) {
1942         StrBuf *filename = NewStrBuf();
1943         StrBuf *partnum = NewStrBuf();
1944
1945         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1946         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1947
1948         postpart(partnum, filename, 0);
1949
1950         FreeStrBuf(&filename);
1951         FreeStrBuf(&partnum);
1952 }
1953
1954 void download_postpart(void) {
1955         StrBuf *filename = NewStrBuf();
1956         StrBuf *partnum = NewStrBuf();
1957
1958         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1959         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1960
1961         postpart(partnum, filename, 1);
1962
1963         FreeStrBuf(&filename);
1964         FreeStrBuf(&partnum);
1965 }
1966
1967
1968
1969 void show_num_attachments(void) {
1970         wc_printf("%d", GetCount(WC->attachments));
1971 }
1972
1973
1974 void h_readnew(void) { readloop(readnew, eUseDefault);}
1975 void h_readold(void) { readloop(readold, eUseDefault);}
1976 void h_readfwd(void) { readloop(readfwd, eUseDefault);}
1977 void h_headers(void) { readloop(headers, eUseDefault);}
1978 void h_do_search(void) { readloop(do_search, eUseDefault);}
1979 void h_readgt(void) { readloop(readgt, eUseDefault);}
1980 void h_readlt(void) { readloop(readlt, eUseDefault);}
1981
1982
1983
1984 /* Output message list in JSON format */
1985 void jsonMessageList(void) {
1986         StrBuf *View = NewStrBuf();
1987         const StrBuf *room = sbstr("room");
1988         long oper = (havebstr("query")) ? do_search : readnew;
1989         StrBufPrintf(View, "%d", VIEW_JSON_LIST);
1990         putbstr("view", View);; 
1991         gotoroom(room);
1992         readloop(oper, eUseDefault);
1993 }
1994
1995 void RegisterReadLoopHandlerset(
1996         int RoomType,
1997         GetParamsGetServerCall_func GetParamsGetServerCall,
1998         PrintViewHeader_func PrintPageHeader,
1999         PrintViewHeader_func PrintViewHeader,
2000         load_msg_ptrs_detailheaders LH,
2001         LoadMsgFromServer_func LoadMsgFromServer,
2002         RenderView_or_Tail_func RenderView_or_Tail,
2003         View_Cleanup_func ViewCleanup
2004         )
2005 {
2006         RoomRenderer *Handler;
2007
2008         Handler = (RoomRenderer*) malloc(sizeof(RoomRenderer));
2009
2010         Handler->RoomType = RoomType;
2011         Handler->GetParamsGetServerCall = GetParamsGetServerCall;
2012         Handler->PrintPageHeader = PrintPageHeader;
2013         Handler->PrintViewHeader = PrintViewHeader;
2014         Handler->LoadMsgFromServer = LoadMsgFromServer;
2015         Handler->RenderView_or_Tail = RenderView_or_Tail;
2016         Handler->ViewCleanup = ViewCleanup;
2017         Handler->LHParse = LH;
2018
2019         Put(ReadLoopHandler, IKEY(RoomType), Handler, NULL);
2020 }
2021
2022 void 
2023 InitModule_MSG
2024 (void)
2025 {
2026         RegisterPreference("use_sig",
2027                            _("Attach signature to email messages?"), 
2028                            PRF_YESNO, 
2029                            NULL);
2030         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
2031         RegisterPreference("default_header_charset",
2032                            _("Default character set for email headers:"), 
2033                            PRF_STRING, 
2034                            NULL);
2035         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
2036         RegisterPreference("defaultname", 
2037                            _("Preferred display name for email messages"), 
2038                            PRF_STRING, 
2039                            NULL);
2040         RegisterPreference("defaulthandle", 
2041                            _("Preferred display name for bulletin board posts"), 
2042                            PRF_STRING, 
2043                            NULL);
2044         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
2045         RegisterPreference("markdown",_("Prefer markdown editing"), PRF_YESNO, NULL);
2046
2047
2048         WebcitAddUrlHandler(HKEY("readnew"), "", 0, h_readnew, ANONYMOUS|NEED_URL);
2049         WebcitAddUrlHandler(HKEY("readold"), "", 0, h_readold, ANONYMOUS|NEED_URL);
2050         WebcitAddUrlHandler(HKEY("readfwd"), "", 0, h_readfwd, ANONYMOUS|NEED_URL);
2051         WebcitAddUrlHandler(HKEY("headers"), "", 0, h_headers, NEED_URL);
2052         WebcitAddUrlHandler(HKEY("readgt"), "", 0, h_readgt, ANONYMOUS|NEED_URL);
2053         WebcitAddUrlHandler(HKEY("readlt"), "", 0, h_readlt, ANONYMOUS|NEED_URL);
2054         WebcitAddUrlHandler(HKEY("do_search"), "", 0, h_do_search, 0);
2055         WebcitAddUrlHandler(HKEY("display_enter"), "", 0, display_enter, 0);
2056         WebcitAddUrlHandler(HKEY("post"), "", 0, post_message, PROHIBIT_STARTPAGE);
2057         WebcitAddUrlHandler(HKEY("move_msg"), "", 0, move_msg, PROHIBIT_STARTPAGE);
2058         WebcitAddUrlHandler(HKEY("delete_msg"), "", 0, delete_msg, PROHIBIT_STARTPAGE);
2059         WebcitAddUrlHandler(HKEY("msg"), "", 0, embed_message, NEED_URL);
2060         WebcitAddUrlHandler(HKEY("message"), "", 0, handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
2061         WebcitAddUrlHandler(HKEY("printmsg"), "", 0, print_message, NEED_URL);
2062         WebcitAddUrlHandler(HKEY("msgheaders"), "", 0, display_headers, NEED_URL);
2063
2064         WebcitAddUrlHandler(HKEY("mimepart"), "", 0, view_mimepart, NEED_URL);
2065         WebcitAddUrlHandler(HKEY("mimepart_download"), "", 0, download_mimepart, NEED_URL);
2066         WebcitAddUrlHandler(HKEY("postpart"), "", 0, view_postpart, NEED_URL|PROHIBIT_STARTPAGE);
2067         WebcitAddUrlHandler(HKEY("postpart_download"), "", 0, download_postpart, NEED_URL|PROHIBIT_STARTPAGE);
2068         WebcitAddUrlHandler(HKEY("upload_attachment"), "", 0, upload_attachment, AJAX);
2069         WebcitAddUrlHandler(HKEY("remove_attachment"), "", 0, remove_attachment, AJAX);
2070         WebcitAddUrlHandler(HKEY("show_num_attachments"), "", 0, show_num_attachments, AJAX);
2071
2072         /* json */
2073         WebcitAddUrlHandler(HKEY("roommsgs"), "", 0, jsonMessageList,0);
2074 }
2075
2076 void
2077 SessionDetachModule_MSG
2078 (wcsession *sess)
2079 {
2080         DeleteHash(&sess->summ);
2081 }