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