sync with 0.8.11cvs16
[claws.git] / src / procmsg.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #include "defs.h"
21
22 #include <glib.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25
26 #include "intl.h"
27 #include "main.h"
28 #include "utils.h"
29 #include "procmsg.h"
30 #include "procheader.h"
31 #include "send_message.h"
32 #include "procmime.h"
33 #include "statusbar.h"
34 #include "folder.h"
35 #include "prefs_common.h"
36 #include "account.h"
37 #if USE_GPGME
38 #  include "rfc2015.h"
39 #endif
40 #include "alertpanel.h"
41 #include "news.h"
42 #include "hooks.h"
43 #include "msgcache.h"
44
45 typedef struct _FlagInfo        FlagInfo;
46
47 struct _FlagInfo
48 {
49         guint    msgnum;
50         MsgFlags flags;
51 };
52
53 GHashTable *procmsg_msg_hash_table_create(GSList *mlist)
54 {
55         GHashTable *msg_table;
56
57         if (mlist == NULL) return NULL;
58
59         msg_table = g_hash_table_new(NULL, g_direct_equal);
60         procmsg_msg_hash_table_append(msg_table, mlist);
61
62         return msg_table;
63 }
64
65 void procmsg_msg_hash_table_append(GHashTable *msg_table, GSList *mlist)
66 {
67         GSList *cur;
68         MsgInfo *msginfo;
69
70         if (msg_table == NULL || mlist == NULL) return;
71
72         for (cur = mlist; cur != NULL; cur = cur->next) {
73                 msginfo = (MsgInfo *)cur->data;
74
75                 g_hash_table_insert(msg_table,
76                                     GUINT_TO_POINTER(msginfo->msgnum),
77                                     msginfo);
78         }
79 }
80
81 GHashTable *procmsg_to_folder_hash_table_create(GSList *mlist)
82 {
83         GHashTable *msg_table;
84         GSList *cur;
85         MsgInfo *msginfo;
86
87         if (mlist == NULL) return NULL;
88
89         msg_table = g_hash_table_new(NULL, g_direct_equal);
90
91         for (cur = mlist; cur != NULL; cur = cur->next) {
92                 msginfo = (MsgInfo *)cur->data;
93                 g_hash_table_insert(msg_table, msginfo->to_folder, msginfo);
94         }
95
96         return msg_table;
97 }
98
99 gint procmsg_get_last_num_in_msg_list(GSList *mlist)
100 {
101         GSList *cur;
102         MsgInfo *msginfo;
103         gint last = 0;
104
105         for (cur = mlist; cur != NULL; cur = cur->next) {
106                 msginfo = (MsgInfo *)cur->data;
107                 if (msginfo && msginfo->msgnum > last)
108                         last = msginfo->msgnum;
109         }
110
111         return last;
112 }
113
114 void procmsg_msg_list_free(GSList *mlist)
115 {
116         GSList *cur;
117         MsgInfo *msginfo;
118
119         for (cur = mlist; cur != NULL; cur = cur->next) {
120                 msginfo = (MsgInfo *)cur->data;
121                 procmsg_msginfo_free(msginfo);
122         }
123         g_slist_free(mlist);
124 }
125
126 struct MarkSum {
127         gint *new;
128         gint *unread;
129         gint *total;
130         gint *min;
131         gint *max;
132         gint first;
133 };
134
135 static gboolean procmsg_ignore_node(GNode *node, gpointer data)
136 {
137         MsgInfo *msginfo = (MsgInfo *)node->data;
138         
139         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
140         procmsg_msginfo_set_flags(msginfo, MSG_IGNORE_THREAD, 0);
141
142         return FALSE;
143 }
144
145 /* return the reversed thread tree */
146 GNode *procmsg_get_thread_tree(GSList *mlist)
147 {
148         GNode *root, *parent, *node, *next;
149         GHashTable *msgid_table;
150         GHashTable *subject_table;
151         MsgInfo *msginfo;
152         const gchar *msgid;
153         const gchar *subject;
154         GNode *found_subject;
155
156         root = g_node_new(NULL);
157         msgid_table = g_hash_table_new(g_str_hash, g_str_equal);
158         subject_table = g_hash_table_new(g_str_hash, g_str_equal);
159
160         for (; mlist != NULL; mlist = mlist->next) {
161                 msginfo = (MsgInfo *)mlist->data;
162                 parent = root;
163
164                 if (msginfo->inreplyto) {
165                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
166                         if (parent == NULL) {
167                                 parent = root;
168                         } else {
169                                 if (MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
170                                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
171                                         procmsg_msginfo_set_flags(msginfo, MSG_IGNORE_THREAD, 0);
172                                 }
173                         }
174                 }
175                 node = g_node_insert_data_before
176                         (parent, parent == root ? parent->children : NULL,
177                          msginfo);
178                 if ((msgid = msginfo->msgid) &&
179                     g_hash_table_lookup(msgid_table, msgid) == NULL)
180                         g_hash_table_insert(msgid_table, (gchar *)msgid, node);
181
182                 if (prefs_common.thread_by_subject) {
183                         subject = msginfo->subject;
184                         found_subject = subject_table_lookup(subject_table,
185                                                              (gchar *) subject);
186                         if (found_subject == NULL)
187                                 subject_table_insert(subject_table, (gchar *) subject,
188                                                      node);
189                         else {
190                                 /* replace if msg in table is older than current one 
191                                  * can add here more stuff. */
192                                 if ( ((MsgInfo*)(found_subject->data))->date_t >
193                                      ((MsgInfo*)(node->data))->date_t )  {
194                                         subject_table_remove(subject_table, (gchar *) subject);
195                                         subject_table_insert(subject_table, (gchar *) subject, node);
196                                 }       
197                         }
198                 }
199         }
200
201         /* complete the unfinished threads */
202         for (node = root->children; node != NULL; ) {
203                 next = node->next;
204                 msginfo = (MsgInfo *)node->data;
205                 parent = NULL;
206                 if (msginfo->inreplyto) 
207                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
208                 if (parent && parent != node) {
209                         g_node_unlink(node);
210                         g_node_insert_before
211                                 (parent, parent->children, node);
212                         /* CLAWS: ignore thread */
213                         if (MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
214                                 g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, procmsg_ignore_node, NULL);
215                         }
216                 }
217                 node = next;
218         }
219
220         /* CLAWS: now see if the first level (below root) still has some nodes that can be
221          * threaded by subject line. we need to handle this in a special way to prevent
222          * circular reference from a node that has already been threaded by IN-REPLY-TO
223          * but is also in the subject line hash table */
224         if (prefs_common.thread_by_subject) {
225                 for (node = root->children; node != NULL; ) {
226                         next = node->next;
227                         msginfo = (MsgInfo *) node->data;
228                         parent = NULL;
229                         if (subject_is_reply(msginfo->subject)) {
230                                 parent = subject_table_lookup(subject_table,
231                                                               msginfo->subject);
232                                 /* the node may already be threaded by IN-REPLY-TO,
233                                    so go up in the tree to find the parent node */
234                                 if (parent != NULL) {
235                                         if (g_node_is_ancestor(node, parent))
236                                                 parent = NULL;
237                                         if (parent == node)
238                                                 parent = NULL;
239                                 }
240
241                                 if (parent) {
242                                         g_node_unlink(node);
243                                         g_node_append(parent, node);
244                                         /* CLAWS: ignore thread */
245                                         if (MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
246                                                 g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, procmsg_ignore_node, NULL);
247                                         }
248                                 }
249                         }                                       
250                         node = next;
251                 }       
252         }
253         
254         g_hash_table_destroy(subject_table);
255         g_hash_table_destroy(msgid_table);
256
257         return root;
258 }
259
260 void procmsg_move_messages(GSList *mlist)
261 {
262         GSList *cur, *movelist = NULL;
263         MsgInfo *msginfo;
264         FolderItem *dest = NULL;
265
266         if (!mlist) return;
267
268         folder_item_update_freeze();
269
270         for (cur = mlist; cur != NULL; cur = cur->next) {
271                 msginfo = (MsgInfo *)cur->data;
272                 if (!dest) {
273                         dest = msginfo->to_folder;
274                         movelist = g_slist_append(movelist, msginfo);
275                 } else if (dest == msginfo->to_folder) {
276                         movelist = g_slist_append(movelist, msginfo);
277                 } else {
278                         folder_item_move_msgs_with_dest(dest, movelist);
279                         g_slist_free(movelist);
280                         movelist = NULL;
281                         dest = msginfo->to_folder;
282                         movelist = g_slist_append(movelist, msginfo);
283                 }
284                 procmsg_msginfo_set_to_folder(msginfo, NULL);
285         }
286
287         if (movelist) {
288                 folder_item_move_msgs_with_dest(dest, movelist);
289                 g_slist_free(movelist);
290         }
291
292         folder_item_update_thaw();
293 }
294
295 void procmsg_copy_messages(GSList *mlist)
296 {
297         GSList *cur, *copylist = NULL;
298         MsgInfo *msginfo;
299         FolderItem *dest = NULL;
300
301         if (!mlist) return;
302
303         folder_item_update_freeze();
304
305         for (cur = mlist; cur != NULL; cur = cur->next) {
306                 msginfo = (MsgInfo *)cur->data;
307                 if (!dest) {
308                         dest = msginfo->to_folder;
309                         copylist = g_slist_append(copylist, msginfo);
310                 } else if (dest == msginfo->to_folder) {
311                         copylist = g_slist_append(copylist, msginfo);
312                 } else {
313                         folder_item_copy_msgs_with_dest(dest, copylist);
314                         g_slist_free(copylist);
315                         copylist = NULL;
316                         dest = msginfo->to_folder;
317                         copylist = g_slist_append(copylist, msginfo);
318                 }
319                 procmsg_msginfo_set_to_folder(msginfo, NULL);
320         }
321
322         if (copylist) {
323                 folder_item_copy_msgs_with_dest(dest, copylist);
324                 g_slist_free(copylist);
325         }
326
327         folder_item_update_thaw();
328 }
329
330 gchar *procmsg_get_message_file_path(MsgInfo *msginfo)
331 {
332         gchar *path, *file;
333
334         g_return_val_if_fail(msginfo != NULL, NULL);
335
336         if (msginfo->plaintext_file)
337                 file = g_strdup(msginfo->plaintext_file);
338         else {
339                 path = folder_item_get_path(msginfo->folder);
340                 file = g_strconcat(path, G_DIR_SEPARATOR_S,
341                                    itos(msginfo->msgnum), NULL);
342                 g_free(path);
343         }
344
345         return file;
346 }
347
348 gchar *procmsg_get_message_file(MsgInfo *msginfo)
349 {
350         gchar *filename = NULL;
351
352         g_return_val_if_fail(msginfo != NULL, NULL);
353
354         filename = folder_item_fetch_msg(msginfo->folder, msginfo->msgnum);
355         if (!filename)
356                 g_warning("can't fetch message %d\n", msginfo->msgnum);
357
358         return filename;
359 }
360
361 FILE *procmsg_open_message(MsgInfo *msginfo)
362 {
363         FILE *fp;
364         gchar *file;
365
366         g_return_val_if_fail(msginfo != NULL, NULL);
367
368         file = procmsg_get_message_file_path(msginfo);
369         g_return_val_if_fail(file != NULL, NULL);
370
371         if (!is_file_exist(file)) {
372                 g_free(file);
373                 file = procmsg_get_message_file(msginfo);
374                 g_return_val_if_fail(file != NULL, NULL);
375         }
376
377         if ((fp = fopen(file, "rb")) == NULL) {
378                 FILE_OP_ERROR(file, "fopen");
379                 g_free(file);
380                 return NULL;
381         }
382
383         g_free(file);
384
385         if (MSG_IS_QUEUED(msginfo->flags) || MSG_IS_DRAFT(msginfo->flags)) {
386                 gchar buf[BUFFSIZE];
387
388                 while (fgets(buf, sizeof(buf), fp) != NULL)
389                         if (buf[0] == '\r' || buf[0] == '\n') break;
390         }
391
392         return fp;
393 }
394
395 #if USE_GPGME
396 FILE *procmsg_open_message_decrypted(MsgInfo *msginfo, MimeInfo **mimeinfo)
397 {
398         FILE *fp;
399         MimeInfo *mimeinfo_;
400
401         g_return_val_if_fail(msginfo != NULL, NULL);
402
403         if (mimeinfo) *mimeinfo = NULL;
404
405         if ((fp = procmsg_open_message(msginfo)) == NULL) return NULL;
406
407         mimeinfo_ = procmime_scan_mime_header(fp);
408         if (!mimeinfo_) {
409                 fclose(fp);
410                 return NULL;
411         }
412
413         if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
414             rfc2015_is_encrypted(mimeinfo_)) {
415                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
416         }
417
418         if (MSG_IS_ENCRYPTED(msginfo->flags) &&
419             (!msginfo->plaintext_file || msginfo->decryption_failed)) {
420                 rfc2015_decrypt_message(msginfo, mimeinfo_, fp);
421                 if (msginfo->plaintext_file &&
422                     !msginfo->decryption_failed) {
423                         fclose(fp);
424                         procmime_mimeinfo_free_all(mimeinfo_);
425                         if ((fp = procmsg_open_message(msginfo)) == NULL)
426                                 return NULL;
427                         mimeinfo_ = procmime_scan_mime_header(fp);
428                         if (!mimeinfo_) {
429                                 fclose(fp);
430                                 return NULL;
431                         }
432                 }
433         }
434
435         if (mimeinfo) *mimeinfo = mimeinfo_;
436         return fp;
437 }
438 #endif
439
440 gboolean procmsg_msg_exist(MsgInfo *msginfo)
441 {
442         gchar *path;
443         gboolean ret;
444
445         if (!msginfo) return FALSE;
446
447         path = folder_item_get_path(msginfo->folder);
448         change_dir(path);
449         ret = !folder_item_is_msg_changed(msginfo->folder, msginfo);
450         g_free(path);
451
452         return ret;
453 }
454
455 void procmsg_empty_trash(void)
456 {
457         FolderItem *trash;
458         GList *cur;
459
460         for (cur = folder_get_list(); cur != NULL; cur = cur->next) {
461                 trash = FOLDER(cur->data)->trash;
462                 if (trash && trash->total > 0)
463                         folder_item_remove_all_msg(trash);
464         }
465 }
466
467 /*!
468  *\brief        Send messages in queue
469  *
470  *\param        queue Queue folder to process
471  *\param        save_msgs Unused
472  *
473  *\return       Number of messages sent, negative if an error occurred
474  *              positive if no error occurred
475  */
476 gint procmsg_send_queue(FolderItem *queue, gboolean save_msgs)
477 {
478         gint ret = 1, count = 0;
479         GSList *list, *elem;
480
481         if (!queue)
482                 queue = folder_get_default_queue();
483         g_return_val_if_fail(queue != NULL, -1);
484
485         folder_item_scan(queue);
486         list = folder_item_get_msg_list(queue);
487
488         for (elem = list; elem != NULL; elem = elem->next) {
489                 gchar *file;
490                 MsgInfo *msginfo;
491                 
492                 msginfo = (MsgInfo *)(elem->data);
493                 if (!MSG_IS_LOCKED(msginfo->flags)) {
494                         file = folder_item_fetch_msg(queue, msginfo->msgnum);
495                         if (file) {
496                                 if (procmsg_send_message_queue(file) < 0) {
497                                         g_warning("Sending queued message %d failed.\n", 
498                                                   msginfo->msgnum);
499                                         ret = -1;
500                                 } else {
501                                         /* CLAWS: 
502                                          * We save in procmsg_send_message_queue because
503                                          * we need the destination folder from the queue
504                                          * header
505                                                         
506                                         if (save_msgs)
507                                                 procmsg_save_to_outbox
508                                                         (queue->folder->outbox,
509                                                          file, TRUE);
510                                          */
511                                         count++; 
512                                         folder_item_remove_msg(queue, msginfo->msgnum);
513                                 }
514                                 g_free(file);
515                         }
516                 }
517                 /* FIXME: supposedly if only one message is locked, and queue
518                  * is being flushed, the following free says something like 
519                  * "freeing msg ## in folder (nil)". */
520                 procmsg_msginfo_free(msginfo);
521         }
522
523         return ret * count;
524 }
525
526 gint procmsg_remove_special_headers(const gchar *in, const gchar *out)
527 {
528         FILE *fp, *outfp;
529         gchar buf[BUFFSIZE];
530         
531         if ((fp = fopen(in, "rb")) == NULL) {
532                 FILE_OP_ERROR(in, "fopen");
533                 return -1;
534         }
535         if ((outfp = fopen(out, "wb")) == NULL) {
536                 FILE_OP_ERROR(out, "fopen");
537                 fclose(fp);
538                 return -1;
539         }
540         while (fgets(buf, sizeof(buf), fp) != NULL)
541                 if (buf[0] == '\r' || buf[0] == '\n') break;
542         while (fgets(buf, sizeof(buf), fp) != NULL)
543                 fputs(buf, outfp);
544         fclose(outfp);
545         fclose(fp);
546         return 0;
547
548 }
549 gint procmsg_save_to_outbox(FolderItem *outbox, const gchar *file,
550                             gboolean is_queued)
551 {
552         gint num;
553         MsgInfo *msginfo;
554
555         debug_print("saving sent message...\n");
556
557         if (!outbox)
558                 outbox = folder_get_default_outbox();
559         g_return_val_if_fail(outbox != NULL, -1);
560
561         /* remove queueing headers */
562         if (is_queued) {
563                 gchar tmp[MAXPATHLEN + 1];
564
565                 g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.out.%08x",
566                            get_rc_dir(), G_DIR_SEPARATOR, (guint)random());
567                 
568                 if (procmsg_remove_special_headers(file, tmp) !=0)
569                         return -1;
570
571                 folder_item_scan(outbox);
572                 if ((num = folder_item_add_msg(outbox, tmp, TRUE)) < 0) {
573                         g_warning("can't save message\n");
574                         unlink(tmp);
575                         return -1;
576                 }
577         } else {
578                 folder_item_scan(outbox);
579                 if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
580                         g_warning("can't save message\n");
581                         return -1;
582                 }
583                 return -1;
584         }
585         msginfo = folder_item_get_msginfo(outbox, num);
586         if (msginfo != NULL) {
587             procmsg_msginfo_unset_flags(msginfo, ~0, 0);
588             procmsg_msginfo_free(msginfo);
589         }
590         folder_item_update(outbox, TRUE);
591
592         return 0;
593 }
594
595 void procmsg_print_message(MsgInfo *msginfo, const gchar *cmdline)
596 {
597         static const gchar *def_cmd = "lpr %s";
598         static guint id = 0;
599         gchar *prtmp;
600         FILE *tmpfp, *prfp;
601         gchar buf[1024];
602         gchar *p;
603
604         g_return_if_fail(msginfo);
605
606         if ((tmpfp = procmime_get_first_text_content(msginfo)) == NULL) {
607                 g_warning("Can't get text part\n");
608                 return;
609         }
610
611         prtmp = g_strdup_printf("%s%cprinttmp.%08x",
612                                 get_mime_tmp_dir(), G_DIR_SEPARATOR, id++);
613
614         if ((prfp = fopen(prtmp, "wb")) == NULL) {
615                 FILE_OP_ERROR(prtmp, "fopen");
616                 g_free(prtmp);
617                 fclose(tmpfp);
618                 return;
619         }
620
621         if (msginfo->date) fprintf(prfp, "Date: %s\n", msginfo->date);
622         if (msginfo->from) fprintf(prfp, "From: %s\n", msginfo->from);
623         if (msginfo->to)   fprintf(prfp, "To: %s\n", msginfo->to);
624         if (msginfo->cc)   fprintf(prfp, "Cc: %s\n", msginfo->cc);
625         if (msginfo->newsgroups)
626                 fprintf(prfp, "Newsgroups: %s\n", msginfo->newsgroups);
627         if (msginfo->subject) fprintf(prfp, "Subject: %s\n", msginfo->subject);
628         fputc('\n', prfp);
629
630         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
631                 fputs(buf, prfp);
632
633         fclose(prfp);
634         fclose(tmpfp);
635
636         if (cmdline && (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
637             !strchr(p + 2, '%'))
638                 g_snprintf(buf, sizeof(buf) - 1, cmdline, prtmp);
639         else {
640                 if (cmdline)
641                         g_warning("Print command line is invalid: `%s'\n",
642                                   cmdline);
643                 g_snprintf(buf, sizeof(buf) - 1, def_cmd, prtmp);
644         }
645
646         g_free(prtmp);
647
648         g_strchomp(buf);
649         if (buf[strlen(buf) - 1] != '&') strcat(buf, "&");
650         system(buf);
651 }
652
653 MsgInfo *procmsg_msginfo_new_ref(MsgInfo *msginfo)
654 {
655         msginfo->refcnt++;
656         
657         return msginfo;
658 }
659
660 MsgInfo *procmsg_msginfo_new()
661 {
662         MsgInfo *newmsginfo;
663
664         newmsginfo = g_new0(MsgInfo, 1);
665         newmsginfo->refcnt = 1;
666         
667         return newmsginfo;
668 }
669
670 MsgInfo *procmsg_msginfo_copy(MsgInfo *msginfo)
671 {
672         MsgInfo *newmsginfo;
673
674         if (msginfo == NULL) return NULL;
675
676         newmsginfo = g_new0(MsgInfo, 1);
677
678         newmsginfo->refcnt = 1;
679
680 #define MEMBCOPY(mmb)   newmsginfo->mmb = msginfo->mmb
681 #define MEMBDUP(mmb)    newmsginfo->mmb = msginfo->mmb ? \
682                         g_strdup(msginfo->mmb) : NULL
683
684         MEMBCOPY(msgnum);
685         MEMBCOPY(size);
686         MEMBCOPY(mtime);
687         MEMBCOPY(date_t);
688         MEMBCOPY(flags);
689
690         MEMBDUP(fromname);
691
692         MEMBDUP(date);
693         MEMBDUP(from);
694         MEMBDUP(to);
695         MEMBDUP(cc);
696         MEMBDUP(newsgroups);
697         MEMBDUP(subject);
698         MEMBDUP(msgid);
699         MEMBDUP(inreplyto);
700         MEMBDUP(xref);
701
702         MEMBCOPY(folder);
703         MEMBCOPY(to_folder);
704
705         MEMBDUP(xface);
706         MEMBDUP(dispositionnotificationto);
707         MEMBDUP(returnreceiptto);
708         MEMBDUP(references);
709
710         MEMBCOPY(score);
711         MEMBCOPY(threadscore);
712
713         return newmsginfo;
714 }
715
716 MsgInfo *procmsg_msginfo_get_full_info(MsgInfo *msginfo)
717 {
718         MsgInfo *full_msginfo;
719         gchar *file;
720
721         if (msginfo == NULL) return NULL;
722
723         file = procmsg_get_message_file(msginfo);
724         if (!file) {
725                 g_warning("procmsg_msginfo_get_full_info(): can't get message file.\n");
726                 return NULL;
727         }
728
729         full_msginfo = procheader_parse_file(file, msginfo->flags, TRUE, FALSE);
730         g_free(file);
731         if (!full_msginfo) return NULL;
732
733         full_msginfo->msgnum = msginfo->msgnum;
734         full_msginfo->size = msginfo->size;
735         full_msginfo->mtime = msginfo->mtime;
736         full_msginfo->folder = msginfo->folder;
737 #if USE_GPGME
738         full_msginfo->plaintext_file = g_strdup(msginfo->plaintext_file);
739         full_msginfo->decryption_failed = msginfo->decryption_failed;
740 #endif
741         procmsg_msginfo_set_to_folder(full_msginfo, msginfo->to_folder);
742
743         return full_msginfo;
744 }
745
746 void procmsg_msginfo_free(MsgInfo *msginfo)
747 {
748         if (msginfo == NULL) return;
749
750         msginfo->refcnt--;
751         if (msginfo->refcnt > 0)
752                 return;
753
754         debug_print("freeing msginfo %d in %s\n", msginfo->msgnum, msginfo->folder ? msginfo->folder->path : "(nil)");
755
756         if (msginfo->to_folder) {
757                 msginfo->to_folder->op_count--;
758                 folder_item_update(msginfo->to_folder, F_ITEM_UPDATE_MSGCNT);
759         }
760
761         g_free(msginfo->fromspace);
762         g_free(msginfo->references);
763         g_free(msginfo->returnreceiptto);
764         g_free(msginfo->dispositionnotificationto);
765         g_free(msginfo->xface);
766
767         g_free(msginfo->fromname);
768
769         g_free(msginfo->date);
770         g_free(msginfo->from);
771         g_free(msginfo->to);
772         g_free(msginfo->cc);
773         g_free(msginfo->newsgroups);
774         g_free(msginfo->subject);
775         g_free(msginfo->msgid);
776         g_free(msginfo->inreplyto);
777         g_free(msginfo->xref);
778
779         g_free(msginfo);
780 }
781
782 guint procmsg_msginfo_memusage(MsgInfo *msginfo)
783 {
784         guint memusage = 0;
785         
786         memusage += sizeof(MsgInfo);
787         if (msginfo->fromname)
788                 memusage += strlen(msginfo->fromname);
789         if (msginfo->date)
790                 memusage += strlen(msginfo->date);
791         if (msginfo->from)
792                 memusage += strlen(msginfo->from);
793         if (msginfo->to)
794                 memusage += strlen(msginfo->to);
795         if (msginfo->cc)
796                 memusage += strlen(msginfo->cc);
797         if (msginfo->newsgroups)
798                 memusage += strlen(msginfo->newsgroups);
799         if (msginfo->subject)
800                 memusage += strlen(msginfo->subject);
801         if (msginfo->msgid)
802                 memusage += strlen(msginfo->msgid);
803         if (msginfo->inreplyto)
804                 memusage += strlen(msginfo->inreplyto);
805         if (msginfo->xface)
806                 memusage += strlen(msginfo->xface);
807         if (msginfo->dispositionnotificationto)
808                 memusage += strlen(msginfo->dispositionnotificationto);
809         if (msginfo->returnreceiptto)
810                 memusage += strlen(msginfo->returnreceiptto);
811         if (msginfo->references)
812                 memusage += strlen(msginfo->references);
813         if (msginfo->fromspace)
814                 memusage += strlen(msginfo->fromspace);
815
816         return memusage;
817 }
818
819 gint procmsg_cmp_msgnum_for_sort(gconstpointer a, gconstpointer b)
820 {
821         const MsgInfo *msginfo1 = a;
822         const MsgInfo *msginfo2 = b;
823
824         if (!msginfo1)
825                 return -1;
826         if (!msginfo2)
827                 return -1;
828
829         return msginfo1->msgnum - msginfo2->msgnum;
830 }
831
832 enum
833 {
834         Q_SENDER           = 0,
835         Q_SMTPSERVER       = 1,
836         Q_RECIPIENTS       = 2,
837         Q_NEWSGROUPS       = 3,
838         Q_MAIL_ACCOUNT_ID  = 4,
839         Q_NEWS_ACCOUNT_ID  = 5,
840         Q_SAVE_COPY_FOLDER = 6,
841         Q_REPLY_MESSAGE_ID = 7,
842         Q_FWD_MESSAGE_ID   = 8
843 };
844
845 gint procmsg_send_message_queue(const gchar *file)
846 {
847         static HeaderEntry qentry[] = {{"S:",    NULL, FALSE},
848                                        {"SSV:",  NULL, FALSE},
849                                        {"R:",    NULL, FALSE},
850                                        {"NG:",   NULL, FALSE},
851                                        {"MAID:", NULL, FALSE},
852                                        {"NAID:", NULL, FALSE},
853                                        {"SCF:",  NULL, FALSE},
854                                        {"RMID:", NULL, FALSE},
855                                        {"FMID:", NULL, FALSE},
856                                        {NULL,    NULL, FALSE}};
857         FILE *fp;
858         gint filepos;
859         gint mailval = 0, newsval = 0;
860         gchar *from = NULL;
861         gchar *smtpserver = NULL;
862         GSList *to_list = NULL;
863         GSList *newsgroup_list = NULL;
864         gchar *savecopyfolder = NULL;
865         gchar *replymessageid = NULL;
866         gchar *fwdmessageid = NULL;
867         gchar buf[BUFFSIZE];
868         gint hnum;
869         PrefsAccount *mailac = NULL, *newsac = NULL;
870         int local = 0;
871
872         g_return_val_if_fail(file != NULL, -1);
873
874         if ((fp = fopen(file, "rb")) == NULL) {
875                 FILE_OP_ERROR(file, "fopen");
876                 return -1;
877         }
878
879         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, qentry))
880                != -1) {
881                 gchar *p = buf + strlen(qentry[hnum].name);
882
883                 switch (hnum) {
884                 case Q_SENDER:
885                         if (!from) from = g_strdup(p);
886                         break;
887                 case Q_SMTPSERVER:
888                         if (!smtpserver) smtpserver = g_strdup(p);
889                         break;
890                 case Q_RECIPIENTS:
891                         to_list = address_list_append(to_list, p);
892                         break;
893                 case Q_NEWSGROUPS:
894                         newsgroup_list = newsgroup_list_append(newsgroup_list, p);
895                         break;
896                 case Q_MAIL_ACCOUNT_ID:
897                         mailac = account_find_from_id(atoi(p));
898                         break;
899                 case Q_NEWS_ACCOUNT_ID:
900                         newsac = account_find_from_id(atoi(p));
901                         break;
902                 case Q_SAVE_COPY_FOLDER:
903                         if (!savecopyfolder) savecopyfolder = g_strdup(p);
904                         break;
905                 case Q_REPLY_MESSAGE_ID:
906                         if (!replymessageid) replymessageid = g_strdup(p);
907                         break;
908                 case Q_FWD_MESSAGE_ID:
909                         if (!fwdmessageid) fwdmessageid = g_strdup(p);
910                         break;
911                 }
912         }
913         filepos = ftell(fp);
914
915         if (to_list) {
916                 debug_print("Sending message by mail\n");
917                 if (!from) {
918                         g_warning("Queued message header is broken.\n");
919                         mailval = -1;
920                 } else if (mailac && mailac->use_mail_command &&
921                            mailac->mail_command && (* mailac->mail_command)) {
922                         mailval = send_message_local(mailac->mail_command, fp);
923                         local = 1;
924                 } else if (prefs_common.use_extsend && prefs_common.extsend_cmd) {
925                         mailval = send_message_local(prefs_common.extsend_cmd, fp);
926                         local = 1;
927                 } else {
928                         if (!mailac) {
929                                 mailac = account_find_from_smtp_server(from, smtpserver);
930                                 if (!mailac) {
931                                         g_warning("Account not found. "
932                                                     "Using current account...\n");
933                                         mailac = cur_account;
934                                 }
935                         }
936
937                         if (mailac)
938                                 mailval = send_message_smtp(mailac, to_list, fp);
939                         else {
940                                 PrefsAccount tmp_ac;
941
942                                 g_warning("Account not found.\n");
943
944                                 memset(&tmp_ac, 0, sizeof(PrefsAccount));
945                                 tmp_ac.address = from;
946                                 tmp_ac.smtp_server = smtpserver;
947                                 tmp_ac.smtpport = SMTP_PORT;
948                                 mailval = send_message_smtp(&tmp_ac, to_list, fp);
949                         }
950                 }
951                 if (mailval < 0) {
952                         if (!local)
953                                 alertpanel_error_log(
954                                         _("Error occurred while sending the message to `%s'."),
955                                         mailac ? mailac->smtp_server : smtpserver);
956                         else
957                                 alertpanel_error_log(
958                                         _("Error occurred while sending the message with command `%s'."),
959                                         (mailac && mailac->use_mail_command && 
960                                          mailac->mail_command && (*mailac->mail_command)) ? 
961                                                 mailac->mail_command : prefs_common.extsend_cmd);
962                 }
963         }
964
965         fseek(fp, filepos, SEEK_SET);
966         if (newsgroup_list && (newsval == 0)) {
967                 Folder *folder;
968                 gchar *tmp = NULL;
969                 FILE *tmpfp;
970
971                 /* write to temporary file */
972                 tmp = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
973                             G_DIR_SEPARATOR, (gint)file);
974                 if ((tmpfp = fopen(tmp, "wb")) == NULL) {
975                         FILE_OP_ERROR(tmp, "fopen");
976                         newsval = -1;
977                         alertpanel_error(_("Could not create temporary file for news sending."));
978                 } else {
979                         if (change_file_mode_rw(tmpfp, tmp) < 0) {
980                                 FILE_OP_ERROR(tmp, "chmod");
981                                 g_warning("can't change file mode\n");
982                         }
983
984                         while ((newsval == 0) && fgets(buf, sizeof(buf), fp) != NULL) {
985                                 if (fputs(buf, tmpfp) == EOF) {
986                                         FILE_OP_ERROR(tmp, "fputs");
987                                         newsval = -1;
988                                         alertpanel_error(_("Error when writing temporary file for news sending."));
989                                 }
990                         }
991                         fclose(tmpfp);
992
993                         if (newsval == 0) {
994                                 debug_print("Sending message by news\n");
995
996                                 folder = FOLDER(newsac->folder);
997
998                                 newsval = news_post(folder, tmp);
999                                 if (newsval < 0) {
1000                                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1001                                                  newsac->nntp_server);
1002                                 }
1003                         }
1004                         unlink(tmp);
1005                 }
1006                 g_free(tmp);
1007         }
1008
1009         slist_free_strings(to_list);
1010         g_slist_free(to_list);
1011         slist_free_strings(newsgroup_list);
1012         g_slist_free(newsgroup_list);
1013         g_free(from);
1014         g_free(smtpserver);
1015         fclose(fp);
1016
1017         /* save message to outbox */
1018         if (mailval == 0 && newsval == 0 && savecopyfolder) {
1019                 FolderItem *outbox;
1020
1021                 debug_print("saving sent message...\n");
1022
1023                 outbox = folder_find_item_from_identifier(savecopyfolder);
1024                 if (!outbox)
1025                         outbox = folder_get_default_outbox();
1026
1027                 procmsg_save_to_outbox(outbox, file, TRUE);
1028         }
1029
1030         if (replymessageid != NULL || fwdmessageid != NULL) {
1031                 gchar **tokens;
1032                 FolderItem *item;
1033                 
1034                 if (replymessageid != NULL)
1035                         tokens = g_strsplit(replymessageid, "\x7f", 0);
1036                 else
1037                         tokens = g_strsplit(fwdmessageid, "\x7f", 0);
1038                 item = folder_find_item_from_identifier(tokens[0]);
1039                 if (item != NULL) {
1040                         MsgInfo *msginfo;
1041                         
1042                         msginfo = folder_item_get_msginfo(item, atoi(tokens[1]));
1043                         if ((msginfo != NULL) && (strcmp(msginfo->msgid, tokens[2]) != 0)) {
1044                                 procmsg_msginfo_free(msginfo);
1045                                 msginfo = NULL;
1046                         }
1047                         
1048                         if (msginfo == NULL) {
1049                                 msginfo = folder_item_get_msginfo_by_msgid(item, tokens[2]);
1050                         }
1051                         
1052                         if (msginfo != NULL) {
1053                                 if (replymessageid != NULL) {
1054                                         procmsg_msginfo_unset_flags(msginfo, MSG_FORWARDED, 0);
1055                                         procmsg_msginfo_set_flags(msginfo, MSG_REPLIED, 0);
1056                                 } 
1057                                 else {
1058                                         procmsg_msginfo_unset_flags(msginfo, MSG_REPLIED, 0);
1059                                         procmsg_msginfo_set_flags(msginfo, MSG_FORWARDED, 0);
1060                                 }
1061                                 procmsg_msginfo_free(msginfo);
1062                         }
1063                 }
1064                 g_strfreev(tokens);
1065         }
1066
1067         g_free(savecopyfolder);
1068         g_free(replymessageid);
1069         g_free(fwdmessageid);
1070         
1071         return (newsval != 0 ? newsval : mailval);
1072 }
1073
1074 static void update_folder_msg_counts(FolderItem *item, MsgInfo *msginfo, MsgPermFlags old)
1075 {
1076         MsgPermFlags new = msginfo->flags.perm_flags;
1077
1078         /* NEW flag */
1079         if (!(old & MSG_NEW) && (new & MSG_NEW)) {
1080                 item->new++;
1081         }
1082
1083         if ((old & MSG_NEW) && !(new & MSG_NEW)) {
1084                 item->new--;
1085         }
1086
1087         /* UNREAD flag */
1088         if (!(old & MSG_UNREAD) && (new & MSG_UNREAD)) {
1089                 item->unread++;
1090                 if (procmsg_msg_has_marked_parent(msginfo))
1091                         item->unreadmarked++;
1092         }
1093
1094         if ((old & MSG_UNREAD) && !(new & MSG_UNREAD)) {
1095                 item->unread--;
1096                 if (procmsg_msg_has_marked_parent(msginfo))
1097                         item->unreadmarked--;
1098         }
1099         
1100         /* MARK flag */
1101         if (!(old & MSG_MARKED) && (new & MSG_MARKED)) {
1102                 procmsg_update_unread_children(msginfo, TRUE);
1103         }
1104
1105         if ((old & MSG_MARKED) && !(new & MSG_MARKED)) {
1106                 procmsg_update_unread_children(msginfo, FALSE);
1107         }
1108 }
1109
1110 void procmsg_msginfo_set_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1111 {
1112         FolderItem *item;
1113         MsgInfoUpdate msginfo_update;
1114         MsgPermFlags perm_flags_new, perm_flags_old;
1115
1116         g_return_if_fail(msginfo != NULL);
1117         item = msginfo->folder;
1118         g_return_if_fail(item != NULL);
1119         
1120         debug_print("Setting flags for message %d in folder %s\n", msginfo->msgnum, item->path);
1121
1122         /* Perm Flags handling */
1123         perm_flags_old = msginfo->flags.perm_flags;
1124         perm_flags_new = msginfo->flags.perm_flags | perm_flags;
1125         if ((perm_flags & MSG_IGNORE_THREAD) || (perm_flags_old & MSG_IGNORE_THREAD)) {
1126                 perm_flags_new &= ~(MSG_NEW | MSG_UNREAD);
1127         }
1128
1129         if (perm_flags_old != perm_flags_new) {
1130                 folder_item_change_msg_flags(msginfo->folder, msginfo, perm_flags_new);
1131
1132                 update_folder_msg_counts(item, msginfo, perm_flags_old);
1133
1134                 msginfo_update.msginfo = msginfo;
1135                 hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
1136                 folder_item_update(msginfo->folder, F_ITEM_UPDATE_MSGCNT);
1137         }
1138
1139         /* Tmp flags hanlding */
1140         msginfo->flags.tmp_flags |= tmp_flags;
1141 }
1142
1143 void procmsg_msginfo_unset_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1144 {
1145         FolderItem *item;
1146         MsgInfoUpdate msginfo_update;
1147         MsgPermFlags perm_flags_new, perm_flags_old;
1148
1149         g_return_if_fail(msginfo != NULL);
1150         item = msginfo->folder;
1151         g_return_if_fail(item != NULL);
1152         
1153         debug_print("Unsetting flags for message %d in folder %s\n", msginfo->msgnum, item->path);
1154
1155         /* Perm Flags handling */
1156         perm_flags_old = msginfo->flags.perm_flags;
1157         perm_flags_new = msginfo->flags.perm_flags & ~perm_flags;
1158         
1159         if (perm_flags_old != perm_flags_new) {
1160                 folder_item_change_msg_flags(msginfo->folder, msginfo, perm_flags_new);
1161
1162                 update_folder_msg_counts(item, msginfo, perm_flags_old);
1163
1164                 msginfo_update.msginfo = msginfo;
1165                 hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
1166                 folder_item_update(msginfo->folder, F_ITEM_UPDATE_MSGCNT);
1167         }
1168
1169         /* Tmp flags hanlding */
1170         msginfo->flags.tmp_flags &= ~tmp_flags;
1171 }
1172
1173 /*!
1174  *\brief        check for flags (e.g. mark) in prior msgs of current thread
1175  *
1176  *\param        info Current message
1177  *\param        perm_flags Flags to be checked
1178  *\param        parentmsgs Hash of prior msgs to avoid loops
1179  *
1180  *\return       gboolean TRUE if perm_flags are found
1181  */
1182 gboolean procmsg_msg_has_flagged_parent_real(MsgInfo *info,
1183                 MsgPermFlags perm_flags, GHashTable *parentmsgs)
1184 {
1185         MsgInfo *tmp;
1186
1187         g_return_val_if_fail(info != NULL, FALSE);
1188
1189         if (info != NULL && info->folder != NULL && info->inreplyto != NULL) {
1190                 tmp = folder_item_get_msginfo_by_msgid(info->folder,
1191                                 info->inreplyto);
1192                 if (tmp && (tmp->flags.perm_flags & perm_flags)) {
1193                         procmsg_msginfo_free(tmp);
1194                         return TRUE;
1195                 } else if (tmp != NULL) {
1196                         gboolean result;
1197
1198                         if (g_hash_table_lookup(parentmsgs, info)) {
1199                                 debug_print("loop detected: %s%c%d\n",
1200                                         folder_item_get_path(info->folder),
1201                                         G_DIR_SEPARATOR, info->msgnum);
1202                                 result = FALSE;
1203                         } else {
1204                                 g_hash_table_insert(parentmsgs, info, "1");
1205                                 result = procmsg_msg_has_flagged_parent_real(
1206                                     tmp, perm_flags, parentmsgs);
1207                         }
1208                         procmsg_msginfo_free(tmp);
1209                         return result;
1210                 } else {
1211                         return FALSE;
1212                 }
1213         } else
1214                 return FALSE;
1215 }
1216
1217 /*!
1218  *\brief        Callback for cleaning up hash of parentmsgs
1219  */
1220 gboolean parentmsgs_hash_remove(gpointer key,
1221                             gpointer value,
1222                             gpointer user_data)
1223 {
1224         return TRUE;
1225 }
1226
1227 /*!
1228  *\brief        Set up list of parentmsgs
1229  *              See procmsg_msg_has_flagged_parent_real()
1230  */
1231 gboolean procmsg_msg_has_flagged_parent(MsgInfo *info, MsgPermFlags perm_flags)
1232 {
1233         gboolean result;
1234         GHashTable *parentmsgs = g_hash_table_new(NULL, NULL); 
1235
1236         result = procmsg_msg_has_flagged_parent_real(info, perm_flags, parentmsgs);
1237         g_hash_table_foreach_remove(parentmsgs, parentmsgs_hash_remove, NULL);
1238         g_hash_table_destroy(parentmsgs);
1239         return result;
1240 }
1241
1242 /*!
1243  *\brief        Check if msgs prior in thread are marked
1244  *              See procmsg_msg_has_flagged_parent_real()
1245  */
1246 gboolean procmsg_msg_has_marked_parent(MsgInfo *info)
1247 {
1248         return procmsg_msg_has_flagged_parent(info, MSG_MARKED);
1249 }
1250
1251
1252 GSList *procmsg_find_children_func(MsgInfo *info, 
1253                                    GSList *children, GSList *all)
1254 {
1255         GSList *cur;
1256
1257         g_return_val_if_fail(info!=NULL, children);
1258         if (info->msgid == NULL)
1259                 return children;
1260
1261         for (cur = all; cur != NULL; cur = g_slist_next(cur)) {
1262                 MsgInfo *tmp = (MsgInfo *)cur->data;
1263                 if (tmp->inreplyto && !strcmp(tmp->inreplyto, info->msgid)) {
1264                         /* Check if message is already in the list */
1265                         if ((children == NULL) || 
1266                             (g_slist_index(children, tmp) == -1)) {
1267                                 children = g_slist_prepend(children,
1268                                                 procmsg_msginfo_new_ref(tmp));
1269                                 children = procmsg_find_children_func(tmp, 
1270                                                         children, 
1271                                                         all);
1272                         }
1273                 }
1274         }
1275         return children;
1276 }
1277
1278 GSList *procmsg_find_children (MsgInfo *info)
1279 {
1280         GSList *children;
1281         GSList *all, *cur;
1282
1283         g_return_val_if_fail(info!=NULL, NULL);
1284         all = folder_item_get_msg_list(info->folder);
1285         children = procmsg_find_children_func(info, NULL, all);
1286         if (children != NULL) {
1287                 for (cur = all; cur != NULL; cur = g_slist_next(cur)) {
1288                         /* this will not free the used pointers
1289                            created with procmsg_msginfo_new_ref */
1290                         procmsg_msginfo_free((MsgInfo *)cur->data);
1291                 }
1292         }
1293         g_slist_free(all);
1294
1295         return children;
1296 }
1297
1298 void procmsg_update_unread_children(MsgInfo *info, gboolean newly_marked)
1299 {
1300         GSList *children = procmsg_find_children(info);
1301         GSList *cur;
1302         for (cur = children; cur != NULL; cur = g_slist_next(cur)) {
1303                 MsgInfo *tmp = (MsgInfo *)cur->data;
1304                 if(MSG_IS_UNREAD(tmp->flags) && !MSG_IS_IGNORE_THREAD(tmp->flags)) {
1305                         if(newly_marked) 
1306                                 info->folder->unreadmarked++;
1307                         else
1308                                 info->folder->unreadmarked--;
1309                         folder_item_update(info->folder, F_ITEM_UPDATE_MSGCNT);
1310                 }
1311                 procmsg_msginfo_free(tmp);
1312         }
1313         g_slist_free(children);
1314 }
1315
1316 /**
1317  * Set the destination folder for a copy or move operation
1318  *
1319  * \param msginfo The message which's destination folder is changed
1320  * \param to_folder The destination folder for the operation
1321  */
1322 void procmsg_msginfo_set_to_folder(MsgInfo *msginfo, FolderItem *to_folder)
1323 {
1324         if(msginfo->to_folder != NULL) {
1325                 msginfo->to_folder->op_count--;
1326                 folder_item_update(msginfo->to_folder, F_ITEM_UPDATE_MSGCNT);
1327         }
1328         msginfo->to_folder = to_folder;
1329         if(to_folder != NULL) {
1330                 to_folder->op_count++;
1331                 folder_item_update(msginfo->to_folder, F_ITEM_UPDATE_MSGCNT);
1332         }
1333 }