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