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