If user clicks in the empty part of a mailbox view, display a blank pane instead...
[citadel.git] / webcit / messages.c
1 /*
2  * Functions which deal with the fetching and displaying of messages.
3  *
4  * Copyright (c) 1996-2011 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 as
8  * published by the Free Software Foundation; either version 3 of the
9  * License, or (at your option) any later version.
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  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  */
20
21 #include "webcit.h"
22 #include "webserver.h"
23 #include "groupdav.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                   SharedMessageStatus *Stat, 
534                   load_msg_ptrs_detailheaders LH)
535 {
536         wcsession *WCC = WC;
537         message_summary *Msg;
538         StrBuf *Buf, *Buf2;
539         long len;
540         int n;
541         int skipit;
542         const char *Ptr = NULL;
543
544         Stat->lowest_found = LONG_MAX;
545         Stat->highest_found = LONG_MIN;
546
547         if (WCC->summ != NULL) {
548                 DeleteHash(&WCC->summ);
549         }
550         WCC->summ = NewHash(1, Flathash);
551         
552         Buf = NewStrBuf();
553         serv_puts(servcmd);
554         StrBuf_ServGetln(Buf);
555         if (GetServerStatus(Buf, NULL) != 1) {
556                 FreeStrBuf(&Buf);
557                 return (Stat->nummsgs);
558         }
559         Buf2 = NewStrBuf();
560         while (len = StrBuf_ServGetln(Buf), 
561                ((len >= 0) &&
562                 ((len != 3) || 
563                  strcmp(ChrPtr(Buf), "000")!= 0)))
564         {
565                 if (Stat->nummsgs < Stat->maxload) {
566                         skipit = 0;
567                         Ptr = NULL;
568                         Msg = (message_summary*)malloc(sizeof(message_summary));
569                         memset(Msg, 0, sizeof(message_summary));
570
571                         Msg->msgnum = StrBufExtractNext_long(Buf, &Ptr, '|');
572                         Msg->date = StrBufExtractNext_long(Buf, &Ptr, '|');
573
574                         if (Stat->nummsgs == 0) {
575                                 if (Msg->msgnum < Stat->lowest_found) {
576                                         Stat->lowest_found = Msg->msgnum;
577                                 }
578                                 if (Msg->msgnum > Stat->highest_found) {
579                                         Stat->highest_found = Msg->msgnum;
580                                 }
581                         }
582
583                         if ((Msg->msgnum == 0) && (StrLength(Buf) < 32)) {
584                                 free(Msg);
585                                 continue;
586                         }
587
588                         /* 
589                          * as citserver probably gives us messages in forward date sorting
590                          * nummsgs should be the same order as the message date.
591                          */
592                         if (Msg->date == 0) {
593                                 Msg->date = Stat->nummsgs;
594                                 if (StrLength(Buf) < 32) 
595                                         skipit = 1;
596                         }
597                         if ((!skipit) && (LH != NULL)) {
598                                 if (!LH(Buf, &Ptr, Msg, Buf2)){
599                                         free(Msg);
600                                         continue;
601                                 }                                       
602                         }
603                         n = Msg->msgnum;
604                         Put(WCC->summ, (const char *)&n, sizeof(n), Msg, DestroyMessageSummary);
605                 }
606                 Stat->nummsgs++;
607         }
608         FreeStrBuf(&Buf2);
609         FreeStrBuf(&Buf);
610         return (Stat->nummsgs);
611 }
612
613
614
615 /**
616  * \brief sets FlagToSet for each of ScanMe that appears in MatchMSet
617  * \param ScanMe List of BasicMsgStruct to be searched it MatchSet
618  * \param MatchMSet MSet we want to flag
619  * \param FlagToSet Flag to set on each BasicMsgStruct->Flags if in MSet
620  */
621 void SetFlagsFromMSet(HashList *ScanMe, MSet *MatchMSet, int FlagToSet, int Reverse)
622 {
623         const char *HashKey;
624         long HKLen;
625         HashPos *at;
626         void *vMsg;
627         message_summary *Msg;
628
629         at = GetNewHashPos(ScanMe, 0);
630         while (GetNextHashPos(ScanMe, at, &HKLen, &HashKey, &vMsg)) {
631                 /* Are you a new message, or an old message? */
632                 Msg = (message_summary*) vMsg;
633                 if (Reverse && IsInMSetList(MatchMSet, Msg->msgnum)) {
634                         Msg->Flags = Msg->Flags | FlagToSet;
635                 }
636                 else if (!Reverse && !IsInMSetList(MatchMSet, Msg->msgnum)) {
637                         Msg->Flags = Msg->Flags | FlagToSet;
638                 }
639         }
640         DeleteHashPos(&at);
641 }
642
643
644 void load_seen_flags(void)
645 {
646         StrBuf *OldMsg;
647         wcsession *WCC = WC;
648         MSet *MatchMSet;
649
650         OldMsg = NewStrBuf();
651         serv_puts("GTSN");
652         StrBuf_ServGetln(OldMsg);
653         if (GetServerStatus(OldMsg, NULL) == 2) {
654                 StrBufCutLeft(OldMsg, 4);
655         }
656         else {
657                 FreeStrBuf(&OldMsg);
658                 return;
659         }
660
661         if (ParseMSet(&MatchMSet, OldMsg))
662         {
663                 SetFlagsFromMSet(WCC->summ, MatchMSet, MSGFLAG_READ, 0);
664         }
665         DeleteMSet(&MatchMSet);
666         FreeStrBuf(&OldMsg);
667 }
668
669 extern readloop_struct rlid[];
670
671 typedef struct _RoomRenderer{
672         int RoomType;
673
674         GetParamsGetServerCall_func GetParamsGetServerCall;
675         PrintViewHeader_func PrintViewHeader;
676         LoadMsgFromServer_func LoadMsgFromServer;
677         RenderView_or_Tail_func RenderView_or_Tail;
678         View_Cleanup_func ViewCleanup;
679         load_msg_ptrs_detailheaders LHParse;
680 } RoomRenderer;
681
682
683 /*
684  * command loop for reading messages
685  *
686  * Set oper to "readnew" or "readold" or "readfwd" or "headers" or "readgt" or "readlt" or "do_search"
687  */
688 void readloop(long oper, eCustomRoomRenderer ForceRenderer)
689 {
690         RoomRenderer *ViewMsg;
691         void *vViewMsg;
692         void *vMsg;
693         message_summary *Msg;
694         char cmd[256] = "";
695         int i, r;
696         wcsession *WCC = WC;
697         HashPos *at;
698         const char *HashKey;
699         long HKLen;
700         WCTemplputParams SubTP;
701         SharedMessageStatus Stat;
702         void *ViewSpecific;
703
704         if (havebstr("is_summary") && (1 == (ibstr("is_summary")))) {
705                 WCC->CurRoom.view = VIEW_MAILBOX;
706         }
707
708         if (havebstr("is_ajax") && (1 == (ibstr("is_ajax")))) {
709                 WCC->is_ajax = 1;
710         }
711
712         if ((oper == do_search) && (WCC->CurRoom.view == VIEW_WIKI)) {
713                 display_wiki_pagelist();
714                 return;
715         }
716
717         if (WCC->CurRoom.view == VIEW_WIKI) {
718                 http_redirect("wiki?page=home");
719                 return;
720         }
721
722         memset(&Stat, 0, sizeof(SharedMessageStatus));
723         Stat.maxload = 10000;
724         Stat.lowest_found = (-1);
725         Stat.highest_found = (-1);
726         if (ForceRenderer == eUseDefault)
727                 GetHash(ReadLoopHandler, IKEY(WCC->CurRoom.view), &vViewMsg);
728         else 
729                 GetHash(ReadLoopHandler, IKEY(ForceRenderer), &vViewMsg);
730         if (vViewMsg == NULL) {
731                 WCC->CurRoom.view = VIEW_BBS;
732                 GetHash(ReadLoopHandler, IKEY(WCC->CurRoom.view), &vViewMsg);
733         }
734         if (vViewMsg == NULL) {
735                 return;                 /* TODO: print message */
736         }
737
738         ViewMsg = (RoomRenderer*) vViewMsg;
739         if (!WCC->is_ajax) {
740                 output_headers(1, 1, 1, 0, 0, 0);
741         } else if (WCC->CurRoom.view == VIEW_MAILBOX) {
742                 jsonMessageListHdr();
743         }
744
745         if (ViewMsg->GetParamsGetServerCall != NULL) {
746                 r = ViewMsg->GetParamsGetServerCall(
747                        &Stat,
748                        &ViewSpecific,
749                        oper,
750                        cmd, sizeof(cmd)
751                 );
752         } else {
753                 r = 0;
754         }
755         switch(r)
756         {
757         case 400:
758         case 404:
759
760                 return;
761         case 300: /* the callback hook should do the work for us here, since he knows what to do. */
762                 return;
763         case 200:
764         default:
765                 break;
766         }
767         if (!IsEmptyStr(cmd))
768                 Stat.nummsgs = load_msg_ptrs(cmd, &Stat, ViewMsg->LHParse);
769
770         if (Stat.sortit) {
771                 CompareFunc SortIt;
772                 memset(&SubTP, 0, sizeof(WCTemplputParams));
773                 SubTP.Filter.ContextType = CTX_MAILSUM;
774                 SubTP.Context = NULL;
775                 SortIt =  RetrieveSort(&SubTP, NULL, 0,
776                                        HKEY("date"), Stat.defaultsortorder);
777                 if (SortIt != NULL)
778                         SortByPayload(WCC->summ, SortIt);
779         }
780         if (Stat.startmsg < 0) {
781                 Stat.startmsg =  0;
782         }
783
784         if (Stat.load_seen) load_seen_flags();
785         
786         /*
787          * Print any inforation above the message list...
788          */
789         if (ViewMsg->PrintViewHeader != NULL)
790                 ViewMsg->PrintViewHeader(&Stat, &ViewSpecific);
791
792         WCC->startmsg =  Stat.startmsg;
793         WCC->maxmsgs = Stat.maxmsgs;
794         WCC->num_displayed = 0;
795
796         /* Put some helpful data in vars for mailsummary_json */
797         {
798                 StrBuf *Foo;
799                 
800                 Foo = NewStrBuf ();
801                 StrBufPrintf(Foo, "%ld", Stat.nummsgs);
802                 PutBstr(HKEY("__READLOOP:TOTALMSGS"), NewStrBufDup(Foo));
803                 StrBufPrintf(Foo, "%ld", Stat.startmsg);
804                 PutBstr(HKEY("__READLOOP:STARTMSG"), Foo);
805         }
806
807         /*
808          * iterate over each message. if we need to load an attachment, do it here. 
809          */
810
811         if ((ViewMsg->LoadMsgFromServer != NULL) && 
812             (!IsEmptyStr(cmd)))
813         {
814                 at = GetNewHashPos(WCC->summ, 0);
815                 Stat.num_displayed = i = 0;
816                 while ( GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
817                         Msg = (message_summary*) vMsg;          
818                         if ((Msg->msgnum >= Stat.startmsg) && (Stat.num_displayed <= Stat.maxmsgs)) {
819                                 ViewMsg->LoadMsgFromServer(&Stat, 
820                                                            &ViewSpecific, 
821                                                            Msg, 
822                                                            (Msg->Flags & MSGFLAG_READ) != 0, 
823                                                            i);
824                         } 
825                         i++;
826                 }
827                 DeleteHashPos(&at);
828         }
829
830         /*
831          * Done iterating the message list. now tasks we want to do after.
832          */
833         if (ViewMsg->RenderView_or_Tail != NULL)
834                 ViewMsg->RenderView_or_Tail(&Stat, &ViewSpecific, oper);
835
836         if (ViewMsg->ViewCleanup != NULL)
837                 ViewMsg->ViewCleanup(&ViewSpecific);
838
839         WCC->startmsg = 0;
840         WCC->maxmsgs = 0;
841         if (WCC->summ != NULL) {
842                 DeleteHash(&WCC->summ);
843         }
844 }
845
846
847 /*
848  * Back end for post_message()
849  * ... this is where the actual message gets transmitted to the server.
850  */
851 void post_mime_to_server(void) {
852         wcsession *WCC = WC;
853         char top_boundary[SIZ];
854         char alt_boundary[SIZ];
855         int is_multipart = 0;
856         static int seq = 0;
857         wc_mime_attachment *att;
858         char *encoded;
859         size_t encoded_length;
860         size_t encoded_strlen;
861         char *txtmail = NULL;
862         int include_text_alt = 0;       /* Set to nonzero to include multipart/alternative text/plain */
863
864         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
865                 ChrPtr(WCC->serv_info->serv_fqdn),
866                 getpid(),
867                 ++seq
868         );
869         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
870                 ChrPtr(WCC->serv_info->serv_fqdn),
871                 getpid(),
872                 ++seq
873         );
874
875         /* RFC2045 requires this, and some clients look for it... */
876         serv_puts("MIME-Version: 1.0");
877         serv_puts("X-Mailer: " PACKAGE_STRING);
878
879         /* If there are attachments, we have to do multipart/mixed */
880         if (GetCount(WCC->attachments) > 0) {
881                 is_multipart = 1;
882         }
883
884         /* Only do multipart/alternative for mailboxes.  BBS and Wiki rooms don't need it. */
885         if (WC->CurRoom.view == VIEW_MAILBOX) {
886                 include_text_alt = 1;
887         }
888
889         if (is_multipart) {
890                 /* Remember, serv_printf() appends an extra newline */
891                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
892                 serv_printf("This is a multipart message in MIME format.\n");
893                 serv_printf("--%s", top_boundary);
894         }
895
896         /* Remember, serv_printf() appends an extra newline */
897         if (include_text_alt) {
898                 serv_printf("Content-type: multipart/alternative; "
899                         "boundary=\"%s\"\n", alt_boundary);
900                 serv_printf("This is a multipart message in MIME format.\n");
901                 serv_printf("--%s", alt_boundary);
902
903                 serv_puts("Content-type: text/plain; charset=utf-8");
904                 serv_puts("Content-Transfer-Encoding: quoted-printable");
905                 serv_puts("");
906                 txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
907                 text_to_server_qp(txtmail);     /* Transmit message in quoted-printable encoding */
908                 free(txtmail);
909
910                 serv_printf("\n--%s", alt_boundary);
911         }
912
913         serv_puts("Content-type: text/html; charset=utf-8");
914         serv_puts("Content-Transfer-Encoding: quoted-printable");
915         serv_puts("");
916         serv_puts("<html><body>\r\n");
917         text_to_server_qp(bstr("msgtext"));     /* Transmit message in quoted-printable encoding */
918         serv_puts("</body></html>\r\n");
919
920         if (include_text_alt) {
921                 serv_printf("--%s--", alt_boundary);
922         }
923         
924         if (is_multipart) {
925                 long len;
926                 const char *Key; 
927                 void *vAtt;
928                 HashPos  *it;
929
930                 /* Add in the attachments */
931                 it = GetNewHashPos(WCC->attachments, 0);
932                 while (GetNextHashPos(WCC->attachments, it, &len, &Key, &vAtt)) {
933                         att = (wc_mime_attachment *)vAtt;
934                         if (att->length == 0)
935                                 continue;
936                         encoded_length = ((att->length * 150) / 100);
937                         encoded = malloc(encoded_length);
938                         if (encoded == NULL) break;
939                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
940
941                         serv_printf("--%s", top_boundary);
942                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
943                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
944                         serv_puts("Content-transfer-encoding: base64");
945                         serv_puts("");
946                         serv_write(encoded, encoded_strlen);
947                         serv_puts("");
948                         serv_puts("");
949                         free(encoded);
950                 }
951                 serv_printf("--%s--", top_boundary);
952                 DeleteHashPos(&it);
953         }
954
955         serv_puts("000");
956 }
957
958
959 /*
960  * Post message (or don't post message)
961  *
962  * Note regarding the "dont_post" variable:
963  * A random value (actually, it's just a timestamp) is inserted as a hidden
964  * field called "postseq" when the display_enter page is generated.  This
965  * value is checked when posting, using the static variable dont_post.  If a
966  * user attempts to post twice using the same dont_post value, the message is
967  * discarded.  This prevents the accidental double-saving of the same message
968  * if the user happens to click the browser "back" button.
969  */
970 void post_message(void)
971 {
972         StrBuf *UserName;
973         StrBuf *EmailAddress;
974         StrBuf *EncBuf;
975         char buf[1024];
976         StrBuf *encoded_subject = NULL;
977         static long dont_post = (-1L);
978         int is_anonymous = 0;
979         const StrBuf *display_name = NULL;
980         wcsession *WCC = WC;
981         StrBuf *Buf;
982         
983         if (havebstr("force_room")) {
984                 gotoroom(sbstr("force_room"));
985         }
986
987         if (havebstr("display_name")) {
988                 display_name = sbstr("display_name");
989                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
990                         display_name = NULL;
991                         is_anonymous = 1;
992                 }
993         }
994
995         if (!strcasecmp(bstr("submit_action"), "cancel")) {
996                 AppendImportantMessage(_("Cancelled.  Message was not posted."), -1);
997         } else if (lbstr("postseq") == dont_post) {
998                 AppendImportantMessage(
999                         _("Automatically cancelled because you have already "
1000                           "saved this message."), -1);
1001         } else {
1002                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1003                 StrBuf *Recp = NULL; 
1004                 StrBuf *Cc = NULL;
1005                 StrBuf *Bcc = NULL;
1006                 const StrBuf *Wikipage = NULL;
1007                 const StrBuf *my_email_addr = NULL;
1008                 StrBuf *CmdBuf = NULL;
1009                 StrBuf *references = NULL;
1010                 int save_to_drafts;
1011                 long HeaderLen;
1012
1013                 save_to_drafts = !strcasecmp(bstr("submit_action"), "drafts");
1014                 Buf = NewStrBuf();
1015
1016                 if (save_to_drafts) {
1017                         /* temporarily change to the drafts room */
1018                         serv_puts("GOTO _DRAFTS_");
1019                         StrBuf_ServGetln(Buf);
1020                         if (GetServerStatusMsg(Buf, NULL, 1, 2) != 2) {
1021                                 /* You probably don't even have a dumb Drafts folder */
1022                                 syslog(9, "%s:%d: server save to drafts error: %s\n", __FILE__, __LINE__, ChrPtr(Buf) + 4);
1023                                 AppendImportantMessage(_("Saved to Drafts failed: "), -1);
1024                                 display_enter();
1025                                 FreeStrBuf(&Buf);
1026                                 return;
1027                         }
1028                 }
1029
1030                 if (havebstr("references"))
1031                 {
1032                         const StrBuf *ref = sbstr("references");
1033                         references = NewStrBufDup(ref);
1034                         if (*ChrPtr(references) == '|') {       /* remove leading '|' if present */
1035                                 StrBufCutLeft(references, 1);
1036                         }
1037                         StrBufReplaceChars(references, '|', '!');
1038                 }
1039                 if (havebstr("subject")) {
1040                         const StrBuf *Subj;
1041                         /*
1042                          * make enough room for the encoded string; 
1043                          * plus the QP header 
1044                          */
1045                         Subj = sbstr("subject");
1046                         
1047                         StrBufRFC2047encode(&encoded_subject, Subj);
1048                 }
1049                 UserName = NewStrBuf();
1050                 EmailAddress = NewStrBuf();
1051                 EncBuf = NewStrBuf();
1052
1053                 Recp = StrBufSanitizeEmailRecipientVector(sbstr("recp"), UserName, EmailAddress, EncBuf);
1054                 Cc = StrBufSanitizeEmailRecipientVector(sbstr("cc"), UserName, EmailAddress, EncBuf);
1055                 Bcc = StrBufSanitizeEmailRecipientVector(sbstr("bcc"), UserName, EmailAddress, EncBuf);
1056
1057                 FreeStrBuf(&UserName);
1058                 FreeStrBuf(&EmailAddress);
1059                 FreeStrBuf(&EncBuf);
1060
1061                 Wikipage = sbstr("page");
1062                 my_email_addr = sbstr("my_email_addr");
1063                 
1064                 HeaderLen = StrLength(Recp) + 
1065                         StrLength(encoded_subject) +
1066                         StrLength(Cc) +
1067                         StrLength(Bcc) + 
1068                         StrLength(Wikipage) +
1069                         StrLength(my_email_addr) + 
1070                         StrLength(references);
1071                 CmdBuf = NewStrBufPlain(NULL, sizeof (CMD) + HeaderLen);
1072                 StrBufPrintf(CmdBuf, 
1073                              CMD,
1074                              save_to_drafts?"":ChrPtr(Recp),
1075                              is_anonymous,
1076                              ChrPtr(encoded_subject),
1077                              ChrPtr(display_name),
1078                              save_to_drafts?"":ChrPtr(Cc),
1079                              save_to_drafts?"":ChrPtr(Bcc),
1080                              ChrPtr(Wikipage),
1081                              ChrPtr(my_email_addr),
1082                              ChrPtr(references));
1083                 FreeStrBuf(&references);
1084                 FreeStrBuf(&encoded_subject);
1085
1086                 if ((HeaderLen + StrLength(sbstr("msgtext")) < 10) && 
1087                     (GetCount(WCC->attachments) == 0)){
1088                         AppendImportantMessage(_("Refusing to post empty message.\n"), -1);
1089                         FreeStrBuf(&CmdBuf);
1090                                 
1091                 }
1092                 else 
1093                 {
1094                         syslog(9, "%s\n", ChrPtr(CmdBuf));
1095                         serv_puts(ChrPtr(CmdBuf));
1096                         FreeStrBuf(&CmdBuf);
1097
1098                         StrBuf_ServGetln(Buf);
1099                         if (GetServerStatus(Buf, NULL) == 4) {
1100                                 if (save_to_drafts) {
1101                                         if (  (havebstr("recp"))
1102                                               || (havebstr("cc"  ))
1103                                               || (havebstr("bcc" )) ) {
1104                                                 /* save recipient headers or room to post to */
1105                                                 serv_printf("To: %s", ChrPtr(Recp));
1106                                                 serv_printf("Cc: %s", ChrPtr(Cc));
1107                                                 serv_printf("Bcc: %s", ChrPtr(Bcc));
1108                                         } else {
1109                                                 serv_printf("X-Citadel-Room: %s", ChrPtr(WC->CurRoom.name));
1110                                         }
1111                                 }
1112                                 post_mime_to_server();
1113                                 if (save_to_drafts) {
1114                                         AppendImportantMessage(_("Message has been saved to Drafts.\n"), -1);
1115                                         gotoroom(WCC->CurRoom.name);
1116                                         display_enter();
1117                                         FreeStrBuf(&Buf);
1118                                         return;
1119                                 } else if (  (havebstr("recp"))
1120                                              || (havebstr("cc"  ))
1121                                              || (havebstr("bcc" ))
1122                                         ) {
1123                                         AppendImportantMessage(_("Message has been sent.\n"), -1);
1124                                 }
1125                                 else {
1126                                         AppendImportantMessage(_("Message has been posted.\n"), -1);
1127                                 }
1128                                 dont_post = lbstr("postseq");
1129                         } else {
1130                                 syslog(9, "%s:%d: server post error: %s\n", __FILE__, __LINE__, ChrPtr(Buf) + 4);
1131                                 AppendImportantMessage(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
1132                                 if (save_to_drafts) gotoroom(WCC->CurRoom.name);
1133                                 display_enter();
1134                                 FreeStrBuf(&Buf);
1135                                 FreeStrBuf(&Cc);
1136                                 FreeStrBuf(&Bcc);
1137                                 return;
1138                         }
1139                 }
1140                 FreeStrBuf(&Recp);
1141                 FreeStrBuf(&Buf);
1142                 FreeStrBuf(&Cc);
1143                 FreeStrBuf(&Bcc);
1144         }
1145
1146         DeleteHash(&WCC->attachments);
1147
1148         /*
1149          *  We may have been supplied with instructions regarding the location
1150          *  to which we must return after posting.  If found, go there.
1151          */
1152         if (havebstr("return_to")) {
1153                 http_redirect(bstr("return_to"));
1154         }
1155         /*
1156          *  If we were editing a page in a wiki room, go to that page now.
1157          */
1158         else if (havebstr("page")) {
1159                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("page"));
1160                 http_redirect(buf);
1161         }
1162         /*
1163          *  Otherwise, just go to the "read messages" loop.
1164          */
1165         else {
1166                 readloop(readnew, eUseDefault);
1167         }
1168 }
1169
1170
1171 /*
1172  * Client is uploading an attachment
1173  */
1174 void upload_attachment(void) {
1175         wcsession *WCC = WC;
1176         const char *pch;
1177         int n;
1178         const char *newn;
1179         long newnlen;
1180         void *v;
1181         wc_mime_attachment *att;
1182
1183         syslog(9, "upload_attachment()\n");
1184         wc_printf("upload_attachment()<br>\n");
1185
1186         if (WCC->upload_length <= 0) {
1187                 syslog(9, "ERROR no attachment was uploaded\n");
1188                 wc_printf("ERROR no attachment was uploaded<br>\n");
1189                 return;
1190         }
1191
1192         syslog(9, "Client is uploading %d bytes\n", WCC->upload_length);
1193         wc_printf("Client is uploading %d bytes<br>\n", WCC->upload_length);
1194         att = malloc(sizeof(wc_mime_attachment));
1195         memset(att, 0, sizeof(wc_mime_attachment ));
1196         att->length = WCC->upload_length;
1197         att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1198         att->FileName = NewStrBufDup(WCC->upload_filename);
1199         
1200         if (WCC->attachments == NULL) {
1201                 WCC->attachments = NewHash(1, Flathash);
1202         }
1203
1204         /* And add it to the list. */
1205         n = 0;
1206         if ((GetCount(WCC->attachments) > 0) && 
1207             GetHashAt(WCC->attachments, 
1208                       GetCount(WCC->attachments) -1, 
1209                       &newnlen, &newn, &v))
1210             n = *((int*) newn) + 1;
1211         Put(WCC->attachments, IKEY(n), att, DestroyMime);
1212
1213         /*
1214          * Mozilla sends a simple filename, which is what we want,
1215          * but Satan's Browser sends an entire pathname.  Reduce
1216          * the path to just a filename if we need to.
1217          */
1218         pch = strrchr(ChrPtr(att->FileName), '/');
1219         if (pch != NULL) {
1220                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1221         }
1222         pch = strrchr(ChrPtr(att->FileName), '\\');
1223         if (pch != NULL) {
1224                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1225         }
1226
1227         /*
1228          * Transfer control of this memory from the upload struct
1229          * to the attachment struct.
1230          */
1231         att->Data = WCC->upload;
1232         WCC->upload = NULL;
1233         WCC->upload_length = 0;
1234 }
1235
1236
1237 /*
1238  * Remove an attachment from the message currently being composed.
1239  *
1240  * Currently we identify the attachment to be removed by its filename.
1241  * There is probably a better way to do this.
1242  */
1243 void remove_attachment(void) {
1244         wcsession *WCC = WC;
1245         wc_mime_attachment *att;
1246         void *vAtt;
1247         StrBuf *WhichAttachment;
1248         HashPos *at;
1249         long len;
1250         const char *key;
1251
1252         WhichAttachment = NewStrBufDup(sbstr("which_attachment"));
1253         StrBufUnescape(WhichAttachment, 0);
1254         at = GetNewHashPos(WCC->attachments, 0);
1255         do {
1256                 GetHashPos(WCC->attachments, at, &len, &key, &vAtt);
1257         
1258                 att = (wc_mime_attachment*) vAtt;
1259                 if ((att != NULL) && 
1260                     (strcmp(ChrPtr(WhichAttachment), 
1261                             ChrPtr(att->FileName)   ) == 0))
1262                 {
1263                         DeleteEntryFromHash(WCC->attachments, at);
1264                         break;
1265                 }
1266         }
1267         while (NextHashPos(WCC->attachments, at));
1268         FreeStrBuf(&WhichAttachment);
1269         wc_printf("remove_attachment() completed\n");
1270 }
1271
1272
1273 long FourHash(const char *key, long length) 
1274 {
1275         int i;
1276         long ret = 0;
1277         const unsigned char *ptr = (const unsigned char*)key;
1278
1279         for (i = 0; i < 4; i++, ptr ++) 
1280                 ret = (ret << 8) | 
1281                         ( ((*ptr >= 'a') &&
1282                            (*ptr <= 'z'))? 
1283                           *ptr - 'a' + 'A': 
1284                           *ptr);
1285
1286         return ret;
1287 }
1288
1289 long l_subj;
1290 long l_wefw;
1291 long l_msgn;
1292 long l_from;
1293 long l_rcpt;
1294 long l_cccc;
1295 long l_node;
1296 long l_rfca;
1297
1298 /*
1299  * display the message entry screen
1300  */
1301 void display_enter(void)
1302 {
1303         StrBuf *Line;
1304         long Result;
1305         int rc;
1306         const StrBuf *display_name = NULL;
1307         int recipient_required = 0;
1308         int subject_required = 0;
1309         int recipient_bad = 0;
1310         int is_anonymous = 0;
1311         wcsession *WCC = WC;
1312         int i = 0;
1313         long replying_to;
1314
1315         if (havebstr("force_room")) {
1316                 gotoroom(sbstr("force_room"));
1317         }
1318
1319         display_name = sbstr("display_name");
1320         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1321                 display_name = NULL;
1322                 is_anonymous = 1;
1323         }
1324
1325         /* First test to see whether this is a room that requires recipients to be entered */
1326         Line = NewStrBuf();
1327         serv_puts("ENT0 0");
1328         StrBuf_ServGetln(Line);
1329         rc = GetServerStatusMsg(Line, &Result, 0, 2);
1330
1331         if (Result == 570) {            /* 570 means that we need a recipient here */
1332                 recipient_required = 1;
1333         }
1334         else if (rc != 2) {             /* Any other error means that we cannot continue */
1335                 rc = GetServerStatusMsg(Line, &Result, 0, 2);
1336                 readloop(readnew, eUseDefault);
1337                 FreeStrBuf(&Line);
1338                 return;
1339         }
1340
1341         /* Is the server strongly recommending that the user enter a message subject? */
1342         if (StrLength(Line) > 4) {
1343                 subject_required = extract_int(ChrPtr(Line) + 4, 1);
1344         }
1345
1346         /*
1347          * Are we perhaps in an address book view?  If so, then an "enter
1348          * message" command really means "add new entry."
1349          */
1350         if (WCC->CurRoom.defview == VIEW_ADDRESSBOOK) {
1351                 do_edit_vcard(-1, "", NULL, NULL, "",  ChrPtr(WCC->CurRoom.name));
1352                 FreeStrBuf(&Line);
1353                 return;
1354         }
1355
1356         /*
1357          * Are we perhaps in a calendar room?  If so, then an "enter
1358          * message" command really means "add new calendar item."
1359          */
1360         if (WCC->CurRoom.defview == VIEW_CALENDAR) {
1361                 display_edit_event();
1362                 FreeStrBuf(&Line);
1363                 return;
1364         }
1365
1366         /*
1367          * Are we perhaps in a tasks view?  If so, then an "enter
1368          * message" command really means "add new task."
1369          */
1370         if (WCC->CurRoom.defview == VIEW_TASKS) {
1371                 display_edit_task();
1372                 FreeStrBuf(&Line);
1373                 return;
1374         }
1375
1376
1377         /*
1378          * If the "replying_to" variable is set, it refers to a message
1379          * number from which we must extract some header fields...
1380          */
1381         replying_to = lbstr("replying_to");
1382         if (replying_to > 0) {
1383                 long len;
1384                 StrBuf *wefw = NULL;
1385                 StrBuf *msgn = NULL;
1386                 StrBuf *from = NULL;
1387                 StrBuf *node = NULL;
1388                 StrBuf *rfca = NULL;
1389                 StrBuf *rcpt = NULL;
1390                 StrBuf *cccc = NULL;
1391                 serv_printf("MSG0 %ld|1", replying_to); 
1392
1393                 StrBuf_ServGetln(Line);
1394                 if (GetServerStatusMsg(Line, NULL, 0, 0) == 1)
1395                         while (len = StrBuf_ServGetln(Line),
1396                                (len >= 0) && 
1397                                ((len != 3)  ||
1398                                 strcmp(ChrPtr(Line), "000")))
1399                         {
1400                                 long which = 0;
1401                                 if ((StrLength(Line) > 4) && 
1402                                     (ChrPtr(Line)[4] == '='))
1403                                         which = FourHash(ChrPtr(Line), 4);
1404
1405                                 if (which == l_subj)
1406                                 {
1407                                         StrBuf *subj = NewStrBuf();
1408                                         StrBuf *FlatSubject;
1409
1410                                         if (!strcasecmp(bstr("replying_mode"), "forward")) {
1411                                                 if (strncasecmp(ChrPtr(Line) + 5, "Fw:", 3)) {
1412                                                         StrBufAppendBufPlain(subj, HKEY("Fw: "), 0);
1413                                                 }
1414                                         }
1415                                         else {
1416                                                 if (strncasecmp(ChrPtr(Line) + 5, "Re:", 3)) {
1417                                                         StrBufAppendBufPlain(subj, HKEY("Re: "), 0);
1418                                                 }
1419                                         }
1420                                         StrBufAppendBufPlain(subj, 
1421                                                              ChrPtr(Line) + 5, 
1422                                                              StrLength(Line) - 5, 0);
1423                                         FlatSubject = NewStrBufPlain(NULL, StrLength(subj));
1424                                         StrBuf_RFC822_to_Utf8(FlatSubject, subj, NULL, NULL);
1425
1426                                         PutBstr(HKEY("subject"), FlatSubject);
1427                                 }
1428
1429                                 else if (which == l_wefw)
1430                                 {
1431                                         int rrtok;
1432                                         int rrlen;
1433
1434                                         wefw = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1435                                         
1436                                         /* Trim down excessively long lists of thread references.  We eliminate the
1437                                          * second one in the list so that the thread root remains intact.
1438                                          */
1439                                         rrtok = num_tokens(ChrPtr(wefw), '|');
1440                                         rrlen = StrLength(wefw);
1441                                         if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
1442                                                 StrBufRemove_token(wefw, 1, '|');
1443                                         }
1444                                 }
1445
1446                                 else if (which == l_msgn) {
1447                                         msgn = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1448                                 }
1449
1450                                 else if (which == l_from) {
1451                                         StrBuf *FlatFrom;
1452                                         from = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1453                                         FlatFrom = NewStrBufPlain(NULL, StrLength(from));
1454                                         StrBuf_RFC822_to_Utf8(FlatFrom, from, NULL, NULL);
1455                                         FreeStrBuf(&from);
1456                                         from = FlatFrom;
1457                                         for (i=0; i<StrLength(from); ++i) {
1458                                                 if (ChrPtr(from)[i] == ',')
1459                                                         StrBufPeek(from, NULL, i, ' ');
1460                                         }
1461                                 }
1462                                 
1463                                 else if (which == l_rcpt) {
1464                                         rcpt = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1465                                 }
1466                                 
1467                                 else if (which == l_cccc) {
1468                                         cccc = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1469                                 }
1470                                 
1471                                 else if (which == l_node) {
1472                                         node = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1473                                 }
1474                                 
1475                                 else if (which == l_rfca) {
1476                                         StrBuf *FlatRFCA;
1477                                         rfca = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1478                                         FlatRFCA = NewStrBufPlain(NULL, StrLength(rfca));
1479                                         StrBuf_RFC822_to_Utf8(FlatRFCA, rfca, NULL, NULL);
1480                                         FreeStrBuf(&rfca);
1481                                         rfca = FlatRFCA;
1482                                 }
1483                         }
1484
1485
1486                 if (StrLength(wefw) + StrLength(msgn) > 0) {
1487                         StrBuf *refs = NewStrBuf();
1488                         if (StrLength(wefw) > 0) {
1489                                 StrBufAppendBuf(refs, wefw, 0);
1490                         }
1491                         if ( (StrLength(wefw) > 0) && 
1492                              (StrLength(msgn) > 0) ) 
1493                         {
1494                                 StrBufAppendBufPlain(refs, HKEY("|"), 0);
1495                         }
1496                         if (StrLength(msgn) > 0) {
1497                                 StrBufAppendBuf(refs, msgn, 0);
1498                         }
1499                         PutBstr(HKEY("references"), refs);
1500                 }
1501
1502                 /*
1503                  * If this is a Reply or a ReplyAll, copy the sender's email into the To: field
1504                  */
1505                 if (    (!strcasecmp(bstr("replying_mode"), "reply"))
1506                         || (!strcasecmp(bstr("replying_mode"), "replyall"))
1507                 ) {
1508                         StrBuf *to_rcpt;
1509                         if (StrLength(rfca) > 0) {
1510                                 to_rcpt = NewStrBuf();
1511                                 StrBufAppendBuf(to_rcpt, from, 0);
1512                                 StrBufAppendBufPlain(to_rcpt, HKEY(" <"), 0);
1513                                 StrBufAppendBuf(to_rcpt, rfca, 0);
1514                                 StrBufAppendBufPlain(to_rcpt, HKEY(">"), 0);
1515                         }
1516                         else {
1517                                 to_rcpt =  from;
1518                                 from = NULL;
1519                                 if (    (StrLength(node) > 0)
1520                                         && (strcasecmp(ChrPtr(node), ChrPtr(WC->serv_info->serv_nodename)))
1521                                 ) {
1522                                         StrBufAppendBufPlain(to_rcpt, HKEY(" @ "), 0);
1523                                         StrBufAppendBuf(to_rcpt, node, 0);
1524                                 }
1525                         }
1526                         PutBstr(HKEY("recp"), to_rcpt);
1527                 }
1528
1529                 /*
1530                  * Only if this is a ReplyAll, copy all recipients into the Cc: field
1531                  */
1532                 if (    (!strcasecmp(bstr("replying_mode"), "replyall"))
1533                 ) {
1534                         StrBuf *cc_rcpt = rcpt;
1535                         rcpt = NULL;
1536                         if (StrLength(cccc) > 0) {
1537                                 if (cc_rcpt != NULL)  {
1538                                         StrBufAppendPrintf(cc_rcpt, ", ");
1539                                         StrBufAppendBuf(cc_rcpt, cccc, 0);
1540                                 } else {
1541                                         cc_rcpt = cccc;
1542                                         cccc = NULL;
1543                                 }
1544                         }
1545                         if (cc_rcpt != NULL)
1546                                 PutBstr(HKEY("cc"), cc_rcpt);
1547                 }
1548                 FreeStrBuf(&wefw);
1549                 FreeStrBuf(&msgn);
1550                 FreeStrBuf(&from);
1551                 FreeStrBuf(&node);
1552                 FreeStrBuf(&rfca);
1553                 FreeStrBuf(&rcpt);
1554                 FreeStrBuf(&cccc);
1555         }
1556         FreeStrBuf(&Line);
1557         /*
1558          * Otherwise proceed normally.
1559          * Do a custom room banner with no navbar...
1560          */
1561
1562         if (recipient_required) {
1563                 const StrBuf *Recp = NULL; 
1564                 const StrBuf *Cc = NULL;
1565                 const StrBuf *Bcc = NULL;
1566                 const StrBuf *Wikipage = NULL;
1567                 StrBuf *CmdBuf = NULL;
1568                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1569                 
1570                 Recp = sbstr("recp");
1571                 Cc = sbstr("cc");
1572                 Bcc = sbstr("bcc");
1573                 Wikipage = sbstr("page");
1574                 
1575                 CmdBuf = NewStrBufPlain(NULL, 
1576                                         sizeof (CMD) + 
1577                                         StrLength(Recp) + 
1578                                         StrLength(display_name) +
1579                                         StrLength(Cc) +
1580                                         StrLength(Bcc) + 
1581                                         StrLength(Wikipage));
1582
1583                 StrBufPrintf(CmdBuf, 
1584                              CMD,
1585                              ChrPtr(Recp), 
1586                              is_anonymous,
1587                              ChrPtr(display_name),
1588                              ChrPtr(Cc), 
1589                              ChrPtr(Bcc), 
1590                              ChrPtr(Wikipage));
1591                 serv_puts(ChrPtr(CmdBuf));
1592                 StrBuf_ServGetln(CmdBuf);
1593
1594                 rc = GetServerStatusMsg(CmdBuf, &Result, 0, 0);
1595
1596                 if (Result == 570) {    /* 570 means we have an invalid recipient listed */
1597                         if (havebstr("recp") && 
1598                             havebstr("cc"  ) && 
1599                             havebstr("bcc" )) {
1600                                 recipient_bad = 1; /* TODO: and now????? */
1601                         }
1602                 }
1603                 else if (rc != 2) {     /* Any other error means that we cannot continue */
1604                         wc_printf("<em>%s</em><br>\n", ChrPtr(CmdBuf) +4);      /* TODO -> important message */
1605                         FreeStrBuf(&CmdBuf);
1606                         return;
1607                 }
1608                 FreeStrBuf(&CmdBuf);
1609         }
1610         if (recipient_required)
1611                 PutBstr(HKEY("__RCPTREQUIRED"), NewStrBufPlain(HKEY("1")));
1612         if (recipient_required || subject_required)
1613                 PutBstr(HKEY("__SUBJREQUIRED"), NewStrBufPlain(HKEY("1")));
1614
1615         begin_burst();
1616         output_headers(1, 0, 0, 0, 1, 0);
1617         DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1618         end_burst();
1619
1620         return;
1621 }
1622
1623 /*
1624  * delete a message
1625  */
1626 void delete_msg(void)
1627 {
1628         long msgid;
1629         StrBuf *Line;
1630         
1631         msgid = lbstr("msgid");
1632         Line = NewStrBuf();
1633         if ((WC->CurRoom.RAFlags & UA_ISTRASH) != 0) {  /* Delete from Trash is a real delete */
1634                 serv_printf("DELE %ld", msgid); 
1635         }
1636         else {                  /* Otherwise move it to Trash */
1637                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1638         }
1639
1640         StrBuf_ServGetln(Line);
1641         GetServerStatusMsg(Line, NULL, 1, 0);
1642
1643         readloop(readnew, eUseDefault);
1644 }
1645
1646
1647 /*
1648  * move a message to another room
1649  */
1650 void move_msg(void)
1651 {
1652         long msgid;
1653
1654         msgid = lbstr("msgid");
1655
1656         if (havebstr("move_button")) {
1657                 StrBuf *Line;
1658                 serv_printf("MOVE %ld|%s", msgid, bstr("target_room"));
1659                 Line = NewStrBuf();
1660                 StrBuf_ServGetln(Line);
1661                 GetServerStatusMsg(Line, NULL, 1, 0);
1662                 FreeStrBuf(&Line);
1663         } else {
1664                 AppendImportantMessage(_("The message was not moved."), -1);
1665         }
1666
1667         readloop(readnew, eUseDefault);
1668 }
1669
1670
1671
1672 /*
1673  * Generic function to output an arbitrary MIME attachment from
1674  * message being composed
1675  *
1676  * partnum              The MIME part to be output
1677  * filename             Fake filename to give
1678  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1679  */
1680 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1681 {
1682         void *vPart;
1683         StrBuf *content_type;
1684         wc_mime_attachment *part;
1685         int i;
1686
1687         i = StrToi(partnum);
1688         if (GetHash(WC->attachments, IKEY(i), &vPart) &&
1689             (vPart != NULL)) {
1690                 part = (wc_mime_attachment*) vPart;
1691                 if (force_download) {
1692                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1693                 }
1694                 else {
1695                         content_type = NewStrBufDup(part->ContentType);
1696                 }
1697                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1698                 http_transmit_thing(ChrPtr(content_type), 0);
1699         } else {
1700                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1701                 output_headers(0, 0, 0, 0, 0, 0);
1702                 hprintf("Content-Type: text/plain\r\n");
1703                 begin_burst();
1704                 wc_printf(_("An error occurred while retrieving this part: %s/%s\n"), 
1705                         ChrPtr(partnum), ChrPtr(filename));
1706                 end_burst();
1707         }
1708         FreeStrBuf(&content_type);
1709 }
1710
1711
1712 /*
1713  * Generic function to output an arbitrary MIME part from an arbitrary
1714  * message number on the server.
1715  *
1716  * msgnum               Number of the item on the citadel server
1717  * partnum              The MIME part to be output
1718  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1719  */
1720 void mimepart(int force_download)
1721 {
1722         long msgnum;
1723         StrBuf *att;
1724         wcsession *WCC = WC;
1725         StrBuf *Buf;
1726         off_t bytes;
1727         StrBuf *ContentType = NewStrBufPlain(HKEY("application/octet-stream"));
1728         const char *CT;
1729
1730         att = Buf = NewStrBuf();
1731         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
1732         StrBufExtract_token(att, WCC->Hdr->HR.ReqLine, 1, '/');
1733
1734         serv_printf("OPNA %ld|%s", msgnum, ChrPtr(att));
1735         StrBuf_ServGetln(Buf);
1736         if (GetServerStatus(Buf, NULL) == 2) {
1737                 StrBufCutLeft(Buf, 4);
1738                 bytes = StrBufExtract_long(Buf, 0, '|');
1739                 if (!force_download) {
1740                         StrBufExtract_token(ContentType, Buf, 3, '|');
1741                 }
1742
1743                 serv_read_binary(WCC->WBuf, bytes, Buf);
1744                 serv_puts("CLOS");
1745                 StrBuf_ServGetln(Buf);
1746                 CT = ChrPtr(ContentType);
1747
1748                 if (!force_download) {
1749                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1750                                 StrBufExtract_token(Buf, WCC->Hdr->HR.ReqLine, 2, '/');
1751                                 CT = GuessMimeByFilename(SKEY(Buf));
1752                         }
1753                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1754                                 CT = GuessMimeType(SKEY(WCC->WBuf));
1755                         }
1756                 }
1757                 http_transmit_thing(CT, 0);
1758         } else {
1759                 StrBufCutLeft(Buf, 4);
1760                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(Buf));
1761                 output_headers(0, 0, 0, 0, 0, 0);
1762                 hprintf("Content-Type: text/plain\r\n");
1763                 begin_burst();
1764                 wc_printf(_("An error occurred while retrieving this part: %s\n"), 
1765                         ChrPtr(Buf));
1766                 end_burst();
1767         }
1768         FreeStrBuf(&ContentType);
1769         FreeStrBuf(&Buf);
1770 }
1771
1772
1773 /*
1774  * Read any MIME part of a message, from the server, into memory.
1775  */
1776 StrBuf *load_mimepart(long msgnum, char *partnum)
1777 {
1778         off_t bytes;
1779         StrBuf *Buf;
1780         
1781         Buf = NewStrBuf();
1782         serv_printf("DLAT %ld|%s", msgnum, partnum);
1783         StrBuf_ServGetln(Buf);
1784         if (GetServerStatus(Buf, NULL) == 6) {
1785                 StrBufCutLeft(Buf, 4);
1786                 bytes = StrBufExtract_long(Buf, 0, '|');
1787                 FreeStrBuf(&Buf);
1788                 Buf = NewStrBuf();
1789                 StrBuf_ServGetBLOBBuffered(Buf, bytes);
1790                 return(Buf);
1791         }
1792         else {
1793                 FreeStrBuf(&Buf);
1794                 return(NULL);
1795         }
1796 }
1797
1798 /*
1799  * Read any MIME part of a message, from the server, into memory.
1800  */
1801 void MimeLoadData(wc_mime_attachment *Mime)
1802 {
1803         StrBuf *Buf;
1804         const char *Ptr;
1805         off_t bytes;
1806         /* TODO: is there a chance the content type is different from the one we know? */
1807
1808         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1809         Buf = NewStrBuf();
1810         StrBuf_ServGetln(Buf);
1811         if (GetServerStatus(Buf, NULL) == 6) {
1812                 Ptr = &(ChrPtr(Buf)[4]);
1813                 bytes = StrBufExtractNext_long(Buf, &Ptr, '|');
1814                 StrBufSkip_NTokenS(Buf, &Ptr, '|', 3);  /* filename, cbtype, mimetype */
1815                 if (Mime->Charset == NULL) Mime->Charset = NewStrBuf();
1816                 StrBufExtract_NextToken(Mime->Charset, Buf, &Ptr, '|');
1817                 
1818                 if (Mime->Data == NULL)
1819                         Mime->Data = NewStrBufPlain(NULL, bytes);
1820                 StrBuf_ServGetBLOBBuffered(Mime->Data, bytes);
1821         }
1822         else {
1823                 FlushStrBuf(Mime->Data);
1824                 /* TODO XImportant message */
1825         }
1826         FreeStrBuf(&Buf);
1827 }
1828
1829
1830 void view_mimepart(void) {
1831         mimepart(0);
1832 }
1833
1834 void download_mimepart(void) {
1835         mimepart(1);
1836 }
1837
1838 void view_postpart(void) {
1839         StrBuf *filename = NewStrBuf();
1840         StrBuf *partnum = NewStrBuf();
1841
1842         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1843         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1844
1845         postpart(partnum, filename, 0);
1846
1847         FreeStrBuf(&filename);
1848         FreeStrBuf(&partnum);
1849 }
1850
1851 void download_postpart(void) {
1852         StrBuf *filename = NewStrBuf();
1853         StrBuf *partnum = NewStrBuf();
1854
1855         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1856         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1857
1858         postpart(partnum, filename, 1);
1859
1860         FreeStrBuf(&filename);
1861         FreeStrBuf(&partnum);
1862 }
1863
1864
1865
1866 void show_num_attachments(void) {
1867         wc_printf("%d", GetCount(WC->attachments));
1868 }
1869
1870
1871 void h_readnew(void) { readloop(readnew, eUseDefault);}
1872 void h_readold(void) { readloop(readold, eUseDefault);}
1873 void h_readfwd(void) { readloop(readfwd, eUseDefault);}
1874 void h_headers(void) { readloop(headers, eUseDefault);}
1875 void h_do_search(void) { readloop(do_search, eUseDefault);}
1876 void h_readgt(void) { readloop(readgt, eUseDefault);}
1877 void h_readlt(void) { readloop(readlt, eUseDefault);}
1878
1879 void jsonMessageListHdr(void) 
1880 {
1881         /* TODO: make a generic function */
1882         hprintf("HTTP/1.1 200 OK\r\n");
1883         hprintf("Content-type: application/json; charset=utf-8\r\n");
1884         hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
1885         hprintf("Connection: close\r\n");
1886         hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
1887         begin_burst();
1888 }
1889
1890
1891 /* Output message list in JSON format */
1892 void jsonMessageList(void) {
1893         const StrBuf *room = sbstr("room");
1894         long oper = (havebstr("query")) ? do_search : readnew;
1895         WC->is_ajax = 1; 
1896         gotoroom(room);
1897         readloop(oper, eUseDefault);
1898         WC->is_ajax = 0;
1899 }
1900
1901 void RegisterReadLoopHandlerset(
1902         int RoomType,
1903         GetParamsGetServerCall_func GetParamsGetServerCall,
1904         PrintViewHeader_func PrintViewHeader,
1905         load_msg_ptrs_detailheaders LH,
1906         LoadMsgFromServer_func LoadMsgFromServer,
1907         RenderView_or_Tail_func RenderView_or_Tail,
1908         View_Cleanup_func ViewCleanup
1909         )
1910 {
1911         RoomRenderer *Handler;
1912
1913         Handler = (RoomRenderer*) malloc(sizeof(RoomRenderer));
1914
1915         Handler->RoomType = RoomType;
1916         Handler->GetParamsGetServerCall = GetParamsGetServerCall;
1917         Handler->PrintViewHeader = PrintViewHeader;
1918         Handler->LoadMsgFromServer = LoadMsgFromServer;
1919         Handler->RenderView_or_Tail = RenderView_or_Tail;
1920         Handler->ViewCleanup = ViewCleanup;
1921         Handler->LHParse = LH;
1922
1923         Put(ReadLoopHandler, IKEY(RoomType), Handler, NULL);
1924 }
1925
1926 void 
1927 InitModule_MSG
1928 (void)
1929 {
1930         RegisterPreference("use_sig",
1931                            _("Attach signature to email messages?"), 
1932                            PRF_YESNO, 
1933                            NULL);
1934         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
1935         RegisterPreference("default_header_charset", 
1936                            _("Default character set for email headers:"), 
1937                            PRF_STRING, 
1938                            NULL);
1939         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
1940         RegisterPreference("defaultname", 
1941                            _("Preferred display name for email messages"), 
1942                            PRF_STRING, 
1943                            NULL);
1944         RegisterPreference("defaulthandle", 
1945                            _("Preferred display name for bulletin board posts"), 
1946                            PRF_STRING, 
1947                            NULL);
1948         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
1949
1950         WebcitAddUrlHandler(HKEY("readnew"), "", 0, h_readnew, ANONYMOUS|NEED_URL);
1951         WebcitAddUrlHandler(HKEY("readold"), "", 0, h_readold, ANONYMOUS|NEED_URL);
1952         WebcitAddUrlHandler(HKEY("readfwd"), "", 0, h_readfwd, ANONYMOUS|NEED_URL);
1953         WebcitAddUrlHandler(HKEY("headers"), "", 0, h_headers, NEED_URL);
1954         WebcitAddUrlHandler(HKEY("readgt"), "", 0, h_readgt, ANONYMOUS|NEED_URL);
1955         WebcitAddUrlHandler(HKEY("readlt"), "", 0, h_readlt, ANONYMOUS|NEED_URL);
1956         WebcitAddUrlHandler(HKEY("do_search"), "", 0, h_do_search, 0);
1957         WebcitAddUrlHandler(HKEY("display_enter"), "", 0, display_enter, 0);
1958         WebcitAddUrlHandler(HKEY("post"), "", 0, post_message, PROHIBIT_STARTPAGE);
1959         WebcitAddUrlHandler(HKEY("move_msg"), "", 0, move_msg, PROHIBIT_STARTPAGE);
1960         WebcitAddUrlHandler(HKEY("delete_msg"), "", 0, delete_msg, PROHIBIT_STARTPAGE);
1961         WebcitAddUrlHandler(HKEY("msg"), "", 0, embed_message, NEED_URL);
1962         WebcitAddUrlHandler(HKEY("message"), "", 0, handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1963         WebcitAddUrlHandler(HKEY("printmsg"), "", 0, print_message, NEED_URL);
1964         WebcitAddUrlHandler(HKEY("msgheaders"), "", 0, display_headers, NEED_URL);
1965
1966         WebcitAddUrlHandler(HKEY("mimepart"), "", 0, view_mimepart, NEED_URL);
1967         WebcitAddUrlHandler(HKEY("mimepart_download"), "", 0, download_mimepart, NEED_URL);
1968         WebcitAddUrlHandler(HKEY("postpart"), "", 0, view_postpart, NEED_URL|PROHIBIT_STARTPAGE);
1969         WebcitAddUrlHandler(HKEY("postpart_download"), "", 0, download_postpart, NEED_URL|PROHIBIT_STARTPAGE);
1970         WebcitAddUrlHandler(HKEY("upload_attachment"), "", 0, upload_attachment, AJAX);
1971         WebcitAddUrlHandler(HKEY("remove_attachment"), "", 0, remove_attachment, AJAX);
1972         WebcitAddUrlHandler(HKEY("show_num_attachments"), "", 0, show_num_attachments, AJAX);
1973
1974         /* json */
1975         WebcitAddUrlHandler(HKEY("roommsgs"), "", 0, jsonMessageList,0);
1976
1977         l_subj = FourHash("subj", 4);
1978         l_wefw = FourHash("wefw", 4);
1979         l_msgn = FourHash("msgn", 4);
1980         l_from = FourHash("from", 4);
1981         l_rcpt = FourHash("rcpt", 4);
1982         l_cccc = FourHash("cccc", 4);
1983         l_node = FourHash("node", 4);
1984         l_rfca = FourHash("rfca", 4);
1985
1986         return ;
1987 }
1988
1989 void
1990 SessionDetachModule_MSG
1991 (wcsession *sess)
1992 {
1993         DeleteHash(&sess->summ);
1994 }