* post_message(): QP encode TO/CC/BCC if necessary
[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 (!Done && StrBuf_ServGetln(Buf)>=0) {
67                 if ( (StrLength(Buf)==3) && 
68                     !strcmp(ChrPtr(Buf), "000")) 
69                 {
70                         Done = 1;
71                         if (state < 2) {
72                                 if (Msg->MsgBody->Data == NULL)
73                                         Msg->MsgBody->Data = NewStrBuf();
74                                 Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/html"));
75                                 StrBufAppendPrintf(Msg->MsgBody->Data, "<div><i>");
76                                 StrBufAppendPrintf(Msg->MsgBody->Data, _("Empty message"));
77                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</i><br /><br />\n");
78                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</div>\n");
79                         }
80                         break;
81                 }
82                 switch (state) {
83                 case 0:/* Citadel Message Headers */
84                         if (StrLength(Buf) == 0) {
85                                 state ++;
86                                 break;
87                         }
88                         StrBufExtract_token(HdrToken, Buf, 0, '=');
89                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
90                         
91 #ifdef TECH_PREVIEW
92                         if (dbg_analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
93 #endif
94                         /* look up one of the examine_* functions to parse the content */
95                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
96                             (vHdr != NULL)) {
97                                 Hdr = (headereval*)vHdr;
98                                 Hdr->evaluator(Msg, Buf, FoundCharset);
99                                 if (Hdr->Type == 1) {
100                                         state++;
101                                 }
102                         }/* TODO: 
103                         else LogError(Target, 
104                                       __FUNCTION__,  
105                                       "don't know how to handle message header[%s]\n", 
106                                       ChrPtr(HdrToken));
107                          */
108                         break;
109                 case 1:/* Message Mime Header */
110                         if (StrLength(Buf) == 0) {
111                                 state++;
112                                 if (Msg->MsgBody->ContentType == NULL)
113                                         /* end of header or no header? */
114                                         Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/plain"));
115                                  /* usual end of mime header */
116                         }
117                         else
118                         {
119                                 StrBufExtract_token(HdrToken, Buf, 0, ':');
120                                 if (StrLength(HdrToken) > 0) {
121                                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
122 #ifdef TECH_PREVIEW
123                                         if (dbg_analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
124 #endif
125                                         /* the examine*'s know how to do with mime headers too... */
126                                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
127                                             (vHdr != NULL)) {
128                                                 Hdr = (headereval*)vHdr;
129                                                 Hdr->evaluator(Msg, Buf, FoundCharset);
130                                         }
131                                         break;
132                                 }
133                         }
134                 case 2: /* Message Body */
135                         
136                         if (Msg->MsgBody->size_known > 0) {
137                                 StrBuf_ServGetBLOBBuffered(Msg->MsgBody->Data, Msg->MsgBody->length);
138                                 state ++;
139                                 /*/ todo: check next line, if not 000, append following lines */
140                         }
141                         else if (1){
142                                 if (StrLength(Msg->MsgBody->Data) > 0)
143                                         StrBufAppendBufPlain(Msg->MsgBody->Data, "\n", 1, 0);
144                                 StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
145                         }
146                         break;
147                 case 3:
148                         StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
149                         break;
150                 }
151         }
152
153         if (Msg->AllAttach == NULL)
154                 Msg->AllAttach = NewHash(1,NULL);
155         /* now we put the body mimepart we read above into the mimelist */
156         Put(Msg->AllAttach, SKEY(Msg->MsgBody->PartNum), Msg->MsgBody, DestroyMime);
157         
158         /* Generate a reply-to address */
159         if (StrLength(Msg->Rfca) > 0) {
160                 if (Msg->reply_to == NULL)
161                         Msg->reply_to = NewStrBuf();
162                 if (StrLength(Msg->from) > 0) {
163                         StrBufPrintf(Msg->reply_to, "%s <%s>", ChrPtr(Msg->from), ChrPtr(Msg->Rfca));
164                 }
165                 else {
166                         FlushStrBuf(Msg->reply_to);
167                         StrBufAppendBuf(Msg->reply_to, Msg->Rfca, 0);
168                 }
169         }
170         else 
171         {
172                 if ((StrLength(Msg->OtherNode)>0) && 
173                     (strcasecmp(ChrPtr(Msg->OtherNode), ChrPtr(WCC->serv_info->serv_nodename))) &&
174                     (strcasecmp(ChrPtr(Msg->OtherNode), ChrPtr(WCC->serv_info->serv_humannode)) ))
175                 {
176                         if (Msg->reply_to == NULL)
177                                 Msg->reply_to = NewStrBuf();
178                         StrBufPrintf(Msg->reply_to, 
179                                      "%s @ %s",
180                                      ChrPtr(Msg->from), 
181                                      ChrPtr(Msg->OtherNode));
182                 }
183                 else {
184                         if (Msg->reply_to == NULL)
185                                 Msg->reply_to = NewStrBuf();
186                         FlushStrBuf(Msg->reply_to);
187                         StrBufAppendBuf(Msg->reply_to, Msg->from, 0);
188                 }
189         }
190         FreeStrBuf(&Buf);
191         FreeStrBuf(&HdrToken);
192         return 1;
193 }
194
195
196
197 /*
198  * I wanna SEE that message!
199  *
200  * msgnum               Message number to display
201  * printable_view       Nonzero to display a printable view
202  * section              Optional for encapsulated message/rfc822 submessage
203  */
204 int read_message(StrBuf *Target, const char *tmpl, long tmpllen, long msgnum, const StrBuf *PartNum, const StrBuf **OutMime) 
205 {
206         StrBuf *Buf;
207         StrBuf *FoundCharset;
208         HashPos  *it;
209         void *vMime;
210         message_summary *Msg = NULL;
211         void *vHdr;
212         long len;
213         const char *Key;
214         WCTemplputParams SubTP;
215         StrBuf *Error = NULL;
216
217         Buf = NewStrBuf();
218         FoundCharset = NewStrBuf();
219         Msg = (message_summary *)malloc(sizeof(message_summary));
220         memset(Msg, 0, sizeof(message_summary));
221         Msg->msgnum = msgnum;
222         Msg->PartNum = PartNum;
223         Msg->MsgBody =  (wc_mime_attachment*) malloc(sizeof(wc_mime_attachment));
224         memset(Msg->MsgBody, 0, sizeof(wc_mime_attachment));
225         Msg->MsgBody->msgnum = msgnum;
226
227         if (!load_message(Msg, FoundCharset, &Error)) {
228                 StrBufAppendBuf(Target, Error, 0);
229                 FreeStrBuf(&Error);
230         }
231
232         /* Extract just the content-type (omit attributes such as "charset") */
233         StrBufExtract_token(Buf, Msg->MsgBody->ContentType, 0, ';');
234         StrBufTrim(Buf);
235         StrBufLowerCase(Buf);
236
237         /* Locate a renderer capable of converting this MIME part into HTML */
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->CurRoom.RAFlags & UA_ISTRASH) != 0) { /* 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->CurRoom.RAFlags & UA_ISTRASH) != 0) { /* 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                         wc_printf("%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, 
575                   SharedMessageStatus *Stat, 
576                   load_msg_ptrs_detailheaders LH)
577 {
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) && (LH != NULL)) {
637                                 if (!LH(Buf, &Ptr, Msg, Buf2)){
638                                         free(Msg);
639                                         continue;
640                                 }                                       
641                         }
642                         n = Msg->msgnum;
643                         Put(WCC->summ, (const char *)&n, sizeof(n), Msg, DestroyMessageSummary);
644                 }
645                 Stat->nummsgs++;
646         }
647         FreeStrBuf(&Buf2);
648         FreeStrBuf(&Buf);
649         return (Stat->nummsgs);
650 }
651
652
653
654
655
656 void load_seen_flags(void)
657 {
658         message_summary *Msg;
659         const char *HashKey;
660         long HKLen;
661         HashPos *at;
662         void *vMsg;
663         StrBuf *OldMsg;
664         wcsession *WCC = WC;
665
666         OldMsg = NewStrBuf();
667         serv_puts("GTSN");
668         StrBuf_ServGetln(OldMsg);
669         if (GetServerStatus(OldMsg, NULL) == 2) {
670                 StrBufCutLeft(OldMsg, 4);
671         }
672         else {
673                 FreeStrBuf(&OldMsg);
674                 return;
675         }
676         at = GetNewHashPos(WCC->summ, 0);
677         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
678                 /* Are you a new message, or an old message? */
679                 Msg = (message_summary*) vMsg;
680                 if (is_msg_in_mset(ChrPtr(OldMsg), Msg->msgnum)) {
681                         Msg->is_new = 0;
682                 }
683                 else {
684                         Msg->is_new = 1;
685                 }
686         }
687         FreeStrBuf(&OldMsg);
688         DeleteHashPos(&at);
689 }
690
691 extern readloop_struct rlid[];
692
693 typedef struct _RoomRenderer{
694         int RoomType;
695
696         GetParamsGetServerCall_func GetParamsGetServerCall;
697         PrintViewHeader_func PrintViewHeader;
698         LoadMsgFromServer_func LoadMsgFromServer;
699         RenderView_or_Tail_func RenderView_or_Tail;
700         View_Cleanup_func ViewCleanup;
701         load_msg_ptrs_detailheaders LHParse;
702 } RoomRenderer;
703
704
705 /*
706  * command loop for reading messages
707  *
708  * Set oper to "readnew" or "readold" or "readfwd" or "headers" or "readgt" or "readlt" or "do_search"
709  */
710 void readloop(long oper, eCustomRoomRenderer ForceRenderer)
711 {
712         RoomRenderer *ViewMsg;
713         void *vViewMsg;
714         void *vMsg;
715         message_summary *Msg;
716         char cmd[256] = "";
717         int i, r;
718         wcsession *WCC = WC;
719         HashPos *at;
720         const char *HashKey;
721         long HKLen;
722         WCTemplputParams SubTP;
723         SharedMessageStatus Stat;
724         void *ViewSpecific;
725
726         if (havebstr("is_summary") && (1 == (ibstr("is_summary")))) {
727                 WCC->CurRoom.view = VIEW_MAILBOX;
728         }
729
730         if (havebstr("is_ajax") && (1 == (ibstr("is_ajax")))) {
731                 WCC->is_ajax = 1;
732         }
733
734         if ((oper == do_search) && (WCC->CurRoom.view == VIEW_WIKI)) {
735                 display_wiki_pagelist();
736                 return;
737         }
738
739         memset(&Stat, 0, sizeof(SharedMessageStatus));
740         Stat.maxload = 10000;
741         Stat.lowest_found = (-1);
742         Stat.highest_found = (-1);
743         if (ForceRenderer == eUseDefault)
744                 GetHash(ReadLoopHandler, IKEY(WCC->CurRoom.view), &vViewMsg);
745         else 
746                 GetHash(ReadLoopHandler, IKEY(ForceRenderer), &vViewMsg);
747         if (vViewMsg == NULL) {
748                 WCC->CurRoom.view = VIEW_BBS;
749                 GetHash(ReadLoopHandler, IKEY(WCC->CurRoom.view), &vViewMsg);
750         }
751         if (vViewMsg == NULL) {
752                 return;                 // TODO: print message
753         }
754
755         ViewMsg = (RoomRenderer*) vViewMsg;
756         if (!WCC->is_ajax) {
757                 output_headers(1, 1, 1, 0, 0, 0);
758         } else if (WCC->CurRoom.view == VIEW_MAILBOX) {
759                 jsonMessageListHdr();
760         }
761
762         if (ViewMsg->GetParamsGetServerCall != NULL) {
763                 r = ViewMsg->GetParamsGetServerCall(
764                        &Stat,
765                        &ViewSpecific,
766                        oper,
767                        cmd, sizeof(cmd)
768                 );
769         } else {
770                 r = 0;
771         }
772         switch(r)
773         {
774         case 400:
775         case 404:
776
777                 return;
778         case 300: /* the callback hook should do the work for us here, since he knows what to do. */
779                 return;
780         case 200:
781         default:
782                 break;
783         }
784         if (!IsEmptyStr(cmd))
785                 Stat.nummsgs = load_msg_ptrs(cmd, &Stat, ViewMsg->LHParse);
786
787         if (Stat.sortit) {
788                 CompareFunc SortIt;
789                 memset(&SubTP, 0, sizeof(WCTemplputParams));
790                 SubTP.Filter.ContextType = CTX_MAILSUM;
791                 SubTP.Context = NULL;
792                 SortIt =  RetrieveSort(&SubTP, NULL, 0,
793                                        HKEY("date"), Stat.defaultsortorder);
794                 if (SortIt != NULL)
795                         SortByPayload(WCC->summ, SortIt);
796         }
797         if (Stat.startmsg < 0) {
798                 Stat.startmsg =  0;
799         }
800
801         if (Stat.load_seen) load_seen_flags();
802         
803         /*
804          * Print any inforation above the message list...
805          */
806         if (ViewMsg->PrintViewHeader != NULL)
807                 ViewMsg->PrintViewHeader(&Stat, &ViewSpecific);
808
809         WCC->startmsg =  Stat.startmsg;
810         WCC->maxmsgs = Stat.maxmsgs;
811         WCC->num_displayed = 0;
812
813         /* Put some helpful data in vars for mailsummary_json */
814         svputlong("READLOOP:TOTALMSGS", Stat.nummsgs);
815         svputlong("READLOOP:STARTMSG", Stat.startmsg);
816         svputlong("WCVIEW", WCC->CurRoom.view);
817
818         /*
819          * iterate over each message. if we need to load an attachment, do it here. 
820          */
821
822         if ((ViewMsg->LoadMsgFromServer != NULL) && 
823             (!IsEmptyStr(cmd)))
824         {
825                 at = GetNewHashPos(WCC->summ, 0);
826                 Stat.num_displayed = i = 0;
827                 while ( GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
828                         Msg = (message_summary*) vMsg;          
829                         if ((Msg->msgnum >= Stat.startmsg) && (Stat.num_displayed <= Stat.maxmsgs)) {
830                                 ViewMsg->LoadMsgFromServer(&Stat, &ViewSpecific, Msg, Msg->is_new, i);
831                         } 
832                         i++;
833                 }
834                 DeleteHashPos(&at);
835         }
836
837         /*
838          * Done iterating the message list. now tasks we want to do after.
839          */
840         if (ViewMsg->RenderView_or_Tail != NULL)
841                 ViewMsg->RenderView_or_Tail(&Stat, &ViewSpecific, oper);
842
843         if (ViewMsg->ViewCleanup != NULL)
844                 ViewMsg->ViewCleanup(&ViewSpecific);
845
846         WCC->startmsg = 0;
847         WCC->maxmsgs = 0;
848         if (WCC->summ != NULL) {
849                 DeleteHash(&WCC->summ);
850         }
851 }
852
853
854 /*
855  * Back end for post_message()
856  * ... this is where the actual message gets transmitted to the server.
857  */
858 void post_mime_to_server(void) {
859         wcsession *WCC = WC;
860         char top_boundary[SIZ];
861         char alt_boundary[SIZ];
862         int is_multipart = 0;
863         static int seq = 0;
864         wc_mime_attachment *att;
865         char *encoded;
866         size_t encoded_length;
867         size_t encoded_strlen;
868         char *txtmail = NULL;
869         int include_text_alt = 0;       /* Set to nonzero to include multipart/alternative text/plain */
870
871         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
872                 ChrPtr(WCC->serv_info->serv_fqdn),
873                 getpid(),
874                 ++seq
875         );
876         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
877                 ChrPtr(WCC->serv_info->serv_fqdn),
878                 getpid(),
879                 ++seq
880         );
881
882         /* RFC2045 requires this, and some clients look for it... */
883         serv_puts("MIME-Version: 1.0");
884         serv_puts("X-Mailer: " PACKAGE_STRING);
885
886         /* If there are attachments, we have to do multipart/mixed */
887         if (GetCount(WCC->attachments) > 0) {
888                 is_multipart = 1;
889         }
890
891         /* Only do multipart/alternative for mailboxes.  BBS and Wiki rooms don't need it. */
892         if (WC->CurRoom.view == VIEW_MAILBOX) {
893                 include_text_alt = 1;
894         }
895
896         if (is_multipart) {
897                 /* Remember, serv_printf() appends an extra newline */
898                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
899                 serv_printf("This is a multipart message in MIME format.\n");
900                 serv_printf("--%s", top_boundary);
901         }
902
903         /* Remember, serv_printf() appends an extra newline */
904         if (include_text_alt) {
905                 serv_printf("Content-type: multipart/alternative; "
906                         "boundary=\"%s\"\n", alt_boundary);
907                 serv_printf("This is a multipart message in MIME format.\n");
908                 serv_printf("--%s", alt_boundary);
909
910                 serv_puts("Content-type: text/plain; charset=utf-8");
911                 serv_puts("Content-Transfer-Encoding: quoted-printable");
912                 serv_puts("");
913                 txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
914                 text_to_server_qp(txtmail);     /* Transmit message in quoted-printable encoding */
915                 free(txtmail);
916
917                 serv_printf("--%s", alt_boundary);
918         }
919
920         serv_puts("Content-type: text/html; charset=utf-8");
921         serv_puts("Content-Transfer-Encoding: quoted-printable");
922         serv_puts("");
923         serv_puts("<html><body>\r\n");
924         text_to_server_qp(bstr("msgtext"));     /* Transmit message in quoted-printable encoding */
925         serv_puts("</body></html>\r\n");
926
927         if (include_text_alt) {
928                 serv_printf("--%s--", alt_boundary);
929         }
930         
931         if (is_multipart) {
932                 long len;
933                 const char *Key; 
934                 void *vAtt;
935                 HashPos  *it;
936
937                 /* Add in the attachments */
938                 it = GetNewHashPos(WCC->attachments, 0);
939                 while (GetNextHashPos(WCC->attachments, it, &len, &Key, &vAtt)) {
940                         att = (wc_mime_attachment *)vAtt;
941                         if (att->length == 0)
942                                 continue;
943                         encoded_length = ((att->length * 150) / 100);
944                         encoded = malloc(encoded_length);
945                         if (encoded == NULL) break;
946                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
947
948                         serv_printf("--%s", top_boundary);
949                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
950                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
951                         serv_puts("Content-transfer-encoding: base64");
952                         serv_puts("");
953                         serv_write(encoded, encoded_strlen);
954                         serv_puts("");
955                         serv_puts("");
956                         free(encoded);
957                 }
958                 serv_printf("--%s--", top_boundary);
959                 DeleteHashPos(&it);
960         }
961
962         serv_puts("000");
963 }
964
965
966 /*
967  * Post message (or don't post message)
968  *
969  * Note regarding the "dont_post" variable:
970  * A random value (actually, it's just a timestamp) is inserted as a hidden
971  * field called "postseq" when the display_enter page is generated.  This
972  * value is checked when posting, using the static variable dont_post.  If a
973  * user attempts to post twice using the same dont_post value, the message is
974  * discarded.  This prevents the accidental double-saving of the same message
975  * if the user happens to click the browser "back" button.
976  */
977 void post_message(void)
978 {
979         StrBuf *UserName;
980         StrBuf *EmailAddress;
981         StrBuf *EncBuf;
982         char buf[1024];
983         StrBuf *encoded_subject = NULL;
984         static long dont_post = (-1L);
985         wc_mime_attachment  *att;
986         int is_anonymous = 0;
987         const StrBuf *display_name = NULL;
988         wcsession *WCC = WC;
989         StrBuf *Buf;
990         
991         if (havebstr("force_room")) {
992                 gotoroom(sbstr("force_room"));
993         }
994
995         if (havebstr("display_name")) {
996                 display_name = sbstr("display_name");
997                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
998                         display_name = NULL;
999                         is_anonymous = 1;
1000                 }
1001         }
1002
1003         if (WCC->upload_length > 0) {
1004                 const char *pch;
1005                 int n;
1006                 const char *newn;
1007                 long newnlen;
1008                 void *v;
1009
1010                 /* There's an attachment.  Save it to this struct... */
1011                 lprintf(9, "Client is uploading %d bytes\n", WCC->upload_length);
1012                 att = malloc(sizeof(wc_mime_attachment));
1013                 memset(att, 0, sizeof(wc_mime_attachment ));
1014                 att->length = WCC->upload_length;
1015                 att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1016                 att->FileName = NewStrBufPlain(WCC->upload_filename, -1);
1017                 
1018                 if (WCC->attachments == NULL) {
1019                         WCC->attachments = NewHash(1, Flathash);
1020                 }
1021
1022                 /* And add it to the list. */
1023                 n = 0;
1024                 if ((GetCount(WCC->attachments) > 0) && 
1025                     GetHashAt(WCC->attachments, 
1026                               GetCount(WCC->attachments) -1, 
1027                               &newnlen, &newn, &v))
1028                     n = *((int*) newn) + 1;
1029                 Put(WCC->attachments, IKEY(n), att, DestroyMime);
1030
1031                 /*
1032                  * Mozilla sends a simple filename, which is what we want,
1033                  * but Satan's Browser sends an entire pathname.  Reduce
1034                  * the path to just a filename if we need to.
1035                  */
1036                 pch = strrchr(ChrPtr(att->FileName), '/');
1037                 if (pch != NULL) {
1038                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1039                 }
1040                 pch = strrchr(ChrPtr(att->FileName), '\\');
1041                 if (pch != NULL) {
1042                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1043                 }
1044
1045                 /*
1046                  * Transfer control of this memory from the upload struct
1047                  * to the attachment struct.
1048                  */
1049                 att->Data = WCC->upload;
1050                 WCC->upload = NULL;
1051                 WCC->upload_length = 0;
1052                 display_enter();
1053                 return;
1054         }
1055
1056         if (havebstr("cancel_button")) {
1057                 sprintf(WCC->ImportantMessage, 
1058                         _("Cancelled.  Message was not posted."));
1059         } else if (havebstr("attach_button")) {
1060                 display_enter();
1061                 return;
1062         } else if (lbstr("postseq") == dont_post) {
1063                 sprintf(WCC->ImportantMessage, 
1064                         _("Automatically cancelled because you have already "
1065                           "saved this message."));
1066         } else if (havebstr("remove_attach_button")) {
1067                 /* now thats st00pit. need to find it by name. */
1068                 void *vAtt;
1069                 StrBuf *WhichAttachment;
1070                 HashPos *at;
1071                 long len;
1072                 const char *key;
1073
1074                 WhichAttachment = NewStrBufDup(sbstr("which_attachment"));
1075                 StrBufUnescape(WhichAttachment, 0);
1076                 at = GetNewHashPos(WCC->attachments, 0);
1077                 do {
1078                         GetHashPos(WCC->attachments, at, &len, &key, &vAtt);
1079                 
1080                         att = (wc_mime_attachment*) vAtt;
1081                         if ((att != NULL) && 
1082                             (strcmp(ChrPtr(WhichAttachment), 
1083                                     ChrPtr(att->FileName)   ) == 0))
1084                         {
1085                                 DeleteEntryFromHash(WCC->attachments, at);
1086                                 break;
1087                         }
1088                 }
1089                 while (NextHashPos(WCC->attachments, at));
1090                 FreeStrBuf(&WhichAttachment);
1091                 display_enter();
1092                 return;
1093         } else {
1094                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1095                 StrBuf *Recp = NULL; 
1096                 StrBuf *Cc = NULL;
1097                 StrBuf *Bcc = NULL;
1098                 const StrBuf *Wikipage = NULL;
1099                 const StrBuf *my_email_addr = NULL;
1100                 StrBuf *CmdBuf = NULL;
1101                 StrBuf *references = NULL;
1102                 int save_to_drafts;
1103                 long HeaderLen;
1104
1105                 save_to_drafts = havebstr("save_button");
1106                 Buf = NewStrBuf();
1107
1108                 if (save_to_drafts) {
1109                         /* temporarily change to the drafts room */
1110                         serv_puts("GOTO _DRAFTS_");
1111                         StrBuf_ServGetln(Buf);
1112                         if (GetServerStatus(Buf, NULL) != 2) {
1113                                 /* You probably don't even have a dumb Drafts folder */
1114                                 StrBufCutLeft(Buf, 4);
1115                                 lprintf(9, "%s:%d: server save to drafts error: %s\n", __FILE__, __LINE__, ChrPtr(Buf));
1116                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Saved to Drafts failed: "), -1, 0);
1117                                 StrBufAppendBuf(WCC->ImportantMsg, Buf, 0);
1118                                 display_enter();
1119                                 FreeStrBuf(&Buf);
1120                                 return;
1121                         }
1122                 }
1123
1124                 if (havebstr("references"))
1125                 {
1126                         const StrBuf *ref = sbstr("references");
1127                         references = NewStrBufDup(ref);
1128                         if (*ChrPtr(references) == '|') {       /* remove leading '|' if present */
1129                                 StrBufCutLeft(references, 1);
1130                         }
1131                         StrBufReplaceChars(references, '|', '!');
1132                 }
1133                 if (havebstr("subject")) {
1134                         const StrBuf *Subj;
1135                         /*
1136                          * make enough room for the encoded string; 
1137                          * plus the QP header 
1138                          */
1139                         Subj = sbstr("subject");
1140                         
1141                         StrBufRFC2047encode(&encoded_subject, Subj);
1142                 }
1143                 UserName = NewStrBuf();
1144                 EmailAddress = NewStrBuf();
1145                 EncBuf = NewStrBuf();
1146
1147                 Recp = StrBufSanitizeEmailRecipientVector(sbstr("recp"), UserName, EmailAddress, EncBuf);
1148                 Cc = StrBufSanitizeEmailRecipientVector(sbstr("cc"), UserName, EmailAddress, EncBuf);
1149                 Bcc = StrBufSanitizeEmailRecipientVector(sbstr("bcc"), UserName, EmailAddress, EncBuf);
1150
1151                 FreeStrBuf(&UserName);
1152                 FreeStrBuf(&EmailAddress);
1153                 FreeStrBuf(&EncBuf);
1154
1155                 Wikipage = sbstr("page");
1156                 my_email_addr = sbstr("my_email_addr");
1157                 
1158                 HeaderLen = StrLength(Recp) + 
1159                         StrLength(encoded_subject) +
1160                         StrLength(Cc) +
1161                         StrLength(Bcc) + 
1162                         StrLength(Wikipage) +
1163                         StrLength(my_email_addr) + 
1164                         StrLength(references);
1165                 CmdBuf = NewStrBufPlain(NULL, sizeof (CMD) + HeaderLen);
1166                 StrBufPrintf(CmdBuf, 
1167                              CMD,
1168                              save_to_drafts?"":ChrPtr(Recp),
1169                              is_anonymous,
1170                              ChrPtr(encoded_subject),
1171                              ChrPtr(display_name),
1172                              save_to_drafts?"":ChrPtr(Cc),
1173                              save_to_drafts?"":ChrPtr(Bcc),
1174                              ChrPtr(Wikipage),
1175                              ChrPtr(my_email_addr),
1176                              ChrPtr(references));
1177                 FreeStrBuf(&references);
1178                 FreeStrBuf(&encoded_subject);
1179
1180                 if ((HeaderLen + StrLength(sbstr("msgtext")) < 10) && 
1181                     (GetCount(WCC->attachments) == 0)){
1182                         StrBufAppendBufPlain(WCC->ImportantMsg, _("Refusing to post empty message.\n"), -1, 0);
1183                         FreeStrBuf(&CmdBuf);
1184                                 
1185                 }
1186                 else 
1187                 {
1188                         lprintf(9, "%s\n", ChrPtr(CmdBuf));
1189                         serv_puts(ChrPtr(CmdBuf));
1190                         FreeStrBuf(&CmdBuf);
1191
1192                         StrBuf_ServGetln(Buf);
1193                         if (GetServerStatus(Buf, NULL) == 4) {
1194                                 if (save_to_drafts) {
1195                                         if (  (havebstr("recp"))
1196                                               || (havebstr("cc"  ))
1197                                               || (havebstr("bcc" )) ) {
1198                                                 /* save recipient headers or room to post to */
1199                                                 serv_printf("To: %s", ChrPtr(Recp));
1200                                                 serv_printf("Cc: %s", ChrPtr(Cc));
1201                                                 serv_printf("Bcc: %s", ChrPtr(Bcc));
1202                                         } else {
1203                                                 serv_printf("X-Citadel-Room: %s", ChrPtr(WC->CurRoom.name));
1204                                         }
1205                                 }
1206                                 post_mime_to_server();
1207                                 if (save_to_drafts) {
1208                                         StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been saved to Drafts.\n"), -1, 0);
1209                                         gotoroom(WCC->CurRoom.name);
1210                                         display_enter();
1211                                         FreeStrBuf(&Buf);
1212                                         return;
1213                                 } else if (  (havebstr("recp"))
1214                                              || (havebstr("cc"  ))
1215                                              || (havebstr("bcc" ))
1216                                         ) {
1217                                         StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been sent.\n"), -1, 0);
1218                                 }
1219                                 else {
1220                                         StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been posted.\n"), -1, 0);
1221                                 }
1222                                 dont_post = lbstr("postseq");
1223                         } else {
1224                                 StrBufCutLeft(Buf, 4);
1225
1226                                 lprintf(9, "%s:%d: server post error: %s\n", __FILE__, __LINE__, ChrPtr(Buf));
1227                                 StrBufAppendBuf(WCC->ImportantMsg, Buf, 0);
1228                                 if (save_to_drafts) gotoroom(WCC->CurRoom.name);
1229                                 display_enter();
1230                                 FreeStrBuf(&Buf);
1231                                 FreeStrBuf(&Cc);
1232                                 FreeStrBuf(&Bcc);
1233                                 return;
1234                         }
1235                 }
1236                 FreeStrBuf(&Buf);
1237                 FreeStrBuf(&Cc);
1238                 FreeStrBuf(&Bcc);
1239         }
1240
1241         DeleteHash(&WCC->attachments);
1242
1243         /*
1244          *  We may have been supplied with instructions regarding the location
1245          *  to which we must return after posting.  If found, go there.
1246          */
1247         if (havebstr("return_to")) {
1248                 http_redirect(bstr("return_to"));
1249         }
1250         /*
1251          *  If we were editing a page in a wiki room, go to that page now.
1252          */
1253         else if (havebstr("page")) {
1254                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("page"));
1255                 http_redirect(buf);
1256         }
1257         /*
1258          *  Otherwise, just go to the "read messages" loop.
1259          */
1260         else {
1261                 readloop(readnew, eUseDefault);
1262         }
1263 }
1264
1265
1266
1267
1268 /*
1269  * display the message entry screen
1270  */
1271 void display_enter(void)
1272 {
1273         char buf[SIZ];
1274         long now;
1275         const StrBuf *display_name = NULL;
1276         int recipient_required = 0;
1277         int subject_required = 0;
1278         int recipient_bad = 0;
1279         int is_anonymous = 0;
1280         wcsession *WCC = WC;
1281
1282         now = time(NULL);
1283
1284         if (havebstr("force_room")) {
1285                 gotoroom(sbstr("force_room"));
1286         }
1287
1288         display_name = sbstr("display_name");
1289         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1290                 display_name = NULL;
1291                 is_anonymous = 1;
1292         }
1293
1294         /* First test to see whether this is a room that requires recipients to be entered */
1295         serv_puts("ENT0 0");
1296         serv_getln(buf, sizeof buf);
1297
1298         if (!strncmp(buf, "570", 3)) {          /* 570 means that we need a recipient here */
1299                 recipient_required = 1;
1300         }
1301         else if (buf[0] != '2') {               /* Any other error means that we cannot continue */
1302                 sprintf(WCC->ImportantMessage, "%s", &buf[4]);
1303                 readloop(readnew, eUseDefault);
1304                 return;
1305         }
1306
1307         /* Is the server strongly recommending that the user enter a message subject? */
1308         if ((buf[3] != '\0') && (buf[4] != '\0')) {
1309                 subject_required = extract_int(&buf[4], 1);
1310         }
1311
1312         /*
1313          * Are we perhaps in an address book view?  If so, then an "enter
1314          * message" command really means "add new entry."
1315          */
1316         if (WCC->CurRoom.defview == VIEW_ADDRESSBOOK) {
1317                 do_edit_vcard(-1, "", NULL, NULL, "",  ChrPtr(WCC->CurRoom.name));
1318                 return;
1319         }
1320
1321         /*
1322          * Are we perhaps in a calendar room?  If so, then an "enter
1323          * message" command really means "add new calendar item."
1324          */
1325         if (WCC->CurRoom.defview == VIEW_CALENDAR) {
1326                 display_edit_event();
1327                 return;
1328         }
1329
1330         /*
1331          * Are we perhaps in a tasks view?  If so, then an "enter
1332          * message" command really means "add new task."
1333          */
1334         if (WCC->CurRoom.defview == VIEW_TASKS) {
1335                 display_edit_task();
1336                 return;
1337         }
1338
1339         /*
1340          * Otherwise proceed normally.
1341          * Do a custom room banner with no navbar...
1342          */
1343
1344         if (recipient_required) {
1345                 const StrBuf *Recp = NULL; 
1346                 const StrBuf *Cc = NULL;
1347                 const StrBuf *Bcc = NULL;
1348                 const StrBuf *Wikipage = NULL;
1349                 StrBuf *CmdBuf = NULL;
1350                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1351                 
1352                 Recp = sbstr("recp");
1353                 Cc = sbstr("cc");
1354                 Bcc = sbstr("bcc");
1355                 Wikipage = sbstr("page");
1356                 
1357                 CmdBuf = NewStrBufPlain(NULL, 
1358                                         sizeof (CMD) + 
1359                                         StrLength(Recp) + 
1360                                         StrLength(display_name) +
1361                                         StrLength(Cc) +
1362                                         StrLength(Bcc) + 
1363                                         StrLength(Wikipage));
1364
1365                 StrBufPrintf(CmdBuf, 
1366                              CMD,
1367                              ChrPtr(Recp), 
1368                              is_anonymous,
1369                              ChrPtr(display_name),
1370                              ChrPtr(Cc), 
1371                              ChrPtr(Bcc), 
1372                              ChrPtr(Wikipage));
1373                 serv_puts(ChrPtr(CmdBuf));
1374                 serv_getln(buf, sizeof buf);
1375                 FreeStrBuf(&CmdBuf);
1376
1377                 if (!strncmp(buf, "570", 3)) {  /* 570 means we have an invalid recipient listed */
1378                         if (havebstr("recp") && 
1379                             havebstr("cc"  ) && 
1380                             havebstr("bcc" )) {
1381                                 recipient_bad = 1;
1382                         }
1383                 }
1384                 else if (buf[0] != '2') {       /* Any other error means that we cannot continue */
1385                         wc_printf("<em>%s</em><br />\n", &buf[4]);      /* TODO -> important message */
1386                         return;
1387                 }
1388         }
1389         svputlong("RCPTREQUIRED", recipient_required);
1390         svputlong("SUBJREQUIRED", recipient_required || subject_required);
1391
1392         begin_burst();
1393         output_headers(1, 0, 0, 0, 1, 0);
1394         DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1395         end_burst();
1396
1397         return;
1398 }
1399
1400 /*
1401  * delete a message
1402  */
1403 void delete_msg(void)
1404 {
1405         long msgid;
1406         char buf[SIZ];
1407
1408         msgid = lbstr("msgid");
1409
1410         if ((WC->CurRoom.RAFlags & UA_ISTRASH) != 0) {  /* Delete from Trash is a real delete */
1411                 serv_printf("DELE %ld", msgid); 
1412         }
1413         else {                  /* Otherwise move it to Trash */
1414                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1415         }
1416
1417         serv_getln(buf, sizeof buf);
1418         sprintf(WC->ImportantMessage, "%s", &buf[4]);
1419         readloop(readnew, eUseDefault);
1420 }
1421
1422
1423 /*
1424  * move a message to another room
1425  */
1426 void move_msg(void)
1427 {
1428         long msgid;
1429         char buf[SIZ];
1430
1431         msgid = lbstr("msgid");
1432
1433         if (havebstr("move_button")) {
1434                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
1435                 serv_puts(buf);
1436                 serv_getln(buf, sizeof buf);
1437                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
1438         } else {
1439                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
1440         }
1441
1442         readloop(readnew, eUseDefault);
1443 }
1444
1445
1446 /*
1447  * Confirm move of a message
1448  */
1449 void confirm_move_msg(void)
1450 {
1451         long msgid;
1452         char buf[SIZ];
1453         char targ[SIZ];
1454
1455         msgid = lbstr("msgid");
1456
1457
1458         output_headers(1, 1, 2, 0, 0, 0);
1459         wc_printf("<div id=\"banner\">\n");
1460         wc_printf("<h1>");
1461         wc_printf(_("Confirm move of message"));
1462         wc_printf("</h1>");
1463         wc_printf("</div>\n");
1464
1465         wc_printf("<div id=\"content\" class=\"service\">\n");
1466
1467         wc_printf("<CENTER>");
1468
1469         wc_printf(_("Move this message to:"));
1470         wc_printf("<br />\n");
1471
1472         wc_printf("<form METHOD=\"POST\" action=\"move_msg\">\n");
1473         wc_printf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
1474         wc_printf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
1475
1476         wc_printf("<SELECT NAME=\"target_room\" SIZE=5>\n");
1477         serv_puts("LKRA");
1478         serv_getln(buf, sizeof buf);
1479         if (buf[0] == '1') {
1480                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1481                         extract_token(targ, buf, 0, '|', sizeof targ);
1482                         wc_printf("<OPTION>");
1483                         escputs(targ);
1484                         wc_printf("\n");
1485                 }
1486         }
1487         wc_printf("</SELECT>\n");
1488         wc_printf("<br />\n");
1489
1490         wc_printf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
1491         wc_printf("&nbsp;");
1492         wc_printf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
1493         wc_printf("</form></CENTER>\n");
1494
1495         wc_printf("</CENTER>\n");
1496         wDumpContent(1);
1497 }
1498
1499
1500 /*
1501  * Generic function to output an arbitrary MIME attachment from
1502  * message being composed
1503  *
1504  * partnum              The MIME part to be output
1505  * filename             Fake filename to give
1506  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1507  */
1508 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1509 {
1510         void *vPart;
1511         StrBuf *content_type;
1512         wc_mime_attachment *part;
1513         int i;
1514
1515         i = StrToi(partnum);
1516         if (GetHash(WC->attachments, IKEY(i), &vPart) &&
1517             (vPart != NULL)) {
1518                 part = (wc_mime_attachment*) vPart;
1519                 if (force_download) {
1520                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1521                 }
1522                 else {
1523                         content_type = NewStrBufDup(part->ContentType);
1524                 }
1525                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1526                 http_transmit_thing(ChrPtr(content_type), 0);
1527         } else {
1528                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1529                 output_headers(0, 0, 0, 0, 0, 0);
1530                 hprintf("Content-Type: text/plain\r\n");
1531                 begin_burst();
1532                 wc_printf(_("An error occurred while retrieving this part: %s/%s\n"), 
1533                         ChrPtr(partnum), ChrPtr(filename));
1534                 end_burst();
1535         }
1536         FreeStrBuf(&content_type);
1537 }
1538
1539
1540 /*
1541  * Generic function to output an arbitrary MIME part from an arbitrary
1542  * message number on the server.
1543  *
1544  * msgnum               Number of the item on the citadel server
1545  * partnum              The MIME part to be output
1546  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1547  */
1548 void mimepart(int force_download)
1549 {
1550         long msgnum;
1551         StrBuf *att;
1552         wcsession *WCC = WC;
1553         StrBuf *Buf;
1554         off_t bytes;
1555         StrBuf *ContentType = NewStrBufPlain(HKEY("application/octet-stream"));
1556         const char *CT;
1557
1558         att = Buf = NewStrBuf();
1559         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
1560         StrBufExtract_token(att, WCC->Hdr->HR.ReqLine, 1, '/');
1561
1562         serv_printf("OPNA %ld|%s", msgnum, ChrPtr(att));
1563         StrBuf_ServGetln(Buf);
1564         if (GetServerStatus(Buf, NULL) == 2) {
1565                 StrBufCutLeft(Buf, 4);
1566                 bytes = StrBufExtract_long(Buf, 0, '|');
1567                 if (!force_download) {
1568                         StrBufExtract_token(ContentType, Buf, 3, '|');
1569                 }
1570
1571                 serv_read_binary(WCC->WBuf, bytes, Buf);
1572                 serv_puts("CLOS");
1573                 StrBuf_ServGetln(Buf);
1574                 CT = ChrPtr(ContentType);
1575
1576                 if (!force_download) {
1577                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1578                                 StrBufExtract_token(Buf, WCC->Hdr->HR.ReqLine, 2, '/');
1579                                 CT = GuessMimeByFilename(SKEY(Buf));
1580                         }
1581                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1582                                 CT = GuessMimeType(SKEY(WCC->WBuf));
1583                         }
1584                 }
1585                 http_transmit_thing(CT, 0);
1586         } else {
1587                 StrBufCutLeft(Buf, 4);
1588                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(Buf));
1589                 output_headers(0, 0, 0, 0, 0, 0);
1590                 hprintf("Content-Type: text/plain\r\n");
1591                 begin_burst();
1592                 wc_printf(_("An error occurred while retrieving this part: %s\n"), 
1593                         ChrPtr(Buf));
1594                 end_burst();
1595         }
1596         FreeStrBuf(&ContentType);
1597         FreeStrBuf(&Buf);
1598 }
1599
1600
1601 /*
1602  * Read any MIME part of a message, from the server, into memory.
1603  */
1604 StrBuf *load_mimepart(long msgnum, char *partnum)
1605 {
1606         off_t bytes;
1607         StrBuf *Buf;
1608         
1609         Buf = NewStrBuf();
1610         serv_printf("DLAT %ld|%s", msgnum, partnum);
1611         StrBuf_ServGetln(Buf);
1612         if (GetServerStatus(Buf, NULL) == 6) {
1613                 StrBufCutLeft(Buf, 4);
1614                 bytes = StrBufExtract_long(Buf, 0, '|');
1615                 FreeStrBuf(&Buf);
1616                 Buf = NewStrBuf();
1617                 StrBuf_ServGetBLOBBuffered(Buf, bytes);
1618                 return(Buf);
1619         }
1620         else {
1621                 FreeStrBuf(&Buf);
1622                 return(NULL);
1623         }
1624 }
1625
1626 /*
1627  * Read any MIME part of a message, from the server, into memory.
1628  */
1629 void MimeLoadData(wc_mime_attachment *Mime)
1630 {
1631         StrBuf *Buf;
1632         const char *Ptr;
1633         off_t bytes;
1634         /* TODO: is there a chance the content type is different from the one we know? */
1635
1636         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1637         Buf = NewStrBuf();
1638         StrBuf_ServGetln(Buf);
1639         if (GetServerStatus(Buf, NULL) == 6) {
1640                 Ptr = &(ChrPtr(Buf)[4]);
1641                 bytes = StrBufExtractNext_long(Buf, &Ptr, '|');
1642                 StrBufSkip_NTokenS(Buf, &Ptr, '|', 3);  /* filename, cbtype, mimetype */
1643                 if (Mime->Charset == NULL) Mime->Charset = NewStrBuf();
1644                 StrBufExtract_NextToken(Mime->Charset, Buf, &Ptr, '|');
1645                 
1646                 if (Mime->Data == NULL)
1647                         Mime->Data = NewStrBufPlain(NULL, bytes);
1648                 StrBuf_ServGetBLOBBuffered(Mime->Data, bytes);
1649         }
1650         else {
1651                 FlushStrBuf(Mime->Data);
1652                 /* TODO XImportant message */
1653         }
1654         FreeStrBuf(&Buf);
1655 }
1656
1657
1658
1659
1660 void view_mimepart(void) {
1661         mimepart(0);
1662 }
1663
1664 void download_mimepart(void) {
1665         mimepart(1);
1666 }
1667
1668 void view_postpart(void) {
1669         StrBuf *filename = NewStrBuf();
1670         StrBuf *partnum = NewStrBuf();
1671
1672         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1673         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1674
1675         postpart(partnum, filename, 0);
1676
1677         FreeStrBuf(&filename);
1678         FreeStrBuf(&partnum);
1679 }
1680
1681 void download_postpart(void) {
1682         StrBuf *filename = NewStrBuf();
1683         StrBuf *partnum = NewStrBuf();
1684
1685         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1686         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1687
1688         postpart(partnum, filename, 1);
1689
1690         FreeStrBuf(&filename);
1691         FreeStrBuf(&partnum);
1692 }
1693
1694 void h_readnew(void) { readloop(readnew, eUseDefault);}
1695 void h_readold(void) { readloop(readold, eUseDefault);}
1696 void h_readfwd(void) { readloop(readfwd, eUseDefault);}
1697 void h_headers(void) { readloop(headers, eUseDefault);}
1698 void h_do_search(void) { readloop(do_search, eUseDefault);}
1699 void h_readgt(void) { readloop(readgt, eUseDefault);}
1700 void h_readlt(void) { readloop(readlt, eUseDefault);}
1701
1702 void jsonMessageListHdr(void) 
1703 {
1704         /* TODO: make a generic function */
1705         hprintf("HTTP/1.1 200 OK\r\n");
1706         hprintf("Content-type: application/json; charset=utf-8\r\n");
1707         hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
1708         hprintf("Connection: close\r\n");
1709         hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
1710         begin_burst();
1711 }
1712
1713
1714 /* Output message list in JSON format */
1715 void jsonMessageList(void) {
1716         const StrBuf *room = sbstr("room");
1717         long oper = (havebstr("query")) ? do_search : readnew;
1718         WC->is_ajax = 1; 
1719         gotoroom(room);
1720         readloop(oper, eUseDefault);
1721         WC->is_ajax = 0;
1722 }
1723
1724 void RegisterReadLoopHandlerset(
1725         int RoomType,
1726         GetParamsGetServerCall_func GetParamsGetServerCall,
1727         PrintViewHeader_func PrintViewHeader,
1728         load_msg_ptrs_detailheaders LH,
1729         LoadMsgFromServer_func LoadMsgFromServer,
1730         RenderView_or_Tail_func RenderView_or_Tail,
1731         View_Cleanup_func ViewCleanup
1732         )
1733 {
1734         RoomRenderer *Handler;
1735
1736         Handler = (RoomRenderer*) malloc(sizeof(RoomRenderer));
1737
1738         Handler->RoomType = RoomType;
1739         Handler->GetParamsGetServerCall = GetParamsGetServerCall;
1740         Handler->PrintViewHeader = PrintViewHeader;
1741         Handler->LoadMsgFromServer = LoadMsgFromServer;
1742         Handler->RenderView_or_Tail = RenderView_or_Tail;
1743         Handler->ViewCleanup = ViewCleanup;
1744         Handler->LHParse = LH;
1745
1746         Put(ReadLoopHandler, IKEY(RoomType), Handler, NULL);
1747 }
1748
1749 void 
1750 InitModule_MSG
1751 (void)
1752 {
1753         RegisterPreference("use_sig",
1754                            _("Attach signature to email messages?"), 
1755                            PRF_YESNO, 
1756                            NULL);
1757         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
1758         RegisterPreference("default_header_charset", 
1759                            _("Default character set for email headers:"), 
1760                            PRF_STRING, 
1761                            NULL);
1762         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
1763         RegisterPreference("defaultname", 
1764                            _("Preferred display name for email messages"), 
1765                            PRF_STRING, 
1766                            NULL);
1767         RegisterPreference("defaulthandle", 
1768                            _("Preferred display name for bulletin board posts"), 
1769                            PRF_STRING, 
1770                            NULL);
1771         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
1772
1773         WebcitAddUrlHandler(HKEY("readnew"), "", 0, h_readnew, NEED_URL);
1774         WebcitAddUrlHandler(HKEY("readold"), "", 0, h_readold, NEED_URL);
1775         WebcitAddUrlHandler(HKEY("readfwd"), "", 0, h_readfwd, NEED_URL);
1776         WebcitAddUrlHandler(HKEY("headers"), "", 0, h_headers, NEED_URL);
1777         WebcitAddUrlHandler(HKEY("readgt"), "", 0, h_readgt, NEED_URL);
1778         WebcitAddUrlHandler(HKEY("readlt"), "", 0, h_readlt, NEED_URL);
1779         WebcitAddUrlHandler(HKEY("do_search"), "", 0, h_do_search, 0);
1780         WebcitAddUrlHandler(HKEY("display_enter"), "", 0, display_enter, 0);
1781         WebcitAddUrlHandler(HKEY("post"), "", 0, post_message, PROHIBIT_STARTPAGE);
1782         WebcitAddUrlHandler(HKEY("move_msg"), "", 0, move_msg, PROHIBIT_STARTPAGE);
1783         WebcitAddUrlHandler(HKEY("delete_msg"), "", 0, delete_msg, PROHIBIT_STARTPAGE);
1784         WebcitAddUrlHandler(HKEY("confirm_move_msg"), "", 0, confirm_move_msg, PROHIBIT_STARTPAGE);
1785         WebcitAddUrlHandler(HKEY("msg"), "", 0, embed_message, NEED_URL);
1786         WebcitAddUrlHandler(HKEY("message"), "", 0, handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1787         WebcitAddUrlHandler(HKEY("printmsg"), "", 0, print_message, NEED_URL);
1788         WebcitAddUrlHandler(HKEY("mobilemsg"), "", 0, mobile_message_view, NEED_URL);
1789         WebcitAddUrlHandler(HKEY("msgheaders"), "", 0, display_headers, NEED_URL);
1790
1791         WebcitAddUrlHandler(HKEY("mimepart"), "", 0, view_mimepart, NEED_URL);
1792         WebcitAddUrlHandler(HKEY("mimepart_download"), "", 0, download_mimepart, NEED_URL);
1793         WebcitAddUrlHandler(HKEY("postpart"), "", 0, view_postpart, NEED_URL|PROHIBIT_STARTPAGE);
1794         WebcitAddUrlHandler(HKEY("postpart_download"), "", 0, download_postpart, NEED_URL|PROHIBIT_STARTPAGE);
1795
1796         /* json */
1797         WebcitAddUrlHandler(HKEY("roommsgs"), "", 0, jsonMessageList,0);
1798         return ;
1799 }
1800
1801 void
1802 SessionDetachModule_MSG
1803 (wcsession *sess)
1804 {
1805         DeleteHash(&sess->summ);
1806 }