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