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