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