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