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