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