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