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