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