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