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