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