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