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