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