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