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