2915ce1480d5b623c2320395ee8e7cad63830c56
[citadel] / 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 "dav.h"
24 #include "calendar.h"
25
26 HashList *MsgHeaderHandler = NULL;
27 HashList *MsgEvaluators = NULL;
28 HashList *MimeRenderHandler = NULL;
29 HashList *ReadLoopHandler = NULL;
30 int dbg_analyze_msg = 0;
31
32 #define SUBJ_COL_WIDTH_PCT              50      /* Mailbox view column width */
33 #define SENDER_COL_WIDTH_PCT            30      /* Mailbox view column width */
34 #define DATE_PLUS_BUTTONS_WIDTH_PCT     20      /* Mailbox view column width */
35
36 void jsonMessageListHdr(void);
37
38 void display_enter(void);
39
40 typedef void (*MsgPartEvaluatorFunc)(message_summary *Sum, StrBuf *Buf);
41
42 typedef struct _MsgPartEvaluatorStruct {
43         MsgPartEvaluatorFunc f;
44 } MsgPartEvaluatorStruct;
45
46 int load_message(message_summary *Msg, 
47                  StrBuf *FoundCharset,
48                  StrBuf **Error)
49 {
50         StrBuf *Buf;
51         StrBuf *HdrToken;
52         headereval *Hdr;
53         void *vHdr;
54         char buf[SIZ];
55         int Done = 0;
56         int state=0;
57         
58         Buf = NewStrBuf();
59         if (Msg->PartNum != NULL) {
60                 serv_printf("MSG4 %ld|%s", Msg->msgnum, ChrPtr(Msg->PartNum));
61         }
62         else {
63                 serv_printf("MSG4 %ld", Msg->msgnum);
64         }
65
66         StrBuf_ServGetln(Buf);
67         if (GetServerStatus(Buf, NULL) != 1) {
68                 *Error = NewStrBuf();
69                 StrBufAppendPrintf(*Error, "<strong>");
70                 StrBufAppendPrintf(*Error, _("ERROR:"));
71                 StrBufAppendPrintf(*Error, "</strong> %s<br>\n", &buf[4]);
72                 FreeStrBuf(&Buf);
73                 return 0;
74         }
75
76         /* begin everythingamundo table */
77         HdrToken = NewStrBuf();
78         while (!Done && StrBuf_ServGetln(Buf)>=0) {
79                 if ( (StrLength(Buf)==3) && 
80                     !strcmp(ChrPtr(Buf), "000")) 
81                 {
82                         Done = 1;
83                         if (state < 2) {
84                                 if (Msg->MsgBody->Data == NULL)
85                                         Msg->MsgBody->Data = NewStrBuf();
86                                 Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/html"));
87                                 StrBufAppendPrintf(Msg->MsgBody->Data, "<div><i>");
88                                 StrBufAppendPrintf(Msg->MsgBody->Data, _("Empty message"));
89                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</i><br><br>\n");
90                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</div>\n");
91                         }
92                         break;
93                 }
94                 switch (state) {
95                 case 0:/* Citadel Message Headers */
96                         if (StrLength(Buf) == 0) {
97                                 state ++;
98                                 break;
99                         }
100                         StrBufExtract_token(HdrToken, Buf, 0, '=');
101                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
102                         
103                         /* look up one of the examine_* functions to parse the content */
104                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
105                             (vHdr != NULL)) {
106                                 Hdr = (headereval*)vHdr;
107                                 Hdr->evaluator(Msg, Buf, FoundCharset);
108                                 if (Hdr->Type == 1) {
109                                         state++;
110                                 }
111                         }/* TODO: 
112                         else LogError(Target, 
113                                       __FUNCTION__,  
114                                       "don't know how to handle message header[%s]\n", 
115                                       ChrPtr(HdrToken));
116                          */
117                         break;
118                 case 1:/* Message Mime Header */
119                         if (StrLength(Buf) == 0) {
120                                 state++;
121                                 if (Msg->MsgBody->ContentType == NULL)
122                                         /* end of header or no header? */
123                                         Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/plain"));
124                                  /* usual end of mime header */
125                         }
126                         else
127                         {
128                                 StrBufExtract_token(HdrToken, Buf, 0, ':');
129                                 if (StrLength(HdrToken) > 0) {
130                                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
131                                         /* the examine*'s know how to do with mime headers too... */
132                                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
133                                             (vHdr != NULL)) {
134                                                 Hdr = (headereval*)vHdr;
135                                                 Hdr->evaluator(Msg, Buf, FoundCharset);
136                                         }
137                                         break;
138                                 }
139                         }
140                 case 2: /* Message Body */
141                         
142                         if (Msg->MsgBody->size_known > 0) {
143                                 StrBuf_ServGetBLOBBuffered(Msg->MsgBody->Data, Msg->MsgBody->length);
144                                 state ++;
145                                 /*/ todo: check next line, if not 000, append following lines */
146                         }
147                         else if (1){
148                                 if (StrLength(Msg->MsgBody->Data) > 0)
149                                         StrBufAppendBufPlain(Msg->MsgBody->Data, "\n", 1, 0);
150                                 StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
151                         }
152                         break;
153                 case 3:
154                         StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
155                         break;
156                 }
157         }
158
159         if (Msg->AllAttach == NULL)
160                 Msg->AllAttach = NewHash(1,NULL);
161         /* now we put the body mimepart we read above into the mimelist */
162         Put(Msg->AllAttach, SKEY(Msg->MsgBody->PartNum), Msg->MsgBody, DestroyMime);
163         
164         FreeStrBuf(&Buf);
165         FreeStrBuf(&HdrToken);
166         return 1;
167 }
168
169
170
171 /*
172  * I wanna SEE that message!
173  *
174  * msgnum               Message number to display
175  * printable_view       Nonzero to display a printable view
176  * section              Optional for encapsulated message/rfc822 submessage
177  */
178 int read_message(StrBuf *Target, const char *tmpl, long tmpllen, long msgnum, const StrBuf *PartNum, const StrBuf **OutMime) 
179 {
180         StrBuf *Buf;
181         StrBuf *FoundCharset;
182         HashPos  *it;
183         void *vMime;
184         message_summary *Msg = NULL;
185         void *vHdr;
186         long len;
187         const char *Key;
188         WCTemplputParams SubTP;
189         StrBuf *Error = NULL;
190
191         Buf = NewStrBuf();
192         FoundCharset = NewStrBuf();
193         Msg = (message_summary *)malloc(sizeof(message_summary));
194         memset(Msg, 0, sizeof(message_summary));
195         Msg->msgnum = msgnum;
196         Msg->PartNum = PartNum;
197         Msg->MsgBody =  (wc_mime_attachment*) malloc(sizeof(wc_mime_attachment));
198         memset(Msg->MsgBody, 0, sizeof(wc_mime_attachment));
199         Msg->MsgBody->msgnum = msgnum;
200
201         if (!load_message(Msg, FoundCharset, &Error)) {
202                 StrBufAppendBuf(Target, Error, 0);
203                 FreeStrBuf(&Error);
204         }
205
206         /* Extract just the content-type (omit attributes such as "charset") */
207         StrBufExtract_token(Buf, Msg->MsgBody->ContentType, 0, ';');
208         StrBufTrim(Buf);
209         StrBufLowerCase(Buf);
210
211         /* Locate a renderer capable of converting this MIME part into HTML */
212         if (GetHash(MimeRenderHandler, SKEY(Buf), &vHdr) &&
213             (vHdr != NULL)) {
214                 RenderMimeFuncStruct *Render;
215                 Render = (RenderMimeFuncStruct*)vHdr;
216                 Render->f(Msg->MsgBody, NULL, FoundCharset);
217         }
218
219         if (StrLength(Msg->reply_references)> 0) {
220                 /* Trim down excessively long lists of thread references.  We eliminate the
221                  * second one in the list so that the thread root remains intact.
222                  */
223                 int rrtok = num_tokens(ChrPtr(Msg->reply_references), '|');
224                 int rrlen = StrLength(Msg->reply_references);
225                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
226                         StrBufRemove_token(Msg->reply_references, 1, '|');
227                 }
228         }
229
230         /* now check if we need to translate some mimeparts, and remove the duplicate */
231         it = GetNewHashPos(Msg->AllAttach, 0);
232         while (GetNextHashPos(Msg->AllAttach, it, &len, &Key, &vMime) && 
233                (vMime != NULL)) {
234                 wc_mime_attachment *Mime = (wc_mime_attachment*) vMime;
235                 evaluate_mime_part(Msg, Mime);
236         }
237         DeleteHashPos(&it);
238         memset(&SubTP, 0, sizeof(WCTemplputParams));
239         SubTP.Filter.ContextType = CTX_MAILSUM;
240         SubTP.Context = Msg;
241         *OutMime = DoTemplate(tmpl, tmpllen, Target, &SubTP);
242
243         DestroyMessageSummary(Msg);
244         FreeStrBuf(&FoundCharset);
245         FreeStrBuf(&Buf);
246         return 1;
247 }
248
249
250 long
251 HttpStatus(long CitadelStatus)
252 {
253         long httpstatus = 502;
254         
255         switch (MAJORCODE(CitadelStatus))
256         {
257         case LISTING_FOLLOWS:
258         case CIT_OK:
259                 httpstatus = 201;
260                 break;
261         case ERROR:
262                 switch (MINORCODE(CitadelStatus))
263                 {
264                 case INTERNAL_ERROR:
265                         httpstatus = 403;
266                         break;
267                         
268                 case TOO_BIG:
269                 case ILLEGAL_VALUE:
270                 case HIGHER_ACCESS_REQUIRED:
271                 case MAX_SESSIONS_EXCEEDED:
272                 case RESOURCE_BUSY:
273                 case RESOURCE_NOT_OPEN:
274                 case NOT_HERE:
275                 case INVALID_FLOOR_OPERATION:
276                 case FILE_NOT_FOUND:
277                 case ROOM_NOT_FOUND:
278                         httpstatus = 409;
279                         break;
280
281                 case MESSAGE_NOT_FOUND:
282                 case ALREADY_EXISTS:
283                         httpstatus = 403;
284                         break;
285
286                 case NO_SUCH_SYSTEM:
287                         httpstatus = 502;
288                         break;
289
290                 default:
291                 case CMD_NOT_SUPPORTED:
292                 case PASSWORD_REQUIRED:
293                 case ALREADY_LOGGED_IN:
294                 case USERNAME_REQUIRED:
295                 case NOT_LOGGED_IN:
296                 case SERVER_SHUTTING_DOWN:
297                 case NO_SUCH_USER:
298                 case ASYNC_GEXP:
299                         httpstatus = 502;
300                         break;
301                 }
302                 break;
303
304         default:
305         case BINARY_FOLLOWS:
306         case SEND_BINARY:
307         case START_CHAT_MODE:
308         case ASYNC_MSG:
309         case MORE_DATA:
310         case SEND_LISTING:
311                 httpstatus = 502; /* aeh... whut? */
312                 break;
313         }
314
315         return httpstatus;
316 }
317
318 /*
319  * Unadorned HTML output of an individual message, suitable
320  * for placing in a hidden iframe, for printing, or whatever
321  */
322 void handle_one_message(void) 
323 {
324         long CitStatus;
325         int CopyMessage = 0;
326         const StrBuf *Destination;
327         void *vLine;
328         const StrBuf *Mime;
329         long msgnum = 0L;
330         wcsession *WCC = WC;
331         const StrBuf *Tmpl;
332         StrBuf *CmdBuf = NULL;
333         const char *pMsg;
334
335
336         pMsg = strchr(ChrPtr(WCC->Hdr->HR.ReqLine), '/');
337         if (pMsg == NULL) {
338                 HttpStatus(CitStatus);
339                 return;
340         }
341
342         msgnum = atol(pMsg + 1);
343         StrBufCutAt(WCC->Hdr->HR.ReqLine, 0, pMsg);
344         gotoroom(WCC->Hdr->HR.ReqLine);
345         switch (WCC->Hdr->HR.eReqType)
346         {
347         case eGET:
348         case ePOST:
349                 Tmpl = sbstr("template");
350                 if (StrLength(Tmpl) > 0) 
351                         read_message(WCC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime);
352                 else 
353                         read_message(WCC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime);
354                 http_transmit_thing(ChrPtr(Mime), 0);
355                 break;
356         case eDELETE:
357                 CmdBuf = NewStrBuf ();
358                 if ((WCC->CurRoom.RAFlags & UA_ISTRASH) != 0) { /* Delete from Trash is a real delete */
359                         serv_printf("DELE %ld", msgnum);        
360                 }
361                 else {                  /* Otherwise move it to Trash */
362                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
363                 }
364                 StrBuf_ServGetln(CmdBuf);
365                 GetServerStatusMsg(CmdBuf, &CitStatus, 1, 0);
366                 HttpStatus(CitStatus);
367                 break;
368         case eCOPY:
369                 CopyMessage = 1;
370         case eMOVE:
371                 if (GetHash(WCC->Hdr->HTTPHeaders, HKEY("DESTINATION"), &vLine) &&
372                     (vLine!=NULL)) {
373                         Destination = (StrBuf*) vLine;
374                         serv_printf("MOVE %ld|%s|%d", msgnum, ChrPtr(Destination), CopyMessage);
375                         StrBuf_ServGetln(CmdBuf);
376                         GetServerStatusMsg(CmdBuf, NULL, 1, 0);
377                         GetServerStatus(CmdBuf, &CitStatus);
378                         HttpStatus(CitStatus);
379                 }
380                 else
381                         HttpStatus(500);
382                 break;
383         default:
384                 break;
385
386         }
387 }
388
389
390 /*
391  * Unadorned HTML output of an individual message, suitable
392  * for placing in a hidden iframe, for printing, or whatever
393  */
394 void embed_message(void) {
395         const StrBuf *Mime;
396         long msgnum = 0L;
397         wcsession *WCC = WC;
398         const StrBuf *Tmpl;
399         StrBuf *CmdBuf = NULL;
400
401         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
402         if (msgnum <= 0) return;
403
404         switch (WCC->Hdr->HR.eReqType)
405         {
406         case eGET:
407         case ePOST:
408                 Tmpl = sbstr("template");
409                 if (StrLength(Tmpl) > 0) 
410                         read_message(WCC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime);
411                 else 
412                         read_message(WCC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime);
413                 http_transmit_thing(ChrPtr(Mime), 0);
414                 break;
415         case eDELETE:
416                 CmdBuf = NewStrBuf ();
417                 if ((WCC->CurRoom.RAFlags & UA_ISTRASH) != 0) { /* Delete from Trash is a real delete */
418                         serv_printf("DELE %ld", msgnum);        
419                 }
420                 else {                  /* Otherwise move it to Trash */
421                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
422                 }
423                 StrBuf_ServGetln(CmdBuf);
424                 GetServerStatusMsg(CmdBuf, NULL, 1, 0);
425                 break;
426         default:
427                 break;
428
429         }
430 }
431
432
433 /*
434  * Printable view of a message
435  */
436 void print_message(void) {
437         long msgnum = 0L;
438         const StrBuf *Mime;
439
440         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
441         output_headers(0, 0, 0, 0, 0, 0);
442
443         hprintf("Content-type: text/html\r\n"
444                 "Server: " PACKAGE_STRING "\r\n"
445                 "Connection: close\r\n");
446
447         begin_burst();
448
449         read_message(WC->WBuf, HKEY("view_message_print"), msgnum, NULL, &Mime);
450
451         wDumpContent(0);
452 }
453
454 /*
455  * Display a message's headers
456  */
457 void display_headers(void) {
458         long msgnum = 0L;
459         char buf[1024];
460
461         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
462         output_headers(0, 0, 0, 0, 0, 0);
463
464         hprintf("Content-type: text/plain\r\n"
465                 "Server: %s\r\n"
466                 "Connection: close\r\n",
467                 PACKAGE_STRING);
468         begin_burst();
469
470         serv_printf("MSG2 %ld|3", msgnum);
471         serv_getln(buf, sizeof buf);
472         if (buf[0] == '1') {
473                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
474                         wc_printf("%s\n", buf);
475                 }
476         }
477
478         wDumpContent(0);
479 }
480
481
482 message_summary *ReadOneMessageSummary(StrBuf *RawMessage, const char *DefaultSubject, long MsgNum) 
483 {
484         void                 *vEval;
485         MsgPartEvaluatorStruct  *Eval;
486         message_summary      *Msg;
487         StrBuf *Buf;
488         const char *buf;
489         const char *ebuf;
490         int nBuf;
491         long len;
492         
493         Buf = NewStrBuf();
494
495         serv_printf("MSG0 %ld|1", MsgNum);      /* ask for headers only */
496         
497         StrBuf_ServGetln(Buf);
498         if (GetServerStatus(Buf, NULL) == 1) {
499                 FreeStrBuf(&Buf);
500                 return NULL;
501         }
502
503         Msg = (message_summary*)malloc(sizeof(message_summary));
504         memset(Msg, 0, sizeof(message_summary));
505         while (len = StrBuf_ServGetln(Buf),
506                (len >= 0) && 
507                ((len != 3)  ||
508                 strcmp(ChrPtr(Buf), "000")))
509         {
510                 buf = ChrPtr(Buf);
511                 ebuf = strchr(ChrPtr(Buf), '=');
512                 nBuf = ebuf - buf;
513                 if (GetHash(MsgEvaluators, buf, nBuf, &vEval) && vEval != NULL) {
514                         Eval = (MsgPartEvaluatorStruct*) vEval;
515                         StrBufCutLeft(Buf, nBuf + 1);
516                         Eval->f(Msg, Buf);
517                 }
518                 else syslog(1, "Don't know how to handle Message Headerline [%s]", ChrPtr(Buf));
519         }
520         return Msg;
521 }
522
523
524
525
526
527 /*
528  * load message pointers from the server for a "read messages" operation
529  *
530  * servcmd:             the citadel command to send to the citserver
531  */
532 int load_msg_ptrs(const char *servcmd, 
533                   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 saving_to_drafts = 0;
1011                 long HeaderLen = 0;
1012
1013                 saving_to_drafts = !strcasecmp(bstr("submit_action"), "draft");
1014                 Buf = NewStrBuf();
1015
1016                 if (saving_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                              saving_to_drafts?"":ChrPtr(Recp),
1075                              is_anonymous,
1076                              ChrPtr(encoded_subject),
1077                              ChrPtr(display_name),
1078                              saving_to_drafts?"":ChrPtr(Cc),
1079                              saving_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 (saving_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 (saving_to_drafts) {
1114                                         AppendImportantMessage(_("Message has been saved to Drafts.\n"), -1);
1115                                         gotoroom(WCC->CurRoom.name);
1116                                         readloop(readnew, eUseDefault);
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", __FILE__, __LINE__, ChrPtr(Buf) + 4);
1131                                 AppendImportantMessage(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
1132                                 display_enter();
1133                                 if (saving_to_drafts) gotoroom(WCC->CurRoom.name);
1134                                 FreeStrBuf(&Recp);
1135                                 FreeStrBuf(&Buf);
1136                                 FreeStrBuf(&Cc);
1137                                 FreeStrBuf(&Bcc);
1138                                 return;
1139                         }
1140                 }
1141                 FreeStrBuf(&Recp);
1142                 FreeStrBuf(&Buf);
1143                 FreeStrBuf(&Cc);
1144                 FreeStrBuf(&Bcc);
1145         }
1146
1147         DeleteHash(&WCC->attachments);
1148
1149         /*
1150          *  We may have been supplied with instructions regarding the location
1151          *  to which we must return after posting.  If found, go there.
1152          */
1153         if (havebstr("return_to")) {
1154                 http_redirect(bstr("return_to"));
1155         }
1156         /*
1157          *  If we were editing a page in a wiki room, go to that page now.
1158          */
1159         else if (havebstr("page")) {
1160                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("page"));
1161                 http_redirect(buf);
1162         }
1163         /*
1164          *  Otherwise, just go to the "read messages" loop.
1165          */
1166         else {
1167                 readloop(readnew, eUseDefault);
1168         }
1169 }
1170
1171
1172 /*
1173  * Client is uploading an attachment
1174  */
1175 void upload_attachment(void) {
1176         wcsession *WCC = WC;
1177         const char *pch;
1178         int n;
1179         const char *newn;
1180         long newnlen;
1181         void *v;
1182         wc_mime_attachment *att;
1183
1184         syslog(9, "upload_attachment()\n");
1185         wc_printf("upload_attachment()<br>\n");
1186
1187         if (WCC->upload_length <= 0) {
1188                 syslog(9, "ERROR no attachment was uploaded\n");
1189                 wc_printf("ERROR no attachment was uploaded<br>\n");
1190                 return;
1191         }
1192
1193         syslog(9, "Client is uploading %d bytes\n", WCC->upload_length);
1194         wc_printf("Client is uploading %d bytes<br>\n", WCC->upload_length);
1195         att = malloc(sizeof(wc_mime_attachment));
1196         memset(att, 0, sizeof(wc_mime_attachment ));
1197         att->length = WCC->upload_length;
1198         att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1199         att->FileName = NewStrBufDup(WCC->upload_filename);
1200         
1201         if (WCC->attachments == NULL) {
1202                 WCC->attachments = NewHash(1, Flathash);
1203         }
1204
1205         /* And add it to the list. */
1206         n = 0;
1207         if ((GetCount(WCC->attachments) > 0) && 
1208             GetHashAt(WCC->attachments, 
1209                       GetCount(WCC->attachments) -1, 
1210                       &newnlen, &newn, &v))
1211             n = *((int*) newn) + 1;
1212         Put(WCC->attachments, IKEY(n), att, DestroyMime);
1213
1214         /*
1215          * Mozilla sends a simple filename, which is what we want,
1216          * but Satan's Browser sends an entire pathname.  Reduce
1217          * the path to just a filename if we need to.
1218          */
1219         pch = strrchr(ChrPtr(att->FileName), '/');
1220         if (pch != NULL) {
1221                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1222         }
1223         pch = strrchr(ChrPtr(att->FileName), '\\');
1224         if (pch != NULL) {
1225                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1226         }
1227
1228         /*
1229          * Transfer control of this memory from the upload struct
1230          * to the attachment struct.
1231          */
1232         att->Data = WCC->upload;
1233         WCC->upload = NULL;
1234         WCC->upload_length = 0;
1235 }
1236
1237
1238 /*
1239  * Remove an attachment from the message currently being composed.
1240  *
1241  * Currently we identify the attachment to be removed by its filename.
1242  * There is probably a better way to do this.
1243  */
1244 void remove_attachment(void) {
1245         wcsession *WCC = WC;
1246         wc_mime_attachment *att;
1247         void *vAtt;
1248         StrBuf *WhichAttachment;
1249         HashPos *at;
1250         long len;
1251         const char *key;
1252
1253         WhichAttachment = NewStrBufDup(sbstr("which_attachment"));
1254         StrBufUnescape(WhichAttachment, 0);
1255         at = GetNewHashPos(WCC->attachments, 0);
1256         do {
1257                 GetHashPos(WCC->attachments, at, &len, &key, &vAtt);
1258         
1259                 att = (wc_mime_attachment*) vAtt;
1260                 if ((att != NULL) && 
1261                     (strcmp(ChrPtr(WhichAttachment), 
1262                             ChrPtr(att->FileName)   ) == 0))
1263                 {
1264                         DeleteEntryFromHash(WCC->attachments, at);
1265                         break;
1266                 }
1267         }
1268         while (NextHashPos(WCC->attachments, at));
1269         FreeStrBuf(&WhichAttachment);
1270         wc_printf("remove_attachment() completed\n");
1271 }
1272
1273
1274 long FourHash(const char *key, long length) 
1275 {
1276         int i;
1277         long ret = 0;
1278         const unsigned char *ptr = (const unsigned char*)key;
1279
1280         for (i = 0; i < 4; i++, ptr ++) 
1281                 ret = (ret << 8) | 
1282                         ( ((*ptr >= 'a') &&
1283                            (*ptr <= 'z'))? 
1284                           *ptr - 'a' + 'A': 
1285                           *ptr);
1286
1287         return ret;
1288 }
1289
1290 long l_subj;
1291 long l_wefw;
1292 long l_msgn;
1293 long l_from;
1294 long l_rcpt;
1295 long l_cccc;
1296 long l_node;
1297 long l_rfca;
1298
1299 /*
1300  * display the message entry screen
1301  */
1302 void display_enter(void)
1303 {
1304         StrBuf *Line;
1305         long Result;
1306         int rc;
1307         const StrBuf *display_name = NULL;
1308         int recipient_required = 0;
1309         int subject_required = 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         /*
1326          * First, do we have permission to enter messages in this room at all?
1327          */
1328         Line = NewStrBuf();
1329         serv_puts("ENT0 0");
1330         StrBuf_ServGetln(Line);
1331         rc = GetServerStatusMsg(Line, &Result, 0, 2);
1332
1333         if (Result == 570) {            /* 570 means that we need a recipient here */
1334                 recipient_required = 1;
1335         }
1336         else if (rc != 2) {             /* Any other error means that we cannot continue */
1337                 rc = GetServerStatusMsg(Line, &Result, 0, 2);
1338                 readloop(readnew, eUseDefault);
1339                 FreeStrBuf(&Line);
1340                 return;
1341         }
1342
1343         /* Is the server strongly recommending that the user enter a message subject? */
1344         if (StrLength(Line) > 4) {
1345                 subject_required = extract_int(ChrPtr(Line) + 4, 1);
1346         }
1347
1348         /*
1349          * Are we perhaps in an address book view?  If so, then an "enter
1350          * message" command really means "add new entry."
1351          */
1352         if (WCC->CurRoom.defview == VIEW_ADDRESSBOOK) {
1353                 do_edit_vcard(-1, "", NULL, NULL, "",  ChrPtr(WCC->CurRoom.name));
1354                 FreeStrBuf(&Line);
1355                 return;
1356         }
1357
1358         /*
1359          * Are we perhaps in a calendar room?  If so, then an "enter
1360          * message" command really means "add new calendar item."
1361          */
1362         if (WCC->CurRoom.defview == VIEW_CALENDAR) {
1363                 display_edit_event();
1364                 FreeStrBuf(&Line);
1365                 return;
1366         }
1367
1368         /*
1369          * Are we perhaps in a tasks view?  If so, then an "enter
1370          * message" command really means "add new task."
1371          */
1372         if (WCC->CurRoom.defview == VIEW_TASKS) {
1373                 display_edit_task();
1374                 FreeStrBuf(&Line);
1375                 return;
1376         }
1377
1378
1379         /*
1380          * If the "replying_to" variable is set, it refers to a message
1381          * number from which we must extract some header fields...
1382          */
1383         replying_to = lbstr("replying_to");
1384         if (replying_to > 0) {
1385                 long len;
1386                 StrBuf *wefw = NULL;
1387                 StrBuf *msgn = NULL;
1388                 StrBuf *from = NULL;
1389                 StrBuf *node = NULL;
1390                 StrBuf *rfca = NULL;
1391                 StrBuf *rcpt = NULL;
1392                 StrBuf *cccc = NULL;
1393                 serv_printf("MSG0 %ld|1", replying_to); 
1394
1395                 StrBuf_ServGetln(Line);
1396                 if (GetServerStatusMsg(Line, NULL, 0, 0) == 1)
1397                         while (len = StrBuf_ServGetln(Line),
1398                                (len >= 0) && 
1399                                ((len != 3)  ||
1400                                 strcmp(ChrPtr(Line), "000")))
1401                         {
1402                                 long which = 0;
1403                                 if ((StrLength(Line) > 4) && 
1404                                     (ChrPtr(Line)[4] == '='))
1405                                         which = FourHash(ChrPtr(Line), 4);
1406
1407                                 if (which == l_subj)
1408                                 {
1409                                         StrBuf *subj = NewStrBuf();
1410                                         StrBuf *FlatSubject;
1411
1412                                         if (!strcasecmp(bstr("replying_mode"), "forward")) {
1413                                                 if (strncasecmp(ChrPtr(Line) + 5, "Fw:", 3)) {
1414                                                         StrBufAppendBufPlain(subj, HKEY("Fw: "), 0);
1415                                                 }
1416                                         }
1417                                         else {
1418                                                 if (strncasecmp(ChrPtr(Line) + 5, "Re:", 3)) {
1419                                                         StrBufAppendBufPlain(subj, HKEY("Re: "), 0);
1420                                                 }
1421                                         }
1422                                         StrBufAppendBufPlain(subj, 
1423                                                              ChrPtr(Line) + 5, 
1424                                                              StrLength(Line) - 5, 0);
1425                                         FlatSubject = NewStrBufPlain(NULL, StrLength(subj));
1426                                         StrBuf_RFC822_to_Utf8(FlatSubject, subj, NULL, NULL);
1427
1428                                         PutBstr(HKEY("subject"), FlatSubject);
1429                                 }
1430
1431                                 else if (which == l_wefw)
1432                                 {
1433                                         int rrtok;
1434                                         int rrlen;
1435
1436                                         wefw = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1437                                         
1438                                         /* Trim down excessively long lists of thread references.  We eliminate the
1439                                          * second one in the list so that the thread root remains intact.
1440                                          */
1441                                         rrtok = num_tokens(ChrPtr(wefw), '|');
1442                                         rrlen = StrLength(wefw);
1443                                         if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
1444                                                 StrBufRemove_token(wefw, 1, '|');
1445                                         }
1446                                 }
1447
1448                                 else if (which == l_msgn) {
1449                                         msgn = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1450                                 }
1451
1452                                 else if (which == l_from) {
1453                                         StrBuf *FlatFrom;
1454                                         from = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1455                                         FlatFrom = NewStrBufPlain(NULL, StrLength(from));
1456                                         StrBuf_RFC822_to_Utf8(FlatFrom, from, NULL, NULL);
1457                                         FreeStrBuf(&from);
1458                                         from = FlatFrom;
1459                                         for (i=0; i<StrLength(from); ++i) {
1460                                                 if (ChrPtr(from)[i] == ',')
1461                                                         StrBufPeek(from, NULL, i, ' ');
1462                                         }
1463                                 }
1464                                 
1465                                 else if (which == l_rcpt) {
1466                                         rcpt = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1467                                 }
1468                                 
1469                                 else if (which == l_cccc) {
1470                                         cccc = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1471                                 }
1472                                 
1473                                 else if (which == l_node) {
1474                                         node = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1475                                 }
1476                                 
1477                                 else if (which == l_rfca) {
1478                                         StrBuf *FlatRFCA;
1479                                         rfca = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1480                                         FlatRFCA = NewStrBufPlain(NULL, StrLength(rfca));
1481                                         StrBuf_RFC822_to_Utf8(FlatRFCA, rfca, NULL, NULL);
1482                                         FreeStrBuf(&rfca);
1483                                         rfca = FlatRFCA;
1484                                 }
1485                         }
1486
1487
1488                 if (StrLength(wefw) + StrLength(msgn) > 0) {
1489                         StrBuf *refs = NewStrBuf();
1490                         if (StrLength(wefw) > 0) {
1491                                 StrBufAppendBuf(refs, wefw, 0);
1492                         }
1493                         if ( (StrLength(wefw) > 0) && 
1494                              (StrLength(msgn) > 0) ) 
1495                         {
1496                                 StrBufAppendBufPlain(refs, HKEY("|"), 0);
1497                         }
1498                         if (StrLength(msgn) > 0) {
1499                                 StrBufAppendBuf(refs, msgn, 0);
1500                         }
1501                         PutBstr(HKEY("references"), refs);
1502                 }
1503
1504                 /*
1505                  * If this is a Reply or a ReplyAll, copy the sender's email into the To: field
1506                  */
1507                 if (    (!strcasecmp(bstr("replying_mode"), "reply"))
1508                         || (!strcasecmp(bstr("replying_mode"), "replyall"))
1509                 ) {
1510                         StrBuf *to_rcpt;
1511                         if (StrLength(rfca) > 0) {
1512                                 to_rcpt = NewStrBuf();
1513                                 StrBufAppendBuf(to_rcpt, from, 0);
1514                                 StrBufAppendBufPlain(to_rcpt, HKEY(" <"), 0);
1515                                 StrBufAppendBuf(to_rcpt, rfca, 0);
1516                                 StrBufAppendBufPlain(to_rcpt, HKEY(">"), 0);
1517                         }
1518                         else {
1519                                 to_rcpt =  from;
1520                                 from = NULL;
1521                                 if (    (StrLength(node) > 0)
1522                                         && (strcasecmp(ChrPtr(node), ChrPtr(WC->serv_info->serv_nodename)))
1523                                 ) {
1524                                         StrBufAppendBufPlain(to_rcpt, HKEY(" @ "), 0);
1525                                         StrBufAppendBuf(to_rcpt, node, 0);
1526                                 }
1527                         }
1528                         PutBstr(HKEY("recp"), to_rcpt);
1529                 }
1530
1531                 /*
1532                  * Only if this is a ReplyAll, copy all recipients into the Cc: field
1533                  */
1534                 if (    (!strcasecmp(bstr("replying_mode"), "replyall"))
1535                 ) {
1536                         StrBuf *cc_rcpt = rcpt;
1537                         rcpt = NULL;
1538                         if (StrLength(cccc) > 0) {
1539                                 if (cc_rcpt != NULL)  {
1540                                         StrBufAppendPrintf(cc_rcpt, ", ");
1541                                         StrBufAppendBuf(cc_rcpt, cccc, 0);
1542                                 } else {
1543                                         cc_rcpt = cccc;
1544                                         cccc = NULL;
1545                                 }
1546                         }
1547                         if (cc_rcpt != NULL)
1548                                 PutBstr(HKEY("cc"), cc_rcpt);
1549                 }
1550                 FreeStrBuf(&wefw);
1551                 FreeStrBuf(&msgn);
1552                 FreeStrBuf(&from);
1553                 FreeStrBuf(&node);
1554                 FreeStrBuf(&rfca);
1555                 FreeStrBuf(&rcpt);
1556                 FreeStrBuf(&cccc);
1557         }
1558         FreeStrBuf(&Line);
1559         /*
1560          * Otherwise proceed normally.
1561          * Do a custom room banner with no navbar...
1562          */
1563
1564         if (recipient_required) {
1565                 const StrBuf *Recp = NULL; 
1566                 const StrBuf *Cc = NULL;
1567                 const StrBuf *Bcc = NULL;
1568                 const StrBuf *Wikipage = NULL;
1569                 StrBuf *CmdBuf = NULL;
1570                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1571                 
1572                 Recp = sbstr("recp");
1573                 Cc = sbstr("cc");
1574                 Bcc = sbstr("bcc");
1575                 Wikipage = sbstr("page");
1576                 
1577                 CmdBuf = NewStrBufPlain(NULL, 
1578                                         sizeof (CMD) + 
1579                                         StrLength(Recp) + 
1580                                         StrLength(display_name) +
1581                                         StrLength(Cc) +
1582                                         StrLength(Bcc) + 
1583                                         StrLength(Wikipage));
1584
1585                 StrBufPrintf(CmdBuf, 
1586                              CMD,
1587                              ChrPtr(Recp), 
1588                              is_anonymous,
1589                              ChrPtr(display_name),
1590                              ChrPtr(Cc), 
1591                              ChrPtr(Bcc), 
1592                              ChrPtr(Wikipage));
1593                 serv_puts(ChrPtr(CmdBuf));
1594                 StrBuf_ServGetln(CmdBuf);
1595
1596                 rc = GetServerStatusMsg(CmdBuf, &Result, 0, 0);
1597
1598                 if (    (Result == 570)         /* invalid or missing recipient(s) */
1599                         || (Result == 550)      /* higher access required to send Internet mail */
1600                 ) {
1601                         /* These errors will have been displayed and are excusable */
1602                 }
1603                 else if (rc != 2) {     /* Any other error means that we cannot continue */
1604                         AppendImportantMessage(ChrPtr(CmdBuf) + 4, StrLength(CmdBuf) - 4);
1605                         FreeStrBuf(&CmdBuf);
1606                         readloop(readnew, eUseDefault);
1607                         return;
1608                 }
1609                 FreeStrBuf(&CmdBuf);
1610         }
1611         if (recipient_required)
1612                 PutBstr(HKEY("__RCPTREQUIRED"), NewStrBufPlain(HKEY("1")));
1613         if (recipient_required || subject_required)
1614                 PutBstr(HKEY("__SUBJREQUIRED"), NewStrBufPlain(HKEY("1")));
1615
1616         begin_burst();
1617         output_headers(1, 0, 0, 0, 1, 0);
1618         DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1619         end_burst();
1620
1621         return;
1622 }
1623
1624 /*
1625  * delete a message
1626  */
1627 void delete_msg(void)
1628 {
1629         long msgid;
1630         StrBuf *Line;
1631         
1632         msgid = lbstr("msgid");
1633         Line = NewStrBuf();
1634         if ((WC->CurRoom.RAFlags & UA_ISTRASH) != 0) {  /* Delete from Trash is a real delete */
1635                 serv_printf("DELE %ld", msgid); 
1636         }
1637         else {                  /* Otherwise move it to Trash */
1638                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1639         }
1640
1641         StrBuf_ServGetln(Line);
1642         GetServerStatusMsg(Line, NULL, 1, 0);
1643
1644         readloop(readnew, eUseDefault);
1645 }
1646
1647
1648 /*
1649  * move a message to another room
1650  */
1651 void move_msg(void)
1652 {
1653         long msgid;
1654
1655         msgid = lbstr("msgid");
1656
1657         if (havebstr("move_button")) {
1658                 StrBuf *Line;
1659                 serv_printf("MOVE %ld|%s", msgid, bstr("target_room"));
1660                 Line = NewStrBuf();
1661                 StrBuf_ServGetln(Line);
1662                 GetServerStatusMsg(Line, NULL, 1, 0);
1663                 FreeStrBuf(&Line);
1664         } else {
1665                 AppendImportantMessage(_("The message was not moved."), -1);
1666         }
1667
1668         readloop(readnew, eUseDefault);
1669 }
1670
1671
1672
1673 /*
1674  * Generic function to output an arbitrary MIME attachment from
1675  * message being composed
1676  *
1677  * partnum              The MIME part to be output
1678  * filename             Fake filename to give
1679  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1680  */
1681 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1682 {
1683         void *vPart;
1684         StrBuf *content_type;
1685         wc_mime_attachment *part;
1686         int i;
1687
1688         i = StrToi(partnum);
1689         if (GetHash(WC->attachments, IKEY(i), &vPart) &&
1690             (vPart != NULL)) {
1691                 part = (wc_mime_attachment*) vPart;
1692                 if (force_download) {
1693                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1694                 }
1695                 else {
1696                         content_type = NewStrBufDup(part->ContentType);
1697                 }
1698                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1699                 http_transmit_thing(ChrPtr(content_type), 0);
1700         } else {
1701                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1702                 output_headers(0, 0, 0, 0, 0, 0);
1703                 hprintf("Content-Type: text/plain\r\n");
1704                 begin_burst();
1705                 wc_printf(_("An error occurred while retrieving this part: %s/%s\n"), 
1706                         ChrPtr(partnum), ChrPtr(filename));
1707                 end_burst();
1708         }
1709         FreeStrBuf(&content_type);
1710 }
1711
1712
1713 /*
1714  * Generic function to output an arbitrary MIME part from an arbitrary
1715  * message number on the server.
1716  *
1717  * msgnum               Number of the item on the citadel server
1718  * partnum              The MIME part to be output
1719  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1720  */
1721 void mimepart(int force_download)
1722 {
1723         long msgnum;
1724         long ErrorDetail;
1725         StrBuf *att;
1726         wcsession *WCC = WC;
1727         StrBuf *Buf;
1728         off_t bytes;
1729         StrBuf *ContentType = NewStrBufPlain(HKEY("application/octet-stream"));
1730         const char *CT;
1731
1732         att = Buf = NewStrBuf();
1733         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
1734         StrBufExtract_token(att, WCC->Hdr->HR.ReqLine, 1, '/');
1735
1736         serv_printf("OPNA %ld|%s", msgnum, ChrPtr(att));
1737         StrBuf_ServGetln(Buf);
1738         if (GetServerStatus(Buf, &ErrorDetail) == 2) {
1739                 StrBufCutLeft(Buf, 4);
1740                 bytes = StrBufExtract_long(Buf, 0, '|');
1741                 if (!force_download) {
1742                         StrBufExtract_token(ContentType, Buf, 3, '|');
1743                 }
1744
1745                 serv_read_binary(WCC->WBuf, bytes, Buf);
1746                 serv_puts("CLOS");
1747                 StrBuf_ServGetln(Buf);
1748                 CT = ChrPtr(ContentType);
1749
1750                 if (!force_download) {
1751                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1752                                 StrBufExtract_token(Buf, WCC->Hdr->HR.ReqLine, 2, '/');
1753                                 CT = GuessMimeByFilename(SKEY(Buf));
1754                         }
1755                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1756                                 CT = GuessMimeType(SKEY(WCC->WBuf));
1757                         }
1758                 }
1759                 http_transmit_thing(CT, 0);
1760         } else {
1761                 StrBufCutLeft(Buf, 4);
1762                 switch (ErrorDetail) {
1763                 default:
1764                 case ERROR + MESSAGE_NOT_FOUND:
1765                         hprintf("HTTP/1.1 404 %s\n", ChrPtr(Buf));
1766                         break;
1767                 case ERROR + NOT_LOGGED_IN:
1768                         hprintf("HTTP/1.1 401 %s\n", ChrPtr(Buf));
1769                         break;
1770
1771                 case ERROR + HIGHER_ACCESS_REQUIRED:
1772                         hprintf("HTTP/1.1 403 %s\n", ChrPtr(Buf));
1773                         break;
1774                 case ERROR + INTERNAL_ERROR:
1775                 case ERROR + TOO_BIG:
1776                         hprintf("HTTP/1.1 500 %s\n", ChrPtr(Buf));
1777                         break;
1778                 }
1779                 output_headers(0, 0, 0, 0, 0, 0);
1780                 hprintf("Content-Type: text/plain\r\n");
1781                 begin_burst();
1782                 wc_printf(_("An error occurred while retrieving this part: %s\n"), 
1783                         ChrPtr(Buf));
1784                 end_burst();
1785         }
1786         FreeStrBuf(&ContentType);
1787         FreeStrBuf(&Buf);
1788 }
1789
1790
1791 /*
1792  * Read any MIME part of a message, from the server, into memory.
1793  */
1794 StrBuf *load_mimepart(long msgnum, char *partnum)
1795 {
1796         off_t bytes;
1797         StrBuf *Buf;
1798         
1799         Buf = NewStrBuf();
1800         serv_printf("DLAT %ld|%s", msgnum, partnum);
1801         StrBuf_ServGetln(Buf);
1802         if (GetServerStatus(Buf, NULL) == 6) {
1803                 StrBufCutLeft(Buf, 4);
1804                 bytes = StrBufExtract_long(Buf, 0, '|');
1805                 FreeStrBuf(&Buf);
1806                 Buf = NewStrBuf();
1807                 StrBuf_ServGetBLOBBuffered(Buf, bytes);
1808                 return(Buf);
1809         }
1810         else {
1811                 FreeStrBuf(&Buf);
1812                 return(NULL);
1813         }
1814 }
1815
1816 /*
1817  * Read any MIME part of a message, from the server, into memory.
1818  */
1819 void MimeLoadData(wc_mime_attachment *Mime)
1820 {
1821         StrBuf *Buf;
1822         const char *Ptr;
1823         off_t bytes;
1824         /* TODO: is there a chance the content type is different from the one we know? */
1825
1826         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1827         Buf = NewStrBuf();
1828         StrBuf_ServGetln(Buf);
1829         if (GetServerStatus(Buf, NULL) == 6) {
1830                 Ptr = &(ChrPtr(Buf)[4]);
1831                 bytes = StrBufExtractNext_long(Buf, &Ptr, '|');
1832                 StrBufSkip_NTokenS(Buf, &Ptr, '|', 3);  /* filename, cbtype, mimetype */
1833                 if (Mime->Charset == NULL) Mime->Charset = NewStrBuf();
1834                 StrBufExtract_NextToken(Mime->Charset, Buf, &Ptr, '|');
1835                 
1836                 if (Mime->Data == NULL)
1837                         Mime->Data = NewStrBufPlain(NULL, bytes);
1838                 StrBuf_ServGetBLOBBuffered(Mime->Data, bytes);
1839         }
1840         else {
1841                 FlushStrBuf(Mime->Data);
1842                 /* TODO XImportant message */
1843         }
1844         FreeStrBuf(&Buf);
1845 }
1846
1847
1848 void view_mimepart(void) {
1849         mimepart(0);
1850 }
1851
1852 void download_mimepart(void) {
1853         mimepart(1);
1854 }
1855
1856 void view_postpart(void) {
1857         StrBuf *filename = NewStrBuf();
1858         StrBuf *partnum = NewStrBuf();
1859
1860         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1861         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1862
1863         postpart(partnum, filename, 0);
1864
1865         FreeStrBuf(&filename);
1866         FreeStrBuf(&partnum);
1867 }
1868
1869 void download_postpart(void) {
1870         StrBuf *filename = NewStrBuf();
1871         StrBuf *partnum = NewStrBuf();
1872
1873         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1874         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1875
1876         postpart(partnum, filename, 1);
1877
1878         FreeStrBuf(&filename);
1879         FreeStrBuf(&partnum);
1880 }
1881
1882
1883
1884 void show_num_attachments(void) {
1885         wc_printf("%d", GetCount(WC->attachments));
1886 }
1887
1888
1889 void h_readnew(void) { readloop(readnew, eUseDefault);}
1890 void h_readold(void) { readloop(readold, eUseDefault);}
1891 void h_readfwd(void) { readloop(readfwd, eUseDefault);}
1892 void h_headers(void) { readloop(headers, eUseDefault);}
1893 void h_do_search(void) { readloop(do_search, eUseDefault);}
1894 void h_readgt(void) { readloop(readgt, eUseDefault);}
1895 void h_readlt(void) { readloop(readlt, eUseDefault);}
1896
1897 void jsonMessageListHdr(void) 
1898 {
1899         /* TODO: make a generic function */
1900         hprintf("HTTP/1.1 200 OK\r\n");
1901         hprintf("Content-type: application/json; charset=utf-8\r\n");
1902         hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
1903         hprintf("Connection: close\r\n");
1904         hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
1905         begin_burst();
1906 }
1907
1908
1909 /* Output message list in JSON format */
1910 void jsonMessageList(void) {
1911         const StrBuf *room = sbstr("room");
1912         long oper = (havebstr("query")) ? do_search : readnew;
1913         WC->is_ajax = 1; 
1914         gotoroom(room);
1915         readloop(oper, eUseDefault);
1916         WC->is_ajax = 0;
1917 }
1918
1919 void RegisterReadLoopHandlerset(
1920         int RoomType,
1921         GetParamsGetServerCall_func GetParamsGetServerCall,
1922         PrintViewHeader_func PrintViewHeader,
1923         load_msg_ptrs_detailheaders LH,
1924         LoadMsgFromServer_func LoadMsgFromServer,
1925         RenderView_or_Tail_func RenderView_or_Tail,
1926         View_Cleanup_func ViewCleanup
1927         )
1928 {
1929         RoomRenderer *Handler;
1930
1931         Handler = (RoomRenderer*) malloc(sizeof(RoomRenderer));
1932
1933         Handler->RoomType = RoomType;
1934         Handler->GetParamsGetServerCall = GetParamsGetServerCall;
1935         Handler->PrintViewHeader = PrintViewHeader;
1936         Handler->LoadMsgFromServer = LoadMsgFromServer;
1937         Handler->RenderView_or_Tail = RenderView_or_Tail;
1938         Handler->ViewCleanup = ViewCleanup;
1939         Handler->LHParse = LH;
1940
1941         Put(ReadLoopHandler, IKEY(RoomType), Handler, NULL);
1942 }
1943
1944 void 
1945 InitModule_MSG
1946 (void)
1947 {
1948         RegisterPreference("use_sig",
1949                            _("Attach signature to email messages?"), 
1950                            PRF_YESNO, 
1951                            NULL);
1952         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
1953         RegisterPreference("default_header_charset", 
1954                            _("Default character set for email headers:"), 
1955                            PRF_STRING, 
1956                            NULL);
1957         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
1958         RegisterPreference("defaultname", 
1959                            _("Preferred display name for email messages"), 
1960                            PRF_STRING, 
1961                            NULL);
1962         RegisterPreference("defaulthandle", 
1963                            _("Preferred display name for bulletin board posts"), 
1964                            PRF_STRING, 
1965                            NULL);
1966         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
1967
1968         WebcitAddUrlHandler(HKEY("readnew"), "", 0, h_readnew, ANONYMOUS|NEED_URL);
1969         WebcitAddUrlHandler(HKEY("readold"), "", 0, h_readold, ANONYMOUS|NEED_URL);
1970         WebcitAddUrlHandler(HKEY("readfwd"), "", 0, h_readfwd, ANONYMOUS|NEED_URL);
1971         WebcitAddUrlHandler(HKEY("headers"), "", 0, h_headers, NEED_URL);
1972         WebcitAddUrlHandler(HKEY("readgt"), "", 0, h_readgt, ANONYMOUS|NEED_URL);
1973         WebcitAddUrlHandler(HKEY("readlt"), "", 0, h_readlt, ANONYMOUS|NEED_URL);
1974         WebcitAddUrlHandler(HKEY("do_search"), "", 0, h_do_search, 0);
1975         WebcitAddUrlHandler(HKEY("display_enter"), "", 0, display_enter, 0);
1976         WebcitAddUrlHandler(HKEY("post"), "", 0, post_message, PROHIBIT_STARTPAGE);
1977         WebcitAddUrlHandler(HKEY("move_msg"), "", 0, move_msg, PROHIBIT_STARTPAGE);
1978         WebcitAddUrlHandler(HKEY("delete_msg"), "", 0, delete_msg, PROHIBIT_STARTPAGE);
1979         WebcitAddUrlHandler(HKEY("msg"), "", 0, embed_message, NEED_URL);
1980         WebcitAddUrlHandler(HKEY("message"), "", 0, handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1981         WebcitAddUrlHandler(HKEY("printmsg"), "", 0, print_message, NEED_URL);
1982         WebcitAddUrlHandler(HKEY("msgheaders"), "", 0, display_headers, NEED_URL);
1983
1984         WebcitAddUrlHandler(HKEY("mimepart"), "", 0, view_mimepart, NEED_URL);
1985         WebcitAddUrlHandler(HKEY("mimepart_download"), "", 0, download_mimepart, NEED_URL);
1986         WebcitAddUrlHandler(HKEY("postpart"), "", 0, view_postpart, NEED_URL|PROHIBIT_STARTPAGE);
1987         WebcitAddUrlHandler(HKEY("postpart_download"), "", 0, download_postpart, NEED_URL|PROHIBIT_STARTPAGE);
1988         WebcitAddUrlHandler(HKEY("upload_attachment"), "", 0, upload_attachment, AJAX);
1989         WebcitAddUrlHandler(HKEY("remove_attachment"), "", 0, remove_attachment, AJAX);
1990         WebcitAddUrlHandler(HKEY("show_num_attachments"), "", 0, show_num_attachments, AJAX);
1991
1992         /* json */
1993         WebcitAddUrlHandler(HKEY("roommsgs"), "", 0, jsonMessageList,0);
1994
1995         l_subj = FourHash("subj", 4);
1996         l_wefw = FourHash("wefw", 4);
1997         l_msgn = FourHash("msgn", 4);
1998         l_from = FourHash("from", 4);
1999         l_rcpt = FourHash("rcpt", 4);
2000         l_cccc = FourHash("cccc", 4);
2001         l_node = FourHash("node", 4);
2002         l_rfca = FourHash("rfca", 4);
2003
2004         return ;
2005 }
2006
2007 void
2008 SessionDetachModule_MSG
2009 (wcsession *sess)
2010 {
2011         DeleteHash(&sess->summ);
2012 }