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