a8b4c60259a063ccf313212b65d18115cae536db
[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                   StrBuf *FoundCharset,
492                   SharedMessageStatus *Stat, 
493                   void **ViewSpecific,
494                   load_msg_ptrs_detailheaders LH,
495                   StrBuf *FetchMessageList,
496                   eMessageField *MessageFieldList,
497                   long HeaderCount)
498 {
499         wcsession *WCC = WC;
500         message_summary *Msg;
501         StrBuf *Buf, *Buf2;
502         long len;
503         int n;
504         int skipit;
505         const char *Ptr = NULL;
506         int StatMajor;
507
508         Stat->lowest_found = LONG_MAX;
509         Stat->highest_found = LONG_MIN;
510
511         if (WCC->summ != NULL) {
512                 DeleteHash(&WCC->summ);
513         }
514         WCC->summ = NewHash(1, Flathash);
515         
516         Buf = NewStrBuf();
517         serv_puts(servcmd);
518         StrBuf_ServGetln(Buf);
519         StatMajor = GetServerStatus(Buf, NULL);
520         switch (StatMajor) {
521         case 1:
522                 break;
523         case 8:
524                 if (filter != NULL) {
525                         serv_puts(filter);
526                         serv_puts("000");
527                         break;
528                 }
529                 else if (FetchMessageList != NULL) {
530                         serv_putbuf(FetchMessageList);
531                         break;
532                 }
533                 /* fall back to empty filter in case of we were fooled... */
534                 serv_puts("");
535                 serv_puts("000");
536                 break;
537         default:
538                 FreeStrBuf(&Buf);
539                 return (Stat->nummsgs);
540         }
541         Buf2 = NewStrBuf();
542         while (len = StrBuf_ServGetln(Buf), 
543                ((len >= 0) &&
544                 ((len != 3) || 
545                  strcmp(ChrPtr(Buf), "000")!= 0)))
546         {
547                 if (Stat->nummsgs < Stat->maxload) {
548                         skipit = 0;
549                         Ptr = NULL;
550                         Msg = (message_summary*)malloc(sizeof(message_summary));
551                         memset(Msg, 0, sizeof(message_summary));
552
553                         Msg->msgnum = StrBufExtractNext_long(Buf, &Ptr, '|');
554                         Msg->date = StrBufExtractNext_long(Buf, &Ptr, '|');
555                         if (MessageFieldList != NULL) {
556                                 long i;
557                                 for (i = 0; i < HeaderCount; i++) {
558                                         StrBufExtract_NextToken(Buf2, Buf, &Ptr, '|');
559                                         if (StrLength(Buf2) > 0) {
560                                                 EvaluateMsgHdrEnum(MessageFieldList[i], Msg, Buf2, FoundCharset);
561                                         }
562                                 }
563                         }
564                         else {
565                                 if (Stat->nummsgs == 0) {
566                                         if (Msg->msgnum < Stat->lowest_found) {
567                                                 Stat->lowest_found = Msg->msgnum;
568                                         }
569                                         if (Msg->msgnum > Stat->highest_found) {
570                                                 Stat->highest_found = Msg->msgnum;
571                                         }
572                                 }
573
574                                 if ((Msg->msgnum == 0) && (StrLength(Buf) < 32)) {
575                                         free(Msg);
576                                         continue;
577                                 }
578                         }
579                         /* 
580                          * as citserver probably gives us messages in forward date sorting
581                          * nummsgs should be the same order as the message date.
582                          */
583                         if (Msg->date == 0) {
584                                 Msg->date = Stat->nummsgs;
585                                 if (StrLength(Buf) < 32) 
586                                         skipit = 1;
587                         }
588                         if ((!skipit) && (LH != NULL)) {
589                                 if (!LH(Buf, &Ptr, Msg, Buf2, ViewSpecific)){
590                                         free(Msg);
591                                         continue;
592                                 }                                       
593                         }
594                         n = Msg->msgnum;
595                         Put(WCC->summ, (const char *)&n, sizeof(n), Msg, DestroyMessageSummary);
596                 }
597                 Stat->nummsgs++;
598         }
599         FreeStrBuf(&Buf2);
600         FreeStrBuf(&Buf);
601         return (Stat->nummsgs);
602 }
603
604
605
606 /**
607  * \brief sets FlagToSet for each of ScanMe that appears in MatchMSet
608  * \param ScanMe List of BasicMsgStruct to be searched it MatchSet
609  * \param MatchMSet MSet we want to flag
610  * \param FlagToSet Flag to set on each BasicMsgStruct->Flags if in MSet
611  */
612 long SetFlagsFromMSet(HashList *ScanMe, MSet *MatchMSet, int FlagToSet, int Reverse)
613 {
614         const char *HashKey;
615         long HKLen;
616         long count = 0;
617         HashPos *at;
618         void *vMsg;
619         message_summary *Msg;
620
621         at = GetNewHashPos(ScanMe, 0);
622         while (GetNextHashPos(ScanMe, at, &HKLen, &HashKey, &vMsg)) {
623                 /* Are you a new message, or an old message? */
624                 Msg = (message_summary*) vMsg;
625                 if (Reverse && IsInMSetList(MatchMSet, Msg->msgnum)) {
626                         Msg->Flags = Msg->Flags | FlagToSet;
627                         count++;
628                 }
629                 else if (!Reverse && !IsInMSetList(MatchMSet, Msg->msgnum)) {
630                         Msg->Flags = Msg->Flags | FlagToSet;
631                         count++;
632                 }
633         }
634         DeleteHashPos(&at);
635         return count;
636 }
637
638
639 long load_seen_flags(void)
640 {
641         long count = 0;
642         StrBuf *OldMsg;
643         wcsession *WCC = WC;
644         MSet *MatchMSet;
645
646         OldMsg = NewStrBuf();
647         serv_puts("GTSN");
648         StrBuf_ServGetln(OldMsg);
649         if (GetServerStatus(OldMsg, NULL) == 2) {
650                 StrBufCutLeft(OldMsg, 4);
651         }
652         else {
653                 FreeStrBuf(&OldMsg);
654                 return 0;
655         }
656
657         if (ParseMSet(&MatchMSet, OldMsg))
658         {
659                 count = SetFlagsFromMSet(WCC->summ, MatchMSet, MSGFLAG_READ, 0);
660         }
661         DeleteMSet(&MatchMSet);
662         FreeStrBuf(&OldMsg);
663         return count;
664 }
665
666 extern readloop_struct rlid[];
667
668 typedef struct _RoomRenderer{
669         int RoomType;
670
671         GetParamsGetServerCall_func GetParamsGetServerCall;
672         
673         PrintViewHeader_func PrintPageHeader;
674         PrintViewHeader_func PrintViewHeader;
675         LoadMsgFromServer_func LoadMsgFromServer;
676         RenderView_or_Tail_func RenderView_or_Tail;
677         View_Cleanup_func ViewCleanup;
678         load_msg_ptrs_detailheaders LHParse;
679         long HeaderCount;
680         StrBuf *FetchMessageList;
681         eMessageField *MessageFieldList;
682 } RoomRenderer;
683
684
685 /*
686  * command loop for reading messages
687  *
688  * Set oper to "readnew" or "readold" or "readfwd" or "headers" or "readgt" or "readlt" or "do_search"
689  */
690 void readloop(long oper, eCustomRoomRenderer ForceRenderer)
691 {
692         RoomRenderer *ViewMsg;
693         void *vViewMsg;
694         void *vMsg;
695         message_summary *Msg;
696         char cmd[256] = "";
697         char filter[256] = "";
698         int i, r;
699         wcsession *WCC = WC;
700         HashPos *at;
701         const char *HashKey;
702         long HKLen;
703         WCTemplputParams SubTP;
704         SharedMessageStatus Stat;
705         void *ViewSpecific = NULL;
706
707         if (havebstr("is_summary") && (1 == (ibstr("is_summary")))) {
708                 WCC->CurRoom.view = VIEW_MAILBOX;
709         }
710
711         if (havebstr("view")) {
712                 WCC->CurRoom.view = ibstr("view");
713         }
714
715         memset(&Stat, 0, sizeof(SharedMessageStatus));
716         Stat.maxload = 10000;
717         Stat.lowest_found = (-1);
718         Stat.highest_found = (-1);
719         if (ForceRenderer == eUseDefault)
720                 GetHash(ReadLoopHandler, IKEY(WCC->CurRoom.view), &vViewMsg);
721         else 
722                 GetHash(ReadLoopHandler, IKEY(ForceRenderer), &vViewMsg);
723         if (vViewMsg == NULL) {
724                 WCC->CurRoom.view = VIEW_BBS;
725                 GetHash(ReadLoopHandler, IKEY(WCC->CurRoom.view), &vViewMsg);
726         }
727         if (vViewMsg == NULL) {
728                 return;                 /* TODO: print message */
729         }
730
731         ViewMsg = (RoomRenderer*) vViewMsg;
732         if (ViewMsg->PrintPageHeader == NULL)
733                 output_headers(1, 1, 1, 0, 0, 0);
734         else 
735                 ViewMsg->PrintPageHeader(&Stat, ViewSpecific);
736
737         if (ViewMsg->GetParamsGetServerCall != NULL) {
738                 r = ViewMsg->GetParamsGetServerCall(
739                        &Stat,
740                        &ViewSpecific,
741                        oper,
742                        cmd, sizeof(cmd),
743                        filter, sizeof(filter)
744                 );
745         } else {
746                 r = 0;
747         }
748
749         switch(r)
750         {
751         case 400:
752         case 404:
753
754                 return;
755         case 300: /* the callback hook should do the work for us here, since he knows what to do. */
756                 return;
757         case 200:
758         default:
759                 break;
760         }
761         if (!IsEmptyStr(cmd)) {
762                 const char *p = NULL;
763                 StrBuf *FoundCharset = NULL;
764                 if (!IsEmptyStr(filter))
765                         p = filter;
766                 if (ViewMsg->HeaderCount > 0) {
767                         FoundCharset = NewStrBuf();
768                 }
769                 Stat.nummsgs = load_msg_ptrs(cmd, p,
770                                              FoundCharset,
771                                              &Stat,
772                                              &ViewSpecific,
773                                              ViewMsg->LHParse,
774                                              ViewMsg->FetchMessageList,
775                                              ViewMsg->MessageFieldList,
776                                              ViewMsg->HeaderCount);
777                 FreeStrBuf(&FoundCharset);
778         }
779
780         if (Stat.sortit) {
781                 CompareFunc SortIt;
782                 StackContext(NULL, &SubTP, NULL, CTX_MAILSUM, 0, NULL);
783                 {
784                         SortIt =  RetrieveSort(&SubTP,
785                                                NULL, 0,
786                                                HKEY("date"),
787                                                Stat.defaultsortorder);
788                 }
789                 UnStackContext(&SubTP);
790                 if (SortIt != NULL)
791                         SortByPayload(WCC->summ, SortIt);
792         }
793         if (Stat.startmsg < 0) {
794                 Stat.startmsg =  0;
795         }
796
797         if (Stat.load_seen) Stat.numNewmsgs = load_seen_flags();
798         
799         /*
800          * Print any inforation above the message list...
801          */
802         if (ViewMsg->PrintViewHeader != NULL)
803                 ViewMsg->PrintViewHeader(&Stat, &ViewSpecific);
804
805         WCC->startmsg =  Stat.startmsg;
806         WCC->maxmsgs = Stat.maxmsgs;
807         WCC->num_displayed = 0;
808
809         /* Put some helpful data in vars for mailsummary_json */
810         {
811                 StrBuf *Foo;
812                 
813                 Foo = NewStrBuf ();
814                 StrBufPrintf(Foo, "%ld", Stat.nummsgs);
815                 PutBstr(HKEY("__READLOOP:TOTALMSGS"), NewStrBufDup(Foo)); /* keep Foo! */
816
817                 StrBufPrintf(Foo, "%ld", Stat.numNewmsgs);
818                 PutBstr(HKEY("__READLOOP:NEWMSGS"), NewStrBufDup(Foo)); /* keep Foo! */
819
820                 StrBufPrintf(Foo, "%ld", Stat.startmsg);
821                 PutBstr(HKEY("__READLOOP:STARTMSG"), Foo); /* store Foo elsewhere, descope it here. */
822         }
823
824         /*
825          * iterate over each message. if we need to load an attachment, do it here. 
826          */
827
828         if ((ViewMsg->LoadMsgFromServer != NULL) && 
829             (!IsEmptyStr(cmd)))
830         {
831                 at = GetNewHashPos(WCC->summ, 0);
832                 Stat.num_displayed = i = 0;
833                 while ( GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
834                         Msg = (message_summary*) vMsg;          
835                         if ((Msg->msgnum >= Stat.startmsg) && (Stat.num_displayed <= Stat.maxmsgs)) {
836                                 ViewMsg->LoadMsgFromServer(&Stat, 
837                                                            &ViewSpecific, 
838                                                            Msg, 
839                                                            (Msg->Flags & MSGFLAG_READ) != 0, 
840                                                            i);
841                         } 
842                         i++;
843                 }
844                 DeleteHashPos(&at);
845         }
846
847         /*
848          * Done iterating the message list. now tasks we want to do after.
849          */
850         if (ViewMsg->RenderView_or_Tail != NULL)
851                 ViewMsg->RenderView_or_Tail(&Stat, &ViewSpecific, oper);
852
853         if (ViewMsg->ViewCleanup != NULL)
854                 ViewMsg->ViewCleanup(&ViewSpecific);
855
856         WCC->startmsg = 0;
857         WCC->maxmsgs = 0;
858         if (WCC->summ != NULL) {
859                 DeleteHash(&WCC->summ);
860         }
861 }
862
863
864 /*
865  * Back end for post_message()
866  * ... this is where the actual message gets transmitted to the server.
867  */
868 void post_mime_to_server(void) {
869         wcsession *WCC = WC;
870         char top_boundary[SIZ];
871         char alt_boundary[SIZ];
872         int is_multipart = 0;
873         static int seq = 0;
874         wc_mime_attachment *att;
875         char *encoded;
876         size_t encoded_length;
877         size_t encoded_strlen;
878         char *txtmail = NULL;
879         int include_text_alt = 0;       /* Set to nonzero to include multipart/alternative text/plain */
880
881         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
882                 ChrPtr(WCC->serv_info->serv_fqdn),
883                 getpid(),
884                 ++seq
885         );
886         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
887                 ChrPtr(WCC->serv_info->serv_fqdn),
888                 getpid(),
889                 ++seq
890         );
891
892         /* RFC2045 requires this, and some clients look for it... */
893         serv_puts("MIME-Version: 1.0");
894         serv_puts("X-Mailer: " PACKAGE_STRING);
895
896         /* If there are attachments, we have to do multipart/mixed */
897         if (GetCount(WCC->attachments) > 0) {
898                 is_multipart = 1;
899         }
900
901         /* Only do multipart/alternative for mailboxes.  BBS and Wiki rooms don't need it. */
902         if ((WCC->CurRoom.view == VIEW_MAILBOX) ||
903             (WCC->CurRoom.view == VIEW_JSON_LIST))
904         {
905                 include_text_alt = 1;
906         }
907
908         if (is_multipart) {
909                 /* Remember, serv_printf() appends an extra newline */
910                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
911                 serv_printf("This is a multipart message in MIME format.\n");
912                 serv_printf("--%s", top_boundary);
913         }
914
915         /* Remember, serv_printf() appends an extra newline */
916         if (include_text_alt) {
917                 StrBuf *Buf;
918                 serv_printf("Content-type: multipart/alternative; "
919                         "boundary=\"%s\"\n", alt_boundary);
920                 serv_printf("This is a multipart message in MIME format.\n");
921                 serv_printf("--%s", alt_boundary);
922
923                 serv_puts("Content-type: text/plain; charset=utf-8");
924                 serv_puts("Content-Transfer-Encoding: quoted-printable");
925                 serv_puts("");
926                 txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
927                 Buf = NewStrBufPlain(txtmail, -1);
928                 free(txtmail);
929
930                 text_to_server_qp(Buf);     /* Transmit message in quoted-printable encoding */
931                 FreeStrBuf(&Buf);
932                 serv_printf("\n--%s", alt_boundary);
933         }
934
935         if (havebstr("markdown"))
936         {
937                 serv_puts("Content-type: text/x-markdown; charset=utf-8");
938                 serv_puts("Content-Transfer-Encoding: quoted-printable");
939                 serv_puts("");
940                 text_to_server_qp(sbstr("msgtext"));    /* Transmit message in quoted-printable encoding */
941         }
942         else
943         {
944                 serv_puts("Content-type: text/html; charset=utf-8");
945                 serv_puts("Content-Transfer-Encoding: quoted-printable");
946                 serv_puts("");
947                 serv_puts("<html><body>\r\n");
948                 text_to_server_qp(sbstr("msgtext"));    /* Transmit message in quoted-printable encoding */
949                 serv_puts("</body></html>\r\n");
950         }
951
952         if (include_text_alt) {
953                 serv_printf("--%s--", alt_boundary);
954         }
955         
956         if (is_multipart) {
957                 long len;
958                 const char *Key; 
959                 void *vAtt;
960                 HashPos  *it;
961
962                 /* Add in the attachments */
963                 it = GetNewHashPos(WCC->attachments, 0);
964                 while (GetNextHashPos(WCC->attachments, it, &len, &Key, &vAtt)) {
965                         att = (wc_mime_attachment *)vAtt;
966                         if (att->length == 0)
967                                 continue;
968                         encoded_length = ((att->length * 150) / 100);
969                         encoded = malloc(encoded_length);
970                         if (encoded == NULL) break;
971                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
972
973                         serv_printf("--%s", top_boundary);
974                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
975                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
976                         serv_puts("Content-transfer-encoding: base64");
977                         serv_puts("");
978                         serv_write(encoded, encoded_strlen);
979                         serv_puts("");
980                         serv_puts("");
981                         free(encoded);
982                 }
983                 serv_printf("--%s--", top_boundary);
984                 DeleteHashPos(&it);
985         }
986
987         serv_puts("000");
988 }
989
990
991 /*
992  * Post message (or don't post message)
993  *
994  * Note regarding the "dont_post" variable:
995  * A random value (actually, it's just a timestamp) is inserted as a hidden
996  * field called "postseq" when the display_enter page is generated.  This
997  * value is checked when posting, using the static variable dont_post.  If a
998  * user attempts to post twice using the same dont_post value, the message is
999  * discarded.  This prevents the accidental double-saving of the same message
1000  * if the user happens to click the browser "back" button.
1001  */
1002 void post_message(void)
1003 {
1004         StrBuf *UserName;
1005         StrBuf *EmailAddress;
1006         StrBuf *EncBuf;
1007         char buf[1024];
1008         StrBuf *encoded_subject = NULL;
1009         static long dont_post = (-1L);
1010         int is_anonymous = 0;
1011         const StrBuf *display_name = NULL;
1012         wcsession *WCC = WC;
1013         StrBuf *Buf;
1014         
1015         if (havebstr("force_room")) {
1016                 gotoroom(sbstr("force_room"));
1017         }
1018
1019         if (havebstr("display_name")) {
1020                 display_name = sbstr("display_name");
1021                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1022                         display_name = NULL;
1023                         is_anonymous = 1;
1024                 }
1025         }
1026
1027         if (!strcasecmp(bstr("submit_action"), "cancel")) {
1028                 AppendImportantMessage(_("Cancelled.  Message was not posted."), -1);
1029         } else if (lbstr("postseq") == dont_post) {
1030                 AppendImportantMessage(
1031                         _("Automatically cancelled because you have already "
1032                           "saved this message."), -1);
1033         } else {
1034                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1035                 StrBuf *Recp = NULL; 
1036                 StrBuf *Cc = NULL;
1037                 StrBuf *Bcc = NULL;
1038                 StrBuf *wikipage = NULL;
1039                 const StrBuf *my_email_addr = NULL;
1040                 StrBuf *CmdBuf = NULL;
1041                 StrBuf *references = NULL;
1042                 int saving_to_drafts = 0;
1043                 long HeaderLen = 0;
1044
1045                 saving_to_drafts = !strcasecmp(bstr("submit_action"), "draft");
1046                 Buf = NewStrBuf();
1047
1048                 if (saving_to_drafts) {
1049                         /* temporarily change to the drafts room */
1050                         serv_puts("GOTO _DRAFTS_");
1051                         StrBuf_ServGetln(Buf);
1052                         if (GetServerStatusMsg(Buf, NULL, 1, 2) != 2) {
1053                                 /* You probably don't even have a dumb Drafts folder */
1054                                 syslog(LOG_DEBUG, "%s:%d: server save to drafts error: %s\n", __FILE__, __LINE__, ChrPtr(Buf) + 4);
1055                                 AppendImportantMessage(_("Saved to Drafts failed: "), -1);
1056                                 display_enter();
1057                                 FreeStrBuf(&Buf);
1058                                 return;
1059                         }
1060                 }
1061
1062                 if (havebstr("references"))
1063                 {
1064                         const StrBuf *ref = sbstr("references");
1065                         references = NewStrBufDup(ref);
1066                         if (*ChrPtr(references) == '|') {       /* remove leading '|' if present */
1067                                 StrBufCutLeft(references, 1);
1068                         }
1069                         StrBufReplaceChars(references, '|', '!');
1070                 }
1071                 if (havebstr("subject")) {
1072                         const StrBuf *Subj;
1073                         /*
1074                          * make enough room for the encoded string; 
1075                          * plus the QP header 
1076                          */
1077                         Subj = sbstr("subject");
1078                         
1079                         StrBufRFC2047encode(&encoded_subject, Subj);
1080                 }
1081                 UserName = NewStrBuf();
1082                 EmailAddress = NewStrBuf();
1083                 EncBuf = NewStrBuf();
1084
1085                 Recp = StrBufSanitizeEmailRecipientVector(sbstr("recp"), UserName, EmailAddress, EncBuf);
1086                 Cc = StrBufSanitizeEmailRecipientVector(sbstr("cc"), UserName, EmailAddress, EncBuf);
1087                 Bcc = StrBufSanitizeEmailRecipientVector(sbstr("bcc"), UserName, EmailAddress, EncBuf);
1088
1089                 FreeStrBuf(&UserName);
1090                 FreeStrBuf(&EmailAddress);
1091                 FreeStrBuf(&EncBuf);
1092
1093                 wikipage = NewStrBufDup(sbstr("page"));
1094                 str_wiki_index(wikipage);
1095                 my_email_addr = sbstr("my_email_addr");
1096                 
1097                 HeaderLen = StrLength(Recp) + 
1098                         StrLength(encoded_subject) +
1099                         StrLength(Cc) +
1100                         StrLength(Bcc) + 
1101                         StrLength(wikipage) +
1102                         StrLength(my_email_addr) + 
1103                         StrLength(references);
1104                 CmdBuf = NewStrBufPlain(NULL, sizeof (CMD) + HeaderLen);
1105                 StrBufPrintf(CmdBuf, 
1106                              CMD,
1107                              saving_to_drafts?"":ChrPtr(Recp),
1108                              is_anonymous,
1109                              ChrPtr(encoded_subject),
1110                              ChrPtr(display_name),
1111                              saving_to_drafts?"":ChrPtr(Cc),
1112                              saving_to_drafts?"":ChrPtr(Bcc),
1113                              ChrPtr(wikipage),
1114                              ChrPtr(my_email_addr),
1115                              ChrPtr(references));
1116                 FreeStrBuf(&references);
1117                 FreeStrBuf(&encoded_subject);
1118                 free(wikipage);
1119
1120                 if ((HeaderLen + StrLength(sbstr("msgtext")) < 10) && 
1121                     (GetCount(WCC->attachments) == 0)){
1122                         AppendImportantMessage(_("Refusing to post empty message.\n"), -1);
1123                         FreeStrBuf(&CmdBuf);
1124                                 
1125                 }
1126                 else 
1127                 {
1128                         syslog(LOG_DEBUG, "%s\n", ChrPtr(CmdBuf));
1129                         serv_puts(ChrPtr(CmdBuf));
1130                         FreeStrBuf(&CmdBuf);
1131
1132                         StrBuf_ServGetln(Buf);
1133                         if (GetServerStatus(Buf, NULL) == 4) {
1134                                 if (saving_to_drafts) {
1135                                         if (  (havebstr("recp"))
1136                                               || (havebstr("cc"  ))
1137                                               || (havebstr("bcc" )) ) {
1138                                                 /* save recipient headers or room to post to */
1139                                                 serv_printf("To: %s", ChrPtr(Recp));
1140                                                 serv_printf("Cc: %s", ChrPtr(Cc));
1141                                                 serv_printf("Bcc: %s", ChrPtr(Bcc));
1142                                         } else {
1143                                                 serv_printf("X-Citadel-Room: %s", ChrPtr(WCC->CurRoom.name));
1144                                         }
1145                                 }
1146                                 post_mime_to_server();
1147                                 if (saving_to_drafts) {
1148                                         AppendImportantMessage(_("Message has been saved to Drafts.\n"), -1);
1149                                         gotoroom(WCC->CurRoom.name);
1150                                         fixview();
1151                                         readloop(readnew, eUseDefault);
1152                                         FreeStrBuf(&Buf);
1153                                         return;
1154                                 } else if (  (havebstr("recp"))
1155                                              || (havebstr("cc"  ))
1156                                              || (havebstr("bcc" ))
1157                                         ) {
1158                                         AppendImportantMessage(_("Message has been sent.\n"), -1);
1159                                 }
1160                                 else {
1161                                         AppendImportantMessage(_("Message has been posted.\n"), -1);
1162                                 }
1163                                 dont_post = lbstr("postseq");
1164                         } else {
1165                                 syslog(LOG_DEBUG, "%s:%d: server post error: %s", __FILE__, __LINE__, ChrPtr(Buf) + 4);
1166                                 AppendImportantMessage(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
1167                                 display_enter();
1168                                 if (saving_to_drafts) gotoroom(WCC->CurRoom.name);
1169                                 FreeStrBuf(&Recp);
1170                                 FreeStrBuf(&Buf);
1171                                 FreeStrBuf(&Cc);
1172                                 FreeStrBuf(&Bcc);
1173                                 return;
1174                         }
1175                 }
1176                 FreeStrBuf(&Recp);
1177                 FreeStrBuf(&Buf);
1178                 FreeStrBuf(&Cc);
1179                 FreeStrBuf(&Bcc);
1180         }
1181
1182         DeleteHash(&WCC->attachments);
1183
1184         /*
1185          *  We may have been supplied with instructions regarding the location
1186          *  to which we must return after posting.  If found, go there.
1187          */
1188         if (havebstr("return_to")) {
1189                 http_redirect(bstr("return_to"));
1190         }
1191         /*
1192          *  If we were editing a page in a wiki room, go to that page now.
1193          */
1194         else if (havebstr("page")) {
1195                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("page"));
1196                 http_redirect(buf);
1197         }
1198         /*
1199          *  Otherwise, just go to the "read messages" loop.
1200          */
1201         else {
1202                 fixview();
1203                 readloop(readnew, eUseDefault);
1204         }
1205 }
1206
1207
1208 /*
1209  * Client is uploading an attachment
1210  */
1211 void upload_attachment(void) {
1212         wcsession *WCC = WC;
1213         const char *pch;
1214         int n;
1215         const char *newn;
1216         long newnlen;
1217         void *v;
1218         wc_mime_attachment *att;
1219         const StrBuf *Tmpl = sbstr("template");
1220         const StrBuf *MimeType = NULL;
1221         const StrBuf *UID;
1222
1223         begin_burst();
1224         syslog(LOG_DEBUG, "upload_attachment()\n");
1225         if (!Tmpl) wc_printf("upload_attachment()<br>\n");
1226
1227         if (WCC->upload_length <= 0) {
1228                 syslog(LOG_DEBUG, "ERROR no attachment was uploaded\n");
1229                 if (Tmpl)
1230                 {
1231                         putlbstr("UPLOAD_ERROR", 1);
1232                         MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
1233                 }
1234                 else      wc_printf("ERROR no attachment was uploaded<br>\n");
1235                 http_transmit_thing(ChrPtr(MimeType), 0);
1236
1237                 return;
1238         }
1239
1240         syslog(LOG_DEBUG, "Client is uploading %d bytes\n", WCC->upload_length);
1241         if (Tmpl) putlbstr("UPLOAD_LENGTH", WCC->upload_length);
1242         else wc_printf("Client is uploading %d bytes<br>\n", WCC->upload_length);
1243
1244         att = (wc_mime_attachment*)malloc(sizeof(wc_mime_attachment));
1245         memset(att, 0, sizeof(wc_mime_attachment ));
1246         att->length = WCC->upload_length;
1247         att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1248         att->FileName = NewStrBufDup(WCC->upload_filename);
1249         UID = sbstr("qquuid");
1250         if (UID)
1251                 att->PartNum = NewStrBufDup(UID);
1252
1253         if (WCC->attachments == NULL) {
1254                 WCC->attachments = NewHash(1, Flathash);
1255         }
1256
1257         /* And add it to the list. */
1258         n = 0;
1259         if ((GetCount(WCC->attachments) > 0) && 
1260             GetHashAt(WCC->attachments, 
1261                       GetCount(WCC->attachments) -1, 
1262                       &newnlen, &newn, &v))
1263             n = *((int*) newn) + 1;
1264         Put(WCC->attachments, IKEY(n), att, DestroyMime);
1265
1266         /*
1267          * Mozilla sends a simple filename, which is what we want,
1268          * but Satan's Browser sends an entire pathname.  Reduce
1269          * the path to just a filename if we need to.
1270          */
1271         pch = strrchr(ChrPtr(att->FileName), '/');
1272         if (pch != NULL) {
1273                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1274         }
1275         pch = strrchr(ChrPtr(att->FileName), '\\');
1276         if (pch != NULL) {
1277                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1278         }
1279
1280         /*
1281          * Transfer control of this memory from the upload struct
1282          * to the attachment struct.
1283          */
1284         att->Data = WCC->upload;
1285         WCC->upload = NULL;
1286         WCC->upload_length = 0;
1287         
1288         if (Tmpl) MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
1289         http_transmit_thing(ChrPtr(MimeType), 0);
1290 }
1291
1292
1293 /*
1294  * Remove an attachment from the message currently being composed.
1295  *
1296  * Currently we identify the attachment to be removed by its filename.
1297  * There is probably a better way to do this.
1298  */
1299 void remove_attachment(void) {
1300         wcsession *WCC = WC;
1301         wc_mime_attachment *att;
1302         void *vAtt;
1303         StrBuf *WhichAttachment;
1304         HashPos *at;
1305         long len;
1306         int found=0;
1307         const char *key;
1308
1309         WhichAttachment = NewStrBufDup(sbstr("which_attachment"));
1310         if (ChrPtr(WhichAttachment)[0] == '/')
1311                 StrBufCutLeft(WhichAttachment, 1);
1312         StrBufUnescape(WhichAttachment, 0);
1313         at = GetNewHashPos(WCC->attachments, 0);
1314         do {
1315                 vAtt = NULL;
1316                 GetHashPos(WCC->attachments, at, &len, &key, &vAtt);
1317
1318                 att = (wc_mime_attachment*) vAtt;
1319                 if ((att != NULL) &&
1320                     (
1321                             !strcmp(ChrPtr(WhichAttachment), ChrPtr(att->FileName)) ||
1322                     ((att->PartNum != NULL) &&
1323                      !strcmp(ChrPtr(WhichAttachment), ChrPtr(att->PartNum)))
1324                             ))
1325                 {
1326                         DeleteEntryFromHash(WCC->attachments, at);
1327                         found=1;
1328                         break;
1329                 }
1330         }
1331         while (NextHashPos(WCC->attachments, at));
1332
1333         FreeStrBuf(&WhichAttachment);
1334         wc_printf("remove_attachment(%d) completed\n", found);
1335 }
1336
1337
1338 const char *ReplyToModeStrings [3] = {
1339         "reply",
1340         "replyall",
1341         "forward"
1342 };
1343 typedef enum _eReplyToNodes {
1344         eReply,
1345         eReplyAll,
1346         eForward
1347 }eReplyToNodes;
1348         
1349 /*
1350  * display the message entry screen
1351  */
1352 void display_enter(void)
1353 {
1354         const char *ReplyingModeStr;
1355         eReplyToNodes ReplyMode = eReply;
1356         StrBuf *Line;
1357         long Result;
1358         int rc;
1359         const StrBuf *display_name = NULL;
1360         int recipient_required = 0;
1361         int subject_required = 0;
1362         int is_anonymous = 0;
1363         wcsession *WCC = WC;
1364         int i = 0;
1365         long replying_to;
1366
1367         int prefer_md;
1368
1369         get_pref_yesno("markdown", &prefer_md, 0);
1370
1371         if (havebstr("force_room")) {
1372                 gotoroom(sbstr("force_room"));
1373         }
1374
1375         display_name = sbstr("display_name");
1376         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1377                 display_name = NULL;
1378                 is_anonymous = 1;
1379         }
1380
1381         /*
1382          * First, do we have permission to enter messages in this room at all?
1383          */
1384         Line = NewStrBuf();
1385         serv_puts("ENT0 0");
1386         StrBuf_ServGetln(Line);
1387         rc = GetServerStatusMsg(Line, &Result, 0, 2);
1388
1389         if (Result == 570) {            /* 570 means that we need a recipient here */
1390                 recipient_required = 1;
1391         }
1392         else if (rc != 2) {             /* Any other error means that we cannot continue */
1393                 rc = GetServerStatusMsg(Line, &Result, 0, 2);
1394                 fixview();
1395                 readloop(readnew, eUseDefault);
1396                 FreeStrBuf(&Line);
1397                 return;
1398         }
1399
1400         /* Is the server strongly recommending that the user enter a message subject? */
1401         if (StrLength(Line) > 4) {
1402                 subject_required = extract_int(ChrPtr(Line) + 4, 1);
1403         }
1404
1405         /*
1406          * Are we perhaps in an address book view?  If so, then an "enter
1407          * message" command really means "add new entry."
1408          */
1409         if (WCC->CurRoom.defview == VIEW_ADDRESSBOOK) {
1410                 do_edit_vcard(-1, "", NULL, NULL, "",  ChrPtr(WCC->CurRoom.name));
1411                 FreeStrBuf(&Line);
1412                 return;
1413         }
1414
1415         /*
1416          * Are we perhaps in a calendar room?  If so, then an "enter
1417          * message" command really means "add new calendar item."
1418          */
1419         if (WCC->CurRoom.defview == VIEW_CALENDAR) {
1420                 display_edit_event();
1421                 FreeStrBuf(&Line);
1422                 return;
1423         }
1424
1425         /*
1426          * Are we perhaps in a tasks view?  If so, then an "enter
1427          * message" command really means "add new task."
1428          */
1429         if (WCC->CurRoom.defview == VIEW_TASKS) {
1430                 display_edit_task();
1431                 FreeStrBuf(&Line);
1432                 return;
1433         }
1434
1435
1436         ReplyingModeStr = bstr("replying_mode");
1437         if (ReplyingModeStr != NULL) for (i = 0; i < 3; i++) {
1438                         if (strcmp(ReplyingModeStr, ReplyToModeStrings[i]) == 0) {
1439                                 ReplyMode = (eReplyToNodes) i;
1440                                 break;
1441                         }
1442                 }
1443                 
1444
1445         /*
1446          * If the "replying_to" variable is set, it refers to a message
1447          * number from which we must extract some header fields...
1448          */
1449         replying_to = lbstr("replying_to");
1450         if (replying_to > 0) {
1451                 long len;
1452                 StrBuf *wefw = NULL;
1453                 StrBuf *msgn = NULL;
1454                 StrBuf *from = NULL;
1455                 StrBuf *node = NULL;
1456                 StrBuf *rfca = NULL;
1457                 StrBuf *rcpt = NULL;
1458                 StrBuf *cccc = NULL;
1459                 StrBuf *replyto = NULL;
1460                 StrBuf *nvto = NULL;
1461                 serv_printf("MSG0 %ld|1", replying_to); 
1462
1463                 StrBuf_ServGetln(Line);
1464                 if (GetServerStatusMsg(Line, NULL, 0, 0) == 1)
1465                         while (len = StrBuf_ServGetln(Line),
1466                                (len >= 0) && 
1467                                ((len != 3)  ||
1468                                 strcmp(ChrPtr(Line), "000")))
1469                         {
1470                                 eMessageField which;
1471                                 if ((StrLength(Line) > 4) && 
1472                                     (ChrPtr(Line)[4] == '=') &&
1473                                     GetFieldFromMnemonic(&which, ChrPtr(Line)))
1474                                         switch (which) {
1475                                         case eMsgSubject: {
1476                                                 StrBuf *subj = NewStrBuf();
1477                                                 StrBuf *FlatSubject;
1478
1479                                                 if (ReplyMode == eForward) {
1480                                                         if (strncasecmp(ChrPtr(Line) + 5, "Fw:", 3)) {
1481                                                                 StrBufAppendBufPlain(subj, HKEY("Fw: "), 0);
1482                                                         }
1483                                                 }
1484                                                 else {
1485                                                         if (strncasecmp(ChrPtr(Line) + 5, "Re:", 3)) {
1486                                                                 StrBufAppendBufPlain(subj, HKEY("Re: "), 0);
1487                                                         }
1488                                                 }
1489                                                 StrBufAppendBufPlain(subj, 
1490                                                                      ChrPtr(Line) + 5, 
1491                                                                      StrLength(Line) - 5, 0);
1492                                                 FlatSubject = NewStrBufPlain(NULL, StrLength(subj));
1493                                                 StrBuf_RFC822_to_Utf8(FlatSubject, subj, NULL, NULL);
1494
1495                                                 PutBstr(HKEY("subject"), FlatSubject);
1496                                         }
1497                                                 break;
1498
1499                                         case eWeferences:
1500                                         {
1501                                                 int rrtok;
1502                                                 int rrlen;
1503
1504                                                 wefw = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1505                                         
1506                                                 /* Trim down excessively long lists of thread references.  We eliminate the
1507                                                  * second one in the list so that the thread root remains intact.
1508                                                  */
1509                                                 rrtok = num_tokens(ChrPtr(wefw), '|');
1510                                                 rrlen = StrLength(wefw);
1511                                                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
1512                                                         StrBufRemove_token(wefw, 1, '|');
1513                                                 }
1514                                                 break;
1515                                         }
1516
1517                                         case emessageId:
1518                                                 msgn = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1519                                                 break;
1520
1521                                         case eAuthor: {
1522                                                 StrBuf *FlatFrom;
1523                                                 from = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1524                                                 FlatFrom = NewStrBufPlain(NULL, StrLength(from));
1525                                                 StrBuf_RFC822_to_Utf8(FlatFrom, from, NULL, NULL);
1526                                                 FreeStrBuf(&from);
1527                                                 from = FlatFrom;
1528                                                 for (i=0; i<StrLength(from); ++i) {
1529                                                         if (ChrPtr(from)[i] == ',')
1530                                                                 StrBufPeek(from, NULL, i, ' ');
1531                                                 }
1532                                                 break;
1533                                         }
1534                                 
1535                                         case eRecipient:
1536                                                 rcpt = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1537                                                 break;
1538                         
1539                                 
1540                                         case eCarbonCopY:
1541                                                 cccc = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1542                                                 break;
1543
1544                                 
1545                                         case eNodeName:
1546                                                 node = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1547                                                 break;
1548                                         case eReplyTo:
1549                                                 replyto = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1550                                                 break;
1551                                         case erFc822Addr: {
1552                                                 StrBuf *FlatRFCA;
1553                                                 rfca = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1554                                                 FlatRFCA = NewStrBufPlain(NULL, StrLength(rfca));
1555                                                 StrBuf_RFC822_to_Utf8(FlatRFCA, rfca, NULL, NULL);
1556                                                 FreeStrBuf(&rfca);
1557                                                 rfca = FlatRFCA;
1558                                                 break;
1559                                         }
1560                                         case eenVelopeTo:
1561                                                 nvto = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1562                                                 putbstr("nvto", nvto);
1563                                                 break;
1564                                         case eXclusivID:
1565                                         case eHumanNode:
1566                                         case eJournal:
1567                                         case eListID:
1568                                         case eMesageText:
1569                                         case eOriginalRoom:
1570                                         case eMessagePath:
1571                                         case eSpecialField:
1572                                         case eTimestamp:
1573                                         case eHeaderOnly:
1574                                         case eFormatType:
1575                                         case eMessagePart:
1576                                         case eSubFolder:
1577                                         case ePevious:
1578                                         case eLastHeader:
1579                                                 break;
1580
1581                                         }
1582                         }
1583
1584
1585                 if (StrLength(wefw) + StrLength(msgn) > 0) {
1586                         StrBuf *refs = NewStrBuf();
1587                         if (StrLength(wefw) > 0) {
1588                                 StrBufAppendBuf(refs, wefw, 0);
1589                         }
1590                         if ( (StrLength(wefw) > 0) && 
1591                              (StrLength(msgn) > 0) ) 
1592                         {
1593                                 StrBufAppendBufPlain(refs, HKEY("|"), 0);
1594                         }
1595                         if (StrLength(msgn) > 0) {
1596                                 StrBufAppendBuf(refs, msgn, 0);
1597                         }
1598                         PutBstr(HKEY("references"), refs);
1599                 }
1600
1601                 /*
1602                  * If this is a Reply or a ReplyAll, copy the sender's email into the To: field
1603                  */
1604                 if ((ReplyMode == eReply) || (ReplyMode == eReplyAll))
1605                 {
1606                         StrBuf *to_rcpt;
1607                         if ((StrLength(replyto) > 0) && (ReplyMode == eReplyAll)) {
1608                                 to_rcpt = NewStrBuf();
1609                                 StrBufAppendBuf(to_rcpt, replyto, 0);
1610                         }
1611                         else if (StrLength(rfca) > 0) {
1612                                 to_rcpt = NewStrBuf();
1613                                 StrBufAppendBuf(to_rcpt, from, 0);
1614                                 StrBufAppendBufPlain(to_rcpt, HKEY(" <"), 0);
1615                                 StrBufAppendBuf(to_rcpt, rfca, 0);
1616                                 StrBufAppendBufPlain(to_rcpt, HKEY(">"), 0);
1617                         }
1618                         else {
1619                                 to_rcpt =  from;
1620                                 from = NULL;
1621                                 if (    (StrLength(node) > 0)
1622                                         && (strcasecmp(ChrPtr(node), ChrPtr(WCC->serv_info->serv_nodename)))
1623                                 ) {
1624                                         StrBufAppendBufPlain(to_rcpt, HKEY(" @ "), 0);
1625                                         StrBufAppendBuf(to_rcpt, node, 0);
1626                                 }
1627                         }
1628                         PutBstr(HKEY("recp"), to_rcpt);
1629                 }
1630
1631                 /*
1632                  * Only if this is a ReplyAll, copy all recipients into the Cc: field
1633                  */
1634                 if (ReplyMode == eReplyAll)
1635                 {
1636                         StrBuf *cc_rcpt = rcpt;
1637                         rcpt = NULL;
1638                         if ((StrLength(cccc) > 0) && (StrLength(replyto) == 0))
1639                         {
1640                                 if (cc_rcpt != NULL)  {
1641                                         StrBufAppendPrintf(cc_rcpt, ", ");
1642                                         StrBufAppendBuf(cc_rcpt, cccc, 0);
1643                                 } else {
1644                                         cc_rcpt = cccc;
1645                                         cccc = NULL;
1646                                 }
1647                         }
1648                         if (cc_rcpt != NULL)
1649                                 PutBstr(HKEY("cc"), cc_rcpt);
1650                 }
1651                 FreeStrBuf(&wefw);
1652                 FreeStrBuf(&msgn);
1653                 FreeStrBuf(&from);
1654                 FreeStrBuf(&node);
1655                 FreeStrBuf(&rfca);
1656                 FreeStrBuf(&rcpt);
1657                 FreeStrBuf(&cccc);
1658         }
1659         FreeStrBuf(&Line);
1660         /*
1661          * Otherwise proceed normally.
1662          * Do a custom room banner with no navbar...
1663          */
1664
1665         if (recipient_required) {
1666                 const StrBuf *Recp = NULL; 
1667                 const StrBuf *Cc = NULL;
1668                 const StrBuf *Bcc = NULL;
1669                 StrBuf *wikipage = NULL;
1670                 StrBuf *CmdBuf = NULL;
1671                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1672                 
1673                 Recp = sbstr("recp");
1674                 Cc = sbstr("cc");
1675                 Bcc = sbstr("bcc");
1676                 wikipage = NewStrBufDup(sbstr("page"));
1677                 str_wiki_index(wikipage);
1678                 
1679                 CmdBuf = NewStrBufPlain(NULL, 
1680                                         sizeof (CMD) + 
1681                                         StrLength(Recp) + 
1682                                         StrLength(display_name) +
1683                                         StrLength(Cc) +
1684                                         StrLength(Bcc) + 
1685                                         StrLength(wikipage));
1686
1687                 StrBufPrintf(CmdBuf, 
1688                              CMD,
1689                              ChrPtr(Recp), 
1690                              is_anonymous,
1691                              ChrPtr(display_name),
1692                              ChrPtr(Cc), 
1693                              ChrPtr(Bcc), 
1694                              ChrPtr(wikipage)
1695                 );
1696                 serv_puts(ChrPtr(CmdBuf));
1697                 StrBuf_ServGetln(CmdBuf);
1698                 free(wikipage);
1699
1700                 rc = GetServerStatusMsg(CmdBuf, &Result, 0, 0);
1701
1702                 if (    (Result == 570)         /* invalid or missing recipient(s) */
1703                         || (Result == 550)      /* higher access required to send Internet mail */
1704                 ) {
1705                         /* These errors will have been displayed and are excusable */
1706                 }
1707                 else if (rc != 2) {     /* Any other error means that we cannot continue */
1708                         AppendImportantMessage(ChrPtr(CmdBuf) + 4, StrLength(CmdBuf) - 4);
1709                         FreeStrBuf(&CmdBuf);
1710                         fixview();
1711                         readloop(readnew, eUseDefault);
1712                         return;
1713                 }
1714                 FreeStrBuf(&CmdBuf);
1715         }
1716         if (recipient_required)
1717                 PutBstr(HKEY("__RCPTREQUIRED"), NewStrBufPlain(HKEY("1")));
1718         if (recipient_required || subject_required)
1719                 PutBstr(HKEY("__SUBJREQUIRED"), NewStrBufPlain(HKEY("1")));
1720
1721         begin_burst();
1722         output_headers(1, 0, 0, 0, 1, 0);
1723         if ((WCC->CurRoom.defview == VIEW_WIKIMD) || prefer_md)
1724                 DoTemplate(HKEY("edit_markdown_epic"), NULL, &NoCtx);
1725         else
1726                 DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1727         end_burst();
1728
1729         return;
1730 }
1731
1732 /*
1733  * delete a message
1734  */
1735 void delete_msg(void)
1736 {
1737         long msgid;
1738         StrBuf *Line;
1739         
1740         msgid = lbstr("msgid");
1741         Line = NewStrBuf();
1742         if ((WC->CurRoom.RAFlags & UA_ISTRASH) != 0) {  /* Delete from Trash is a real delete */
1743                 serv_printf("DELE %ld", msgid); 
1744         }
1745         else {                  /* Otherwise move it to Trash */
1746                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1747         }
1748
1749         StrBuf_ServGetln(Line);
1750         GetServerStatusMsg(Line, NULL, 1, 0);
1751
1752         fixview();
1753
1754         readloop(readnew, eUseDefault);
1755 }
1756
1757
1758 /*
1759  * move a message to another room
1760  */
1761 void move_msg(void)
1762 {
1763         long msgid;
1764
1765         msgid = lbstr("msgid");
1766
1767         if (havebstr("move_button")) {
1768                 StrBuf *Line;
1769                 serv_printf("MOVE %ld|%s", msgid, bstr("target_room"));
1770                 Line = NewStrBuf();
1771                 StrBuf_ServGetln(Line);
1772                 GetServerStatusMsg(Line, NULL, 1, 0);
1773                 FreeStrBuf(&Line);
1774         } else {
1775                 AppendImportantMessage(_("The message was not moved."), -1);
1776         }
1777
1778         fixview();
1779         readloop(readnew, eUseDefault);
1780 }
1781
1782
1783
1784 /*
1785  * Generic function to output an arbitrary MIME attachment from
1786  * message being composed
1787  *
1788  * partnum              The MIME part to be output
1789  * filename             Fake filename to give
1790  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1791  */
1792 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1793 {
1794         void *vPart;
1795         StrBuf *content_type;
1796         wc_mime_attachment *part;
1797         int i;
1798
1799         i = StrToi(partnum);
1800         if (GetHash(WC->attachments, IKEY(i), &vPart) &&
1801             (vPart != NULL)) {
1802                 part = (wc_mime_attachment*) vPart;
1803                 if (force_download) {
1804                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1805                 }
1806                 else {
1807                         content_type = NewStrBufDup(part->ContentType);
1808                 }
1809                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1810                 http_transmit_thing(ChrPtr(content_type), 0);
1811         } else {
1812                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1813                 output_headers(0, 0, 0, 0, 0, 0);
1814                 hprintf("Content-Type: text/plain\r\n");
1815                 begin_burst();
1816                 wc_printf(_("An error occurred while retrieving this part: %s/%s\n"), 
1817                         ChrPtr(partnum), ChrPtr(filename));
1818                 end_burst();
1819         }
1820         FreeStrBuf(&content_type);
1821 }
1822
1823
1824 /*
1825  * Generic function to output an arbitrary MIME part from an arbitrary
1826  * message number on the server.
1827  *
1828  * msgnum               Number of the item on the citadel server
1829  * partnum              The MIME part to be output
1830  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1831  */
1832 void mimepart(int force_download)
1833 {
1834         int detect_mime = 0;
1835         long msgnum;
1836         long ErrorDetail;
1837         StrBuf *att;
1838         wcsession *WCC = WC;
1839         StrBuf *Buf;
1840         off_t bytes;
1841         StrBuf *ContentType = NewStrBufPlain(HKEY("application/octet-stream"));
1842         const char *CT;
1843
1844         att = Buf = NewStrBuf();
1845         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
1846         StrBufExtract_token(att, WCC->Hdr->HR.ReqLine, 1, '/');
1847
1848         serv_printf("OPNA %ld|%s", msgnum, ChrPtr(att));
1849         StrBuf_ServGetln(Buf);
1850         if (GetServerStatus(Buf, &ErrorDetail) == 2) {
1851                 StrBufCutLeft(Buf, 4);
1852                 bytes = StrBufExtract_long(Buf, 0, '|');
1853                 StrBufExtract_token(ContentType, Buf, 3, '|');
1854                 CheckGZipCompressionAllowed (SKEY(ContentType));
1855                 if (force_download)
1856                 {
1857                         FlushStrBuf(ContentType);
1858                         detect_mime = 0;
1859                 }
1860                 else
1861                 {
1862                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream"))
1863                         {
1864                                 StrBufExtract_token(Buf, WCC->Hdr->HR.ReqLine, 2, '/');
1865                                 CT = GuessMimeByFilename(SKEY(Buf));
1866                                 StrBufPlain(ContentType, CT, -1);
1867                         }
1868                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream"))
1869                         {
1870                                 detect_mime = 1;
1871                         }
1872                 }
1873                 serv_read_binary_to_http(ContentType, bytes, 0, detect_mime);
1874
1875                 serv_read_binary(WCC->WBuf, bytes, Buf);
1876                 serv_puts("CLOS");
1877                 StrBuf_ServGetln(Buf);
1878                 CT = ChrPtr(ContentType);
1879         } else {
1880                 StrBufCutLeft(Buf, 4);
1881                 switch (ErrorDetail) {
1882                 default:
1883                 case ERROR + MESSAGE_NOT_FOUND:
1884                         hprintf("HTTP/1.1 404 %s\n", ChrPtr(Buf));
1885                         break;
1886                 case ERROR + NOT_LOGGED_IN:
1887                         hprintf("HTTP/1.1 401 %s\n", ChrPtr(Buf));
1888                         break;
1889
1890                 case ERROR + HIGHER_ACCESS_REQUIRED:
1891                         hprintf("HTTP/1.1 403 %s\n", ChrPtr(Buf));
1892                         break;
1893                 case ERROR + INTERNAL_ERROR:
1894                 case ERROR + TOO_BIG:
1895                         hprintf("HTTP/1.1 500 %s\n", ChrPtr(Buf));
1896                         break;
1897                 }
1898
1899                 hprintf("Pragma: no-cache\r\n"
1900                         "Cache-Control: no-store\r\n"
1901                         "Expires: -1\r\n"
1902                 );
1903
1904                 hprintf("Content-Type: text/plain\r\n");
1905                 begin_burst();
1906                 wc_printf(_("An error occurred while retrieving this part: %s\n"), 
1907                         ChrPtr(Buf));
1908                 end_burst();
1909         }
1910         FreeStrBuf(&ContentType);
1911         FreeStrBuf(&Buf);
1912 }
1913
1914
1915 /*
1916  * Read any MIME part of a message, from the server, into memory.
1917  */
1918 StrBuf *load_mimepart(long msgnum, char *partnum)
1919 {
1920         off_t bytes;
1921         StrBuf *Buf;
1922         
1923         Buf = NewStrBuf();
1924         serv_printf("DLAT %ld|%s", msgnum, partnum);
1925         StrBuf_ServGetln(Buf);
1926         if (GetServerStatus(Buf, NULL) == 6) {
1927                 StrBufCutLeft(Buf, 4);
1928                 bytes = StrBufExtract_long(Buf, 0, '|');
1929                 FreeStrBuf(&Buf);
1930                 Buf = NewStrBuf();
1931                 StrBuf_ServGetBLOBBuffered(Buf, bytes);
1932                 return(Buf);
1933         }
1934         else {
1935                 FreeStrBuf(&Buf);
1936                 return(NULL);
1937         }
1938 }
1939
1940 /*
1941  * Read any MIME part of a message, from the server, into memory.
1942  */
1943 void MimeLoadData(wc_mime_attachment *Mime)
1944 {
1945         StrBuf *Buf;
1946         const char *Ptr;
1947         off_t bytes;
1948         /* TODO: is there a chance the content type is different from the one we know? */
1949
1950         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1951         Buf = NewStrBuf();
1952         StrBuf_ServGetln(Buf);
1953         if (GetServerStatus(Buf, NULL) == 6) {
1954                 Ptr = &(ChrPtr(Buf)[4]);
1955                 bytes = StrBufExtractNext_long(Buf, &Ptr, '|');
1956                 StrBufSkip_NTokenS(Buf, &Ptr, '|', 3);  /* filename, cbtype, mimetype */
1957                 if (Mime->Charset == NULL) Mime->Charset = NewStrBuf();
1958                 StrBufExtract_NextToken(Mime->Charset, Buf, &Ptr, '|');
1959                 
1960                 if (Mime->Data == NULL)
1961                         Mime->Data = NewStrBufPlain(NULL, bytes);
1962                 StrBuf_ServGetBLOBBuffered(Mime->Data, bytes);
1963         }
1964         else {
1965                 FlushStrBuf(Mime->Data);
1966                 /* TODO XImportant message */
1967         }
1968         FreeStrBuf(&Buf);
1969 }
1970
1971
1972 void view_mimepart(void) {
1973         mimepart(0);
1974 }
1975
1976 void download_mimepart(void) {
1977         mimepart(1);
1978 }
1979
1980 void view_postpart(void) {
1981         StrBuf *filename = NewStrBuf();
1982         StrBuf *partnum = NewStrBuf();
1983
1984         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1985         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1986
1987         postpart(partnum, filename, 0);
1988
1989         FreeStrBuf(&filename);
1990         FreeStrBuf(&partnum);
1991 }
1992
1993 void download_postpart(void) {
1994         StrBuf *filename = NewStrBuf();
1995         StrBuf *partnum = NewStrBuf();
1996
1997         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1998         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1999
2000         postpart(partnum, filename, 1);
2001
2002         FreeStrBuf(&filename);
2003         FreeStrBuf(&partnum);
2004 }
2005
2006
2007
2008 void show_num_attachments(void) {
2009         wc_printf("%d", GetCount(WC->attachments));
2010 }
2011
2012
2013 void h_readnew(void) { readloop(readnew, eUseDefault);}
2014 void h_readold(void) { readloop(readold, eUseDefault);}
2015 void h_readfwd(void) { readloop(readfwd, eUseDefault);}
2016 void h_headers(void) { readloop(headers, eUseDefault);}
2017 void h_do_search(void) { readloop(do_search, eUseDefault);}
2018 void h_readgt(void) { readloop(readgt, eUseDefault);}
2019 void h_readlt(void) { readloop(readlt, eUseDefault);}
2020
2021
2022
2023 /* Output message list in JSON format */
2024 void jsonMessageList(void) {
2025         StrBuf *View = NewStrBuf();
2026         const StrBuf *room = sbstr("room");
2027         long oper = (havebstr("query")) ? do_search : readnew;
2028         StrBufPrintf(View, "%d", VIEW_JSON_LIST);
2029         putbstr("view", View);; 
2030         gotoroom(room);
2031         readloop(oper, eUseDefault);
2032 }
2033
2034 void FreeReadLoopHandlerSet(void *v) {
2035         RoomRenderer *Handler = (RoomRenderer *) v;
2036         FreeStrBuf(&Handler->FetchMessageList);
2037         if (Handler->MessageFieldList != NULL) {
2038                 free(Handler->MessageFieldList);
2039         }
2040         free(Handler);
2041 }
2042
2043 void RegisterReadLoopHandlerset(
2044         int RoomType,
2045         GetParamsGetServerCall_func GetParamsGetServerCall,
2046         PrintViewHeader_func PrintPageHeader,
2047         PrintViewHeader_func PrintViewHeader,
2048         load_msg_ptrs_detailheaders LH,
2049         LoadMsgFromServer_func LoadMsgFromServer,
2050         RenderView_or_Tail_func RenderView_or_Tail,
2051         View_Cleanup_func ViewCleanup,
2052         const char **browseListFields
2053         )
2054 {
2055         long count = 0;
2056         long i = 0;
2057         RoomRenderer *Handler;
2058
2059         Handler = (RoomRenderer*) malloc(sizeof(RoomRenderer));
2060
2061         Handler->RoomType = RoomType;
2062         Handler->GetParamsGetServerCall = GetParamsGetServerCall;
2063         Handler->PrintPageHeader = PrintPageHeader;
2064         Handler->PrintViewHeader = PrintViewHeader;
2065         Handler->LoadMsgFromServer = LoadMsgFromServer;
2066         Handler->RenderView_or_Tail = RenderView_or_Tail;
2067         Handler->ViewCleanup = ViewCleanup;
2068         Handler->LHParse = LH;
2069
2070         if (browseListFields != NULL) {
2071                 while (browseListFields[count] != NULL) {
2072                         count ++;
2073                 }
2074                 Handler->HeaderCount = count;
2075                 Handler->MessageFieldList = (eMessageField*) malloc(sizeof(eMessageField) * count);
2076                 Handler->FetchMessageList = NewStrBufPlain(NULL, 5 * count + 4 + 5);
2077                 StrBufPlain(Handler->FetchMessageList, HKEY("time\n"));
2078                 for (i = 0; i < count; i++) {
2079                         if (!GetFieldFromMnemonic(&Handler->MessageFieldList[i], browseListFields[i])) {
2080                                 fprintf(stderr, "Unknown message header: %s\n", browseListFields[i]);
2081                                 exit(1);
2082                         }
2083                         StrBufAppendBufPlain(Handler->FetchMessageList, browseListFields[i], 4, 0);
2084                         StrBufAppendBufPlain(Handler->FetchMessageList, HKEY("\n"), 0);
2085                 }
2086                 StrBufAppendBufPlain(Handler->FetchMessageList, HKEY("000"), 0);
2087         }
2088         else {
2089                 Handler->FetchMessageList = NULL;
2090                 Handler->MessageFieldList = NULL;
2091         }
2092
2093         Put(ReadLoopHandler, IKEY(RoomType), Handler, FreeReadLoopHandlerSet);
2094 }
2095
2096 void 
2097 InitModule_MSG
2098 (void)
2099 {
2100         RegisterPreference("use_sig",
2101                            _("Attach signature to email messages?"), 
2102                            PRF_YESNO, 
2103                            NULL);
2104         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
2105         RegisterPreference("default_header_charset",
2106                            _("Default character set for email headers:"), 
2107                            PRF_STRING, 
2108                            NULL);
2109         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
2110         RegisterPreference("defaultname", 
2111                            _("Preferred display name for email messages"), 
2112                            PRF_STRING, 
2113                            NULL);
2114         RegisterPreference("defaulthandle", 
2115                            _("Preferred display name for bulletin board posts"), 
2116                            PRF_STRING, 
2117                            NULL);
2118         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
2119         RegisterPreference("markdown",_("Prefer markdown editing"), PRF_YESNO, NULL);
2120
2121
2122         WebcitAddUrlHandler(HKEY("readnew"), "", 0, h_readnew, ANONYMOUS|NEED_URL);
2123         WebcitAddUrlHandler(HKEY("readold"), "", 0, h_readold, ANONYMOUS|NEED_URL);
2124         WebcitAddUrlHandler(HKEY("readfwd"), "", 0, h_readfwd, ANONYMOUS|NEED_URL);
2125         WebcitAddUrlHandler(HKEY("headers"), "", 0, h_headers, NEED_URL);
2126         WebcitAddUrlHandler(HKEY("readgt"), "", 0, h_readgt, ANONYMOUS|NEED_URL);
2127         WebcitAddUrlHandler(HKEY("readlt"), "", 0, h_readlt, ANONYMOUS|NEED_URL);
2128         WebcitAddUrlHandler(HKEY("do_search"), "", 0, h_do_search, 0);
2129         WebcitAddUrlHandler(HKEY("display_enter"), "", 0, display_enter, 0);
2130         WebcitAddUrlHandler(HKEY("post"), "", 0, post_message, PROHIBIT_STARTPAGE);
2131         WebcitAddUrlHandler(HKEY("move_msg"), "", 0, move_msg, PROHIBIT_STARTPAGE);
2132         WebcitAddUrlHandler(HKEY("delete_msg"), "", 0, delete_msg, PROHIBIT_STARTPAGE);
2133         WebcitAddUrlHandler(HKEY("msg"), "", 0, embed_message, NEED_URL);
2134         WebcitAddUrlHandler(HKEY("message"), "", 0, handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
2135         WebcitAddUrlHandler(HKEY("printmsg"), "", 0, print_message, NEED_URL);
2136         WebcitAddUrlHandler(HKEY("msgheaders"), "", 0, display_headers, NEED_URL);
2137
2138         WebcitAddUrlHandler(HKEY("mimepart"), "", 0, view_mimepart, NEED_URL);
2139         WebcitAddUrlHandler(HKEY("mimepart_download"), "", 0, download_mimepart, NEED_URL);
2140         WebcitAddUrlHandler(HKEY("postpart"), "", 0, view_postpart, NEED_URL|PROHIBIT_STARTPAGE);
2141         WebcitAddUrlHandler(HKEY("postpart_download"), "", 0, download_postpart, NEED_URL|PROHIBIT_STARTPAGE);
2142         WebcitAddUrlHandler(HKEY("upload_attachment"), "", 0, upload_attachment, AJAX);
2143         WebcitAddUrlHandler(HKEY("remove_attachment"), "", 0, remove_attachment, AJAX);
2144         WebcitAddUrlHandler(HKEY("show_num_attachments"), "", 0, show_num_attachments, AJAX);
2145
2146         /* json */
2147         WebcitAddUrlHandler(HKEY("roommsgs"), "", 0, jsonMessageList,0);
2148 }
2149
2150 void
2151 SessionDetachModule_MSG
2152 (wcsession *sess)
2153 {
2154         DeleteHash(&sess->summ);
2155 }