0.8.9claws14
[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.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 "imap.h"
43 #include "hooks.h"
44
45 typedef struct _FlagInfo        FlagInfo;
46
47 struct _FlagInfo
48 {
49         guint    msgnum;
50         MsgFlags flags;
51 };
52
53 static GHashTable *procmsg_read_mark_file       (const gchar    *folder);
54 void   procmsg_msginfo_write_flags              (MsgInfo        *msginfo);
55
56 GHashTable *procmsg_msg_hash_table_create(GSList *mlist)
57 {
58         GHashTable *msg_table;
59
60         if (mlist == NULL) return NULL;
61
62         msg_table = g_hash_table_new(NULL, g_direct_equal);
63         procmsg_msg_hash_table_append(msg_table, mlist);
64
65         return msg_table;
66 }
67
68 void procmsg_msg_hash_table_append(GHashTable *msg_table, GSList *mlist)
69 {
70         GSList *cur;
71         MsgInfo *msginfo;
72
73         if (msg_table == NULL || mlist == NULL) return;
74
75         for (cur = mlist; cur != NULL; cur = cur->next) {
76                 msginfo = (MsgInfo *)cur->data;
77
78                 g_hash_table_insert(msg_table,
79                                     GUINT_TO_POINTER(msginfo->msgnum),
80                                     msginfo);
81         }
82 }
83
84 GHashTable *procmsg_to_folder_hash_table_create(GSList *mlist)
85 {
86         GHashTable *msg_table;
87         GSList *cur;
88         MsgInfo *msginfo;
89
90         if (mlist == NULL) return NULL;
91
92         msg_table = g_hash_table_new(NULL, g_direct_equal);
93
94         for (cur = mlist; cur != NULL; cur = cur->next) {
95                 msginfo = (MsgInfo *)cur->data;
96                 g_hash_table_insert(msg_table, msginfo->to_folder, msginfo);
97         }
98
99         return msg_table;
100 }
101
102 static gint procmsg_read_cache_data_str(FILE *fp, gchar **str)
103 {
104         gchar buf[BUFFSIZE];
105         gint ret = 0;
106         size_t len;
107
108         if (fread(&len, sizeof(len), 1, fp) == 1) {
109                 if (len < 0)
110                         ret = -1;
111                 else {
112                         gchar *tmp = NULL;
113
114                         while (len > 0) {
115                                 size_t size = MIN(len, BUFFSIZE - 1);
116
117                                 if (fread(buf, size, 1, fp) != 1) {
118                                         ret = -1;
119                                         if (tmp) g_free(tmp);
120                                         *str = NULL;
121                                         break;
122                                 }
123
124                                 buf[size] = '\0';
125                                 if (tmp) {
126                                         *str = g_strconcat(tmp, buf, NULL);
127                                         g_free(tmp);
128                                         tmp = *str;
129                                 } else
130                                         tmp = *str = g_strdup(buf);
131
132                                 len -= size;
133                         }
134                 }
135         } else
136                 ret = -1;
137
138         if (ret < 0)
139                 g_warning("Cache data is corrupted\n");
140
141         return ret;
142 }
143
144 #define READ_CACHE_DATA(data, fp) \
145 { \
146         if (procmsg_read_cache_data_str(fp, &data) < 0) { \
147                 procmsg_msginfo_free(msginfo); \
148                 break; \
149         } \
150 }
151
152 #define READ_CACHE_DATA_INT(n, fp) \
153 { \
154         if (fread(&n, sizeof(n), 1, fp) != 1) { \
155                 g_warning("Cache data is corrupted\n"); \
156                 procmsg_msginfo_free(msginfo); \
157                 break; \
158         } \
159 }
160
161 GSList *procmsg_read_cache(FolderItem *item, gboolean scan_file)
162 {
163         GSList *mlist = NULL;
164         GSList *last = NULL;
165         gchar *cache_file;
166         FILE *fp;
167         MsgInfo *msginfo;
168         MsgFlags default_flags;
169         gchar file_buf[BUFFSIZE];
170         gint ver;
171         guint num;
172         FolderType type;
173
174         g_return_val_if_fail(item != NULL, NULL);
175         g_return_val_if_fail(item->folder != NULL, NULL);
176         type = item->folder->type;
177
178         default_flags.perm_flags = MSG_NEW|MSG_UNREAD;
179         default_flags.tmp_flags = MSG_CACHED;
180         if (type == F_MH || type == F_IMAP) {
181                 if (item->stype == F_QUEUE) {
182                         MSG_SET_TMP_FLAGS(default_flags, MSG_QUEUED);
183                 } else if (item->stype == F_DRAFT) {
184                         MSG_SET_TMP_FLAGS(default_flags, MSG_DRAFT);
185                 }
186         }
187         if (type == F_IMAP) {
188                 MSG_SET_TMP_FLAGS(default_flags, MSG_IMAP);
189         } else if (type == F_NEWS) {
190                 MSG_SET_TMP_FLAGS(default_flags, MSG_NEWS);
191         }
192
193         if (type == F_MH) {
194                 gchar *path;
195
196                 path = folder_item_get_path(item);
197                 if (change_dir(path) < 0) {
198                         g_free(path);
199                         return NULL;
200                 }
201                 g_free(path);
202         }
203         cache_file = folder_item_get_cache_file(item);
204         if ((fp = fopen(cache_file, "rb")) == NULL) {
205                 debug_print("\tNo cache file\n");
206                 g_free(cache_file);
207                 return NULL;
208         }
209         setvbuf(fp, file_buf, _IOFBF, sizeof(file_buf));
210         g_free(cache_file);
211
212         debug_print("\tReading summary cache...\n");
213
214         /* compare cache version */
215         if (fread(&ver, sizeof(ver), 1, fp) != 1 ||
216             CACHE_VERSION != ver) {
217                 debug_print("Cache version is different. Discarding it.\n");
218                 fclose(fp);
219                 return NULL;
220         }
221
222         while (fread(&num, sizeof(num), 1, fp) == 1) {
223                 msginfo = procmsg_msginfo_new();
224                 msginfo->msgnum = num;
225                 READ_CACHE_DATA_INT(msginfo->size, fp);
226                 READ_CACHE_DATA_INT(msginfo->mtime, fp);
227                 READ_CACHE_DATA_INT(msginfo->date_t, fp);
228                 READ_CACHE_DATA_INT(msginfo->flags.tmp_flags, fp);
229
230                 READ_CACHE_DATA(msginfo->fromname, fp);
231
232                 READ_CACHE_DATA(msginfo->date, fp);
233                 READ_CACHE_DATA(msginfo->from, fp);
234                 READ_CACHE_DATA(msginfo->to, fp);
235                 READ_CACHE_DATA(msginfo->cc, fp);
236                 READ_CACHE_DATA(msginfo->newsgroups, fp);
237                 READ_CACHE_DATA(msginfo->subject, fp);
238                 READ_CACHE_DATA(msginfo->msgid, fp);
239                 READ_CACHE_DATA(msginfo->inreplyto, fp);
240                 READ_CACHE_DATA(msginfo->references, fp);
241                 READ_CACHE_DATA(msginfo->xref, fp);
242
243
244                 MSG_SET_PERM_FLAGS(msginfo->flags, default_flags.perm_flags);
245                 MSG_SET_TMP_FLAGS(msginfo->flags, default_flags.tmp_flags);
246
247                 /* if the message file doesn't exist or is changed,
248                    don't add the data */
249                 if (type == F_MH && scan_file &&
250                     folder_item_is_msg_changed(item, msginfo))
251                         procmsg_msginfo_free(msginfo);
252                 else {
253                         msginfo->folder = item;
254
255                         if (!mlist)
256                                 last = mlist = g_slist_append(NULL, msginfo);
257                         else {
258                                 last = g_slist_append(last, msginfo);
259                                 last = last->next;
260                         }
261                 }
262         }
263
264         fclose(fp);
265         debug_print("done.\n");
266
267         return mlist;
268 }
269
270 #undef READ_CACHE_DATA
271 #undef READ_CACHE_DATA_INT
272
273 void procmsg_set_flags(GSList *mlist, FolderItem *item)
274 {
275         GSList *cur, *tmp;
276         gint newmsg = 0;
277         gint lastnum = 0;
278         gchar *markdir;
279         MsgInfo *msginfo;
280         GHashTable *mark_table;
281         MsgFlags *flags;
282
283         if (!mlist) return;
284         g_return_if_fail(item != NULL);
285         g_return_if_fail(item->folder != NULL);
286
287         debug_print("\tMarking the messages...\n");
288
289         markdir = folder_item_get_path(item);
290         if (!is_dir_exist(markdir))
291                 make_dir_hier(markdir);
292
293         mark_table = procmsg_read_mark_file(markdir);
294         g_free(markdir);
295
296         if (!mark_table) return;
297
298         for (cur = mlist; cur != NULL; cur = cur->next) {
299                 msginfo = (MsgInfo *)cur->data;
300
301                 if (lastnum < msginfo->msgnum)
302                         lastnum = msginfo->msgnum;
303
304                 flags = g_hash_table_lookup
305                         (mark_table, GUINT_TO_POINTER(msginfo->msgnum));
306
307                 if (flags != NULL) {
308                         /* add the permanent flags only */
309                         msginfo->flags.perm_flags = flags->perm_flags;
310                         if (item->folder->type == F_IMAP) {
311                                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_IMAP);
312                         } else if (item->folder->type == F_NEWS) {
313                                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_NEWS);
314                         }
315                 } else {
316                         /* not found (new message) */
317                         if (newmsg == 0) {
318                                 for (tmp = mlist; tmp != cur; tmp = tmp->next)
319                                         MSG_UNSET_PERM_FLAGS
320                                                 (((MsgInfo *)tmp->data)->flags,
321                                                  MSG_NEW);
322                         }
323                         newmsg++;
324                 }
325         }
326
327         item->last_num = lastnum;
328
329         debug_print("done.\n");
330         if (newmsg)
331                 debug_print("\t%d new message(s)\n", newmsg);
332
333         hash_free_value_mem(mark_table);
334         g_hash_table_destroy(mark_table);
335 }
336
337 gint procmsg_get_last_num_in_msg_list(GSList *mlist)
338 {
339         GSList *cur;
340         MsgInfo *msginfo;
341         gint last = 0;
342
343         for (cur = mlist; cur != NULL; cur = cur->next) {
344                 msginfo = (MsgInfo *)cur->data;
345                 if (msginfo && msginfo->msgnum > last)
346                         last = msginfo->msgnum;
347         }
348
349         return last;
350 }
351
352 void procmsg_msg_list_free(GSList *mlist)
353 {
354         GSList *cur;
355         MsgInfo *msginfo;
356
357         for (cur = mlist; cur != NULL; cur = cur->next) {
358                 msginfo = (MsgInfo *)cur->data;
359                 procmsg_msginfo_free(msginfo);
360         }
361         g_slist_free(mlist);
362 }
363
364 void procmsg_write_cache(MsgInfo *msginfo, FILE *fp)
365 {
366         MsgTmpFlags flags = msginfo->flags.tmp_flags & MSG_CACHED_FLAG_MASK;
367
368         WRITE_CACHE_DATA_INT(msginfo->msgnum, fp);
369         WRITE_CACHE_DATA_INT(msginfo->size, fp);
370         WRITE_CACHE_DATA_INT(msginfo->mtime, fp);
371         WRITE_CACHE_DATA_INT(msginfo->date_t, fp);
372         WRITE_CACHE_DATA_INT(flags, fp);
373
374         WRITE_CACHE_DATA(msginfo->fromname, fp);
375
376         WRITE_CACHE_DATA(msginfo->date, fp);
377         WRITE_CACHE_DATA(msginfo->from, fp);
378         WRITE_CACHE_DATA(msginfo->to, fp);
379         WRITE_CACHE_DATA(msginfo->cc, fp);
380         WRITE_CACHE_DATA(msginfo->newsgroups, fp);
381         WRITE_CACHE_DATA(msginfo->subject, fp);
382         WRITE_CACHE_DATA(msginfo->msgid, fp);
383         WRITE_CACHE_DATA(msginfo->inreplyto, fp);
384         WRITE_CACHE_DATA(msginfo->references, fp);
385         WRITE_CACHE_DATA(msginfo->xref, fp);
386
387 }
388
389 void procmsg_write_flags(MsgInfo *msginfo, FILE *fp)
390 {
391         MsgPermFlags flags = msginfo->flags.perm_flags;
392
393         WRITE_CACHE_DATA_INT(msginfo->msgnum, fp);
394         WRITE_CACHE_DATA_INT(flags, fp);
395 }
396
397 void procmsg_flush_mark_queue(FolderItem *item, FILE *fp)
398 {
399         MsgInfo *flaginfo;
400
401         g_return_if_fail(item != NULL);
402         g_return_if_fail(fp != NULL);
403
404         while (item->mark_queue != NULL) {
405                 flaginfo = (MsgInfo *)item->mark_queue->data;
406                 procmsg_write_flags(flaginfo, fp);
407                 procmsg_msginfo_free(flaginfo);
408                 item->mark_queue = g_slist_remove(item->mark_queue, flaginfo);
409         }
410 }
411
412 void procmsg_add_flags(FolderItem *item, gint num, MsgFlags flags)
413 {
414         FILE *fp;
415         gchar *path;
416         MsgInfo msginfo;
417
418         g_return_if_fail(item != NULL);
419
420         if (item->opened) {
421                 MsgInfo *queue_msginfo;
422
423                 queue_msginfo = g_new0(MsgInfo, 1);
424                 queue_msginfo->msgnum = num;
425                 queue_msginfo->flags = flags;
426                 item->mark_queue = g_slist_append
427                         (item->mark_queue, queue_msginfo);
428                 return;
429         }
430
431         path = folder_item_get_path(item);
432         g_return_if_fail(path != NULL);
433
434         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL) {
435                 g_warning("can't open mark file\n");
436                 g_free(path);
437                 return;
438         }
439         g_free(path);
440
441         msginfo.msgnum = num;
442         msginfo.flags = flags;
443
444         procmsg_write_flags(&msginfo, fp);
445         fclose(fp);
446 }
447
448 struct MarkSum {
449         gint *new;
450         gint *unread;
451         gint *total;
452         gint *min;
453         gint *max;
454         gint first;
455 };
456
457 static GHashTable *procmsg_read_mark_file(const gchar *folder)
458 {
459         FILE *fp;
460         GHashTable *mark_table = NULL;
461         gint num;
462         MsgFlags *flags;
463         MsgPermFlags perm_flags;
464
465         if ((fp = procmsg_open_mark_file(folder, FALSE)) == NULL)
466                 return NULL;
467
468         mark_table = g_hash_table_new(NULL, g_direct_equal);
469
470         while (fread(&num, sizeof(num), 1, fp) == 1) {
471                 if (fread(&perm_flags, sizeof(perm_flags), 1, fp) != 1) break;
472
473                 flags = g_hash_table_lookup(mark_table, GUINT_TO_POINTER(num));
474                 if (flags != NULL)
475                         g_free(flags);
476
477                 flags = g_new0(MsgFlags, 1);
478                 flags->perm_flags = perm_flags;
479     
480                 if (!MSG_IS_REALLY_DELETED(*flags)) {
481                         g_hash_table_insert(mark_table, GUINT_TO_POINTER(num), flags);
482                 } else {
483                         g_hash_table_remove(mark_table, GUINT_TO_POINTER(num));
484                 }
485         }
486
487         fclose(fp);
488         return mark_table;
489 }
490
491 FILE *procmsg_open_mark_file(const gchar *folder, gboolean append)
492 {
493         gchar *markfile;
494         FILE *fp;
495         gint ver;
496
497         markfile = g_strconcat(folder, G_DIR_SEPARATOR_S, MARK_FILE, NULL);
498
499         if ((fp = fopen(markfile, "rb")) == NULL)
500                 debug_print("Mark file not found.\n");
501         else if (fread(&ver, sizeof(ver), 1, fp) != 1 || MARK_VERSION != ver) {
502                 debug_print("Mark version is different (%d != %d). "
503                               "Discarding it.\n", ver, MARK_VERSION);
504                 fclose(fp);
505                 fp = NULL;
506         }
507
508         /* read mode */
509         if (append == FALSE) {
510                 g_free(markfile);
511                 return fp;
512         }
513
514         if (fp) {
515                 /* reopen with append mode */
516                 fclose(fp);
517                 if ((fp = fopen(markfile, "ab")) == NULL)
518                         g_warning("Can't open mark file with append mode.\n");
519         } else {
520                 /* open with overwrite mode if mark file doesn't exist or
521                    version is different */
522                 if ((fp = fopen(markfile, "wb")) == NULL)
523                         g_warning("Can't open mark file with write mode.\n");
524                 else {
525                         ver = MARK_VERSION;
526                         WRITE_CACHE_DATA_INT(ver, fp);
527                 }
528         }
529
530         g_free(markfile);
531         return fp;
532 }
533
534 static gboolean procmsg_ignore_node(GNode *node, gpointer data)
535 {
536         MsgInfo *msginfo = (MsgInfo *)node->data;
537         
538         procmsg_msginfo_set_flags(msginfo, MSG_IGNORE_THREAD, 0);
539
540         return FALSE;
541 }
542
543 /* return the reversed thread tree */
544 GNode *procmsg_get_thread_tree(GSList *mlist)
545 {
546         GNode *root, *parent, *node, *next;
547         GHashTable *msgid_table;
548         GHashTable *subject_table;
549         MsgInfo *msginfo;
550         const gchar *msgid;
551         const gchar *subject;
552         GNode *found_subject;
553
554         root = g_node_new(NULL);
555         msgid_table = g_hash_table_new(g_str_hash, g_str_equal);
556         subject_table = g_hash_table_new(g_str_hash, g_str_equal);
557
558         for (; mlist != NULL; mlist = mlist->next) {
559                 msginfo = (MsgInfo *)mlist->data;
560                 parent = root;
561
562                 if (msginfo->inreplyto) {
563                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
564                         if (parent == NULL) {
565                                 parent = root;
566                         } else {
567                                 if (MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
568                                         procmsg_msginfo_set_flags(msginfo, MSG_IGNORE_THREAD, 0);
569                                 }
570                         }
571                 }
572                 node = g_node_insert_data_before
573                         (parent, parent == root ? parent->children : NULL,
574                          msginfo);
575                 if ((msgid = msginfo->msgid) &&
576                     g_hash_table_lookup(msgid_table, msgid) == NULL)
577                         g_hash_table_insert(msgid_table, (gchar *)msgid, node);
578
579                 subject = msginfo->subject;
580                 found_subject = subject_table_lookup(subject_table,
581                                                      (gchar *) subject);
582                 if (found_subject == NULL)
583                         subject_table_insert(subject_table, (gchar *) subject,
584                                              node);
585                 else {
586                         /* replace if msg in table is older than current one 
587                          * can add here more stuff.  */
588                         if ( ((MsgInfo*)(found_subject->data))->date_t >
589                              ((MsgInfo*)(node->data))->date_t )  {
590                                 subject_table_remove(subject_table, (gchar *) subject);
591                                 subject_table_insert(subject_table, (gchar *) subject, node);
592                         }       
593                 }
594         }
595
596         /* complete the unfinished threads */
597         for (node = root->children; node != NULL; ) {
598                 next = node->next;
599                 msginfo = (MsgInfo *)node->data;
600                 parent = NULL;
601                 if (msginfo->inreplyto) 
602                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
603                 if (parent && parent != node) {
604                         g_node_unlink(node);
605                         g_node_insert_before
606                                 (parent, parent->children, node);
607                         /* CLAWS: ignore thread */
608                         if (MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
609                                 g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, procmsg_ignore_node, NULL);
610                         }
611                 }
612                 node = next;
613         }
614
615         /* CLAWS: now see if the first level (below root) still has some nodes that can be
616          * threaded by subject line. we need to handle this in a special way to prevent
617          * circular reference from a node that has already been threaded by IN-REPLY-TO
618          * but is also in the subject line hash table */
619         for (node = root->children; node != NULL; ) {
620                 next = node->next;
621                 msginfo = (MsgInfo *) node->data;
622                 parent = NULL;
623                 if (subject_is_reply(msginfo->subject)) {
624                         parent = subject_table_lookup(subject_table,
625                                                       msginfo->subject);
626                         /* the node may already be threaded by IN-REPLY-TO,
627                            so go up in the tree to find the parent node */
628                         if (parent != NULL) {
629                                 if (g_node_is_ancestor(node, parent))
630                                         parent = NULL;
631                                 if (parent == node)
632                                         parent = NULL;
633                         }
634
635                         if (parent) {
636                                 g_node_unlink(node);
637                                 g_node_append(parent, node);
638                                 /* CLAWS: ignore thread */
639                                 if (MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
640                                         g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, procmsg_ignore_node, NULL);
641                                 }
642                         }
643                 }                                       
644                 node = next;
645         }               
646
647         g_hash_table_destroy(subject_table);
648         g_hash_table_destroy(msgid_table);
649
650         return root;
651 }
652
653 void procmsg_move_messages(GSList *mlist)
654 {
655         GSList *cur, *movelist = NULL;
656         MsgInfo *msginfo;
657         FolderItem *dest = NULL;
658
659         if (!mlist) return;
660
661         folder_item_update_freeze();
662
663         for (cur = mlist; cur != NULL; cur = cur->next) {
664                 msginfo = (MsgInfo *)cur->data;
665                 if (!dest) {
666                         dest = msginfo->to_folder;
667                         movelist = g_slist_append(movelist, msginfo);
668                 } else if (dest == msginfo->to_folder) {
669                         movelist = g_slist_append(movelist, msginfo);
670                 } else {
671                         folder_item_move_msgs_with_dest(dest, movelist);
672                         g_slist_free(movelist);
673                         movelist = NULL;
674                         dest = msginfo->to_folder;
675                         movelist = g_slist_append(movelist, msginfo);
676                 }
677                 procmsg_msginfo_set_to_folder(msginfo, NULL);
678         }
679
680         if (movelist) {
681                 folder_item_move_msgs_with_dest(dest, movelist);
682                 g_slist_free(movelist);
683         }
684
685         folder_item_update_thaw();
686 }
687
688 void procmsg_copy_messages(GSList *mlist)
689 {
690         GSList *cur, *copylist = NULL;
691         MsgInfo *msginfo;
692         FolderItem *dest = NULL;
693
694         if (!mlist) return;
695
696         folder_item_update_freeze();
697
698         for (cur = mlist; cur != NULL; cur = cur->next) {
699                 msginfo = (MsgInfo *)cur->data;
700                 if (!dest) {
701                         dest = msginfo->to_folder;
702                         copylist = g_slist_append(copylist, msginfo);
703                 } else if (dest == msginfo->to_folder) {
704                         copylist = g_slist_append(copylist, msginfo);
705                 } else {
706                         folder_item_copy_msgs_with_dest(dest, copylist);
707                         g_slist_free(copylist);
708                         copylist = NULL;
709                         dest = msginfo->to_folder;
710                         copylist = g_slist_append(copylist, msginfo);
711                 }
712                 procmsg_msginfo_set_to_folder(msginfo, NULL);
713         }
714
715         if (copylist) {
716                 folder_item_copy_msgs_with_dest(dest, copylist);
717                 g_slist_free(copylist);
718         }
719
720         folder_item_update_thaw();
721 }
722
723 gchar *procmsg_get_message_file_path(MsgInfo *msginfo)
724 {
725         gchar *path, *file;
726
727         g_return_val_if_fail(msginfo != NULL, NULL);
728
729         if (msginfo->plaintext_file)
730                 file = g_strdup(msginfo->plaintext_file);
731         else {
732                 path = folder_item_get_path(msginfo->folder);
733                 file = g_strconcat(path, G_DIR_SEPARATOR_S,
734                                    itos(msginfo->msgnum), NULL);
735                 g_free(path);
736         }
737
738         return file;
739 }
740
741 gchar *procmsg_get_message_file(MsgInfo *msginfo)
742 {
743         gchar *filename = NULL;
744
745         g_return_val_if_fail(msginfo != NULL, NULL);
746
747         filename = folder_item_fetch_msg(msginfo->folder, msginfo->msgnum);
748         if (!filename)
749                 g_warning("can't fetch message %d\n", msginfo->msgnum);
750
751         return filename;
752 }
753
754 FILE *procmsg_open_message(MsgInfo *msginfo)
755 {
756         FILE *fp;
757         gchar *file;
758
759         g_return_val_if_fail(msginfo != NULL, NULL);
760
761         file = procmsg_get_message_file_path(msginfo);
762         g_return_val_if_fail(file != NULL, NULL);
763
764         if (!is_file_exist(file)) {
765                 g_free(file);
766                 file = procmsg_get_message_file(msginfo);
767                 g_return_val_if_fail(file != NULL, NULL);
768         }
769
770         if ((fp = fopen(file, "rb")) == NULL) {
771                 FILE_OP_ERROR(file, "fopen");
772                 g_free(file);
773                 return NULL;
774         }
775
776         g_free(file);
777
778         if (MSG_IS_QUEUED(msginfo->flags) || MSG_IS_DRAFT(msginfo->flags)) {
779                 gchar buf[BUFFSIZE];
780
781                 while (fgets(buf, sizeof(buf), fp) != NULL)
782                         if (buf[0] == '\r' || buf[0] == '\n') break;
783         }
784
785         return fp;
786 }
787
788 #if USE_GPGME
789 FILE *procmsg_open_message_decrypted(MsgInfo *msginfo, MimeInfo **mimeinfo)
790 {
791         FILE *fp;
792         MimeInfo *mimeinfo_;
793
794         g_return_val_if_fail(msginfo != NULL, NULL);
795
796         if (mimeinfo) *mimeinfo = NULL;
797
798         if ((fp = procmsg_open_message(msginfo)) == NULL) return NULL;
799
800         mimeinfo_ = procmime_scan_mime_header(fp);
801         if (!mimeinfo_) {
802                 fclose(fp);
803                 return NULL;
804         }
805
806         if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
807             rfc2015_is_encrypted(mimeinfo_)) {
808                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
809         }
810
811         if (MSG_IS_ENCRYPTED(msginfo->flags) &&
812             (!msginfo->plaintext_file || msginfo->decryption_failed)) {
813                 rfc2015_decrypt_message(msginfo, mimeinfo_, fp);
814                 if (msginfo->plaintext_file &&
815                     !msginfo->decryption_failed) {
816                         fclose(fp);
817                         procmime_mimeinfo_free_all(mimeinfo_);
818                         if ((fp = procmsg_open_message(msginfo)) == NULL)
819                                 return NULL;
820                         mimeinfo_ = procmime_scan_mime_header(fp);
821                         if (!mimeinfo_) {
822                                 fclose(fp);
823                                 return NULL;
824                         }
825                 }
826         }
827
828         if (mimeinfo) *mimeinfo = mimeinfo_;
829         return fp;
830 }
831 #endif
832
833 gboolean procmsg_msg_exist(MsgInfo *msginfo)
834 {
835         gchar *path;
836         gboolean ret;
837
838         if (!msginfo) return FALSE;
839
840         path = folder_item_get_path(msginfo->folder);
841         change_dir(path);
842         ret = !folder_item_is_msg_changed(msginfo->folder, msginfo);
843         g_free(path);
844
845         return ret;
846 }
847
848 void procmsg_empty_trash(void)
849 {
850         FolderItem *trash;
851         GList *cur;
852
853         for (cur = folder_get_list(); cur != NULL; cur = cur->next) {
854                 trash = FOLDER(cur->data)->trash;
855                 if (trash && trash->total > 0)
856                         folder_item_remove_all_msg(trash);
857         }
858 }
859
860 gint procmsg_send_queue(FolderItem *queue, gboolean save_msgs)
861 {
862         gint ret = 0;
863         GSList *list, *elem;
864
865         if (!queue)
866                 queue = folder_get_default_queue();
867         g_return_val_if_fail(queue != NULL, -1);
868
869         folder_item_scan(queue);
870         list = folder_item_get_msg_list(queue);
871
872
873         for (elem = list; elem != NULL; elem = elem->next) {
874                 gchar *file;
875                 MsgInfo *msginfo;
876                 
877                 msginfo = (MsgInfo *)(elem->data);
878
879                 file = folder_item_fetch_msg(queue, msginfo->msgnum);
880                 if (file) {
881                         if (procmsg_send_message_queue(file) < 0) {
882                                 g_warning("Sending queued message %d failed.\n", msginfo->msgnum);
883                                 ret = -1;
884                         } else {
885                         /* CLAWS: 
886                          * We save in procmsg_send_message_queue because
887                          * we need the destination folder from the queue
888                          * header
889                                                 
890                                 if (save_msgs)
891                                         procmsg_save_to_outbox
892                                                 (queue->folder->outbox,
893                                                  file, TRUE);
894 */
895                                 folder_item_remove_msg(queue, msginfo->msgnum);
896                         }
897                         g_free(file);
898                 }
899                 procmsg_msginfo_free(msginfo);
900         }
901
902         return ret;
903 }
904
905 gint procmsg_remove_special_headers(const gchar *in, const gchar *out)
906 {
907         FILE *fp, *outfp;
908         gchar buf[BUFFSIZE];
909         
910         if ((fp = fopen(in, "rb")) == NULL) {
911                 FILE_OP_ERROR(in, "fopen");
912                 return -1;
913         }
914         if ((outfp = fopen(out, "wb")) == NULL) {
915                 FILE_OP_ERROR(out, "fopen");
916                 fclose(fp);
917                 return -1;
918         }
919         while (fgets(buf, sizeof(buf), fp) != NULL)
920                 if (buf[0] == '\r' || buf[0] == '\n') break;
921         while (fgets(buf, sizeof(buf), fp) != NULL)
922                 fputs(buf, outfp);
923         fclose(outfp);
924         fclose(fp);
925         return 0;
926
927 }
928 gint procmsg_save_to_outbox(FolderItem *outbox, const gchar *file,
929                             gboolean is_queued)
930 {
931         gint num;
932         MsgInfo *msginfo;
933
934         debug_print("saving sent message...\n");
935
936         if (!outbox)
937                 outbox = folder_get_default_outbox();
938         g_return_val_if_fail(outbox != NULL, -1);
939
940         /* remove queueing headers */
941         if (is_queued) {
942                 gchar tmp[MAXPATHLEN + 1];
943
944                 g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.out.%08x",
945                            get_rc_dir(), G_DIR_SEPARATOR, (guint)random());
946                 
947                 if (procmsg_remove_special_headers(file, tmp) !=0)
948                         return -1;
949
950                 folder_item_scan(outbox);
951                 if ((num = folder_item_add_msg(outbox, tmp, TRUE)) < 0) {
952                         g_warning("can't save message\n");
953                         unlink(tmp);
954                         return -1;
955                 }
956         } else {
957                 folder_item_scan(outbox);
958                 if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
959                         g_warning("can't save message\n");
960                         return -1;
961                 }
962                 return -1;
963         }
964         msginfo = folder_item_get_msginfo(outbox, num);
965         if (msginfo != NULL) {
966             procmsg_msginfo_unset_flags(msginfo, ~0, 0);
967             procmsg_msginfo_free(msginfo);
968         }
969         folder_item_update(outbox, TRUE);
970
971         return 0;
972 }
973
974 void procmsg_print_message(MsgInfo *msginfo, const gchar *cmdline)
975 {
976         static const gchar *def_cmd = "lpr %s";
977         static guint id = 0;
978         gchar *prtmp;
979         FILE *tmpfp, *prfp;
980         gchar buf[1024];
981         gchar *p;
982
983         g_return_if_fail(msginfo);
984
985         if ((tmpfp = procmime_get_first_text_content(msginfo)) == NULL) {
986                 g_warning("Can't get text part\n");
987                 return;
988         }
989
990         prtmp = g_strdup_printf("%s%cprinttmp.%08x",
991                                 get_mime_tmp_dir(), G_DIR_SEPARATOR, id++);
992
993         if ((prfp = fopen(prtmp, "wb")) == NULL) {
994                 FILE_OP_ERROR(prtmp, "fopen");
995                 g_free(prtmp);
996                 fclose(tmpfp);
997                 return;
998         }
999
1000         if (msginfo->date) fprintf(prfp, "Date: %s\n", msginfo->date);
1001         if (msginfo->from) fprintf(prfp, "From: %s\n", msginfo->from);
1002         if (msginfo->to)   fprintf(prfp, "To: %s\n", msginfo->to);
1003         if (msginfo->cc)   fprintf(prfp, "Cc: %s\n", msginfo->cc);
1004         if (msginfo->newsgroups)
1005                 fprintf(prfp, "Newsgroups: %s\n", msginfo->newsgroups);
1006         if (msginfo->subject) fprintf(prfp, "Subject: %s\n", msginfo->subject);
1007         fputc('\n', prfp);
1008
1009         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
1010                 fputs(buf, prfp);
1011
1012         fclose(prfp);
1013         fclose(tmpfp);
1014
1015         if (cmdline && (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
1016             !strchr(p + 2, '%'))
1017                 g_snprintf(buf, sizeof(buf) - 1, cmdline, prtmp);
1018         else {
1019                 if (cmdline)
1020                         g_warning("Print command line is invalid: `%s'\n",
1021                                   cmdline);
1022                 g_snprintf(buf, sizeof(buf) - 1, def_cmd, prtmp);
1023         }
1024
1025         g_free(prtmp);
1026
1027         g_strchomp(buf);
1028         if (buf[strlen(buf) - 1] != '&') strcat(buf, "&");
1029         system(buf);
1030 }
1031
1032 MsgInfo *procmsg_msginfo_new_ref(MsgInfo *msginfo)
1033 {
1034         msginfo->refcnt++;
1035         
1036         return msginfo;
1037 }
1038
1039 MsgInfo *procmsg_msginfo_new()
1040 {
1041         MsgInfo *newmsginfo;
1042
1043         newmsginfo = g_new0(MsgInfo, 1);
1044         newmsginfo->refcnt = 1;
1045         
1046         return newmsginfo;
1047 }
1048
1049 MsgInfo *procmsg_msginfo_copy(MsgInfo *msginfo)
1050 {
1051         MsgInfo *newmsginfo;
1052
1053         if (msginfo == NULL) return NULL;
1054
1055         newmsginfo = g_new0(MsgInfo, 1);
1056
1057         newmsginfo->refcnt = 1;
1058
1059 #define MEMBCOPY(mmb)   newmsginfo->mmb = msginfo->mmb
1060 #define MEMBDUP(mmb)    newmsginfo->mmb = msginfo->mmb ? \
1061                         g_strdup(msginfo->mmb) : NULL
1062
1063         MEMBCOPY(msgnum);
1064         MEMBCOPY(size);
1065         MEMBCOPY(mtime);
1066         MEMBCOPY(date_t);
1067         MEMBCOPY(flags);
1068
1069         MEMBDUP(fromname);
1070
1071         MEMBDUP(date);
1072         MEMBDUP(from);
1073         MEMBDUP(to);
1074         MEMBDUP(cc);
1075         MEMBDUP(newsgroups);
1076         MEMBDUP(subject);
1077         MEMBDUP(msgid);
1078         MEMBDUP(inreplyto);
1079         MEMBDUP(xref);
1080
1081         MEMBCOPY(folder);
1082         MEMBCOPY(to_folder);
1083
1084         MEMBDUP(xface);
1085         MEMBDUP(dispositionnotificationto);
1086         MEMBDUP(returnreceiptto);
1087         MEMBDUP(references);
1088
1089         MEMBCOPY(score);
1090         MEMBCOPY(threadscore);
1091
1092         return newmsginfo;
1093 }
1094
1095 MsgInfo *procmsg_msginfo_get_full_info(MsgInfo *msginfo)
1096 {
1097         MsgInfo *full_msginfo;
1098         gchar *file;
1099
1100         if (msginfo == NULL) return NULL;
1101
1102         file = procmsg_get_message_file(msginfo);
1103         if (!file) {
1104                 g_warning("procmsg_msginfo_get_full_info(): can't get message file.\n");
1105                 return NULL;
1106         }
1107
1108         full_msginfo = procheader_parse_file(file, msginfo->flags, TRUE, FALSE);
1109         g_free(file);
1110         if (!full_msginfo) return NULL;
1111
1112         full_msginfo->msgnum = msginfo->msgnum;
1113         full_msginfo->size = msginfo->size;
1114         full_msginfo->mtime = msginfo->mtime;
1115         full_msginfo->folder = msginfo->folder;
1116 #if USE_GPGME
1117         full_msginfo->plaintext_file = g_strdup(msginfo->plaintext_file);
1118         full_msginfo->decryption_failed = msginfo->decryption_failed;
1119 #endif
1120         procmsg_msginfo_set_to_folder(full_msginfo, msginfo->to_folder);
1121
1122         return full_msginfo;
1123 }
1124
1125 void procmsg_msginfo_free(MsgInfo *msginfo)
1126 {
1127         if (msginfo == NULL) return;
1128
1129         msginfo->refcnt--;
1130         if (msginfo->refcnt > 0)
1131                 return;
1132
1133         debug_print("freeing msginfo %d is %s\n", msginfo->msgnum, msginfo->folder ? msginfo->folder->path : "(nil)");
1134
1135         if (msginfo->to_folder) {
1136                 msginfo->to_folder->op_count--;
1137                 folder_item_update(msginfo->to_folder, F_ITEM_UPDATE_MSGCNT);
1138         }
1139
1140         g_free(msginfo->fromspace);
1141         g_free(msginfo->references);
1142         g_free(msginfo->returnreceiptto);
1143         g_free(msginfo->dispositionnotificationto);
1144         g_free(msginfo->xface);
1145
1146         g_free(msginfo->fromname);
1147
1148         g_free(msginfo->date);
1149         g_free(msginfo->from);
1150         g_free(msginfo->to);
1151         g_free(msginfo->cc);
1152         g_free(msginfo->newsgroups);
1153         g_free(msginfo->subject);
1154         g_free(msginfo->msgid);
1155         g_free(msginfo->inreplyto);
1156         g_free(msginfo->xref);
1157
1158         g_free(msginfo);
1159 }
1160
1161 guint procmsg_msginfo_memusage(MsgInfo *msginfo)
1162 {
1163         guint memusage = 0;
1164         
1165         memusage += sizeof(MsgInfo);
1166         if (msginfo->fromname)
1167                 memusage += strlen(msginfo->fromname);
1168         if (msginfo->date)
1169                 memusage += strlen(msginfo->date);
1170         if (msginfo->from)
1171                 memusage += strlen(msginfo->from);
1172         if (msginfo->to)
1173                 memusage += strlen(msginfo->to);
1174         if (msginfo->cc)
1175                 memusage += strlen(msginfo->cc);
1176         if (msginfo->newsgroups)
1177                 memusage += strlen(msginfo->newsgroups);
1178         if (msginfo->subject)
1179                 memusage += strlen(msginfo->subject);
1180         if (msginfo->msgid)
1181                 memusage += strlen(msginfo->msgid);
1182         if (msginfo->inreplyto)
1183                 memusage += strlen(msginfo->inreplyto);
1184         if (msginfo->xface)
1185                 memusage += strlen(msginfo->xface);
1186         if (msginfo->dispositionnotificationto)
1187                 memusage += strlen(msginfo->dispositionnotificationto);
1188         if (msginfo->returnreceiptto)
1189                 memusage += strlen(msginfo->returnreceiptto);
1190         if (msginfo->references)
1191                 memusage += strlen(msginfo->references);
1192         if (msginfo->fromspace)
1193                 memusage += strlen(msginfo->fromspace);
1194
1195         return memusage;
1196 }
1197
1198 gint procmsg_cmp_msgnum_for_sort(gconstpointer a, gconstpointer b)
1199 {
1200         const MsgInfo *msginfo1 = a;
1201         const MsgInfo *msginfo2 = b;
1202
1203         if (!msginfo1)
1204                 return -1;
1205         if (!msginfo2)
1206                 return -1;
1207
1208         return msginfo1->msgnum - msginfo2->msgnum;
1209 }
1210
1211 enum
1212 {
1213         Q_SENDER           = 0,
1214         Q_SMTPSERVER       = 1,
1215         Q_RECIPIENTS       = 2,
1216         Q_NEWSGROUPS       = 3,
1217         Q_MAIL_ACCOUNT_ID  = 4,
1218         Q_NEWS_ACCOUNT_ID  = 5,
1219         Q_SAVE_COPY_FOLDER = 6,
1220         Q_REPLY_MESSAGE_ID = 7,
1221         Q_FWD_MESSAGE_ID   = 8
1222 };
1223
1224 gint procmsg_send_message_queue(const gchar *file)
1225 {
1226         static HeaderEntry qentry[] = {{"S:",    NULL, FALSE},
1227                                        {"SSV:",  NULL, FALSE},
1228                                        {"R:",    NULL, FALSE},
1229                                        {"NG:",   NULL, FALSE},
1230                                        {"MAID:", NULL, FALSE},
1231                                        {"NAID:", NULL, FALSE},
1232                                        {"SCF:",  NULL, FALSE},
1233                                        {"RMID:", NULL, FALSE},
1234                                        {"FMID:", NULL, FALSE},
1235                                        {NULL,    NULL, FALSE}};
1236         FILE *fp;
1237         gint filepos;
1238         gint mailval = 0, newsval = 0;
1239         gchar *from = NULL;
1240         gchar *smtpserver = NULL;
1241         GSList *to_list = NULL;
1242         GSList *newsgroup_list = NULL;
1243         gchar *savecopyfolder = NULL;
1244         gchar *replymessageid = NULL;
1245         gchar *fwdmessageid = NULL;
1246         gchar buf[BUFFSIZE];
1247         gint hnum;
1248         PrefsAccount *mailac = NULL, *newsac = NULL;
1249         int local = 0;
1250
1251         g_return_val_if_fail(file != NULL, -1);
1252
1253         if ((fp = fopen(file, "rb")) == NULL) {
1254                 FILE_OP_ERROR(file, "fopen");
1255                 return -1;
1256         }
1257
1258         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, qentry))
1259                != -1) {
1260                 gchar *p = buf + strlen(qentry[hnum].name);
1261
1262                 switch (hnum) {
1263                 case Q_SENDER:
1264                         if (!from) from = g_strdup(p);
1265                         break;
1266                 case Q_SMTPSERVER:
1267                         if (!smtpserver) smtpserver = g_strdup(p);
1268                         break;
1269                 case Q_RECIPIENTS:
1270                         to_list = address_list_append(to_list, p);
1271                         break;
1272                 case Q_NEWSGROUPS:
1273                         newsgroup_list = newsgroup_list_append(newsgroup_list, p);
1274                         break;
1275                 case Q_MAIL_ACCOUNT_ID:
1276                         mailac = account_find_from_id(atoi(p));
1277                         break;
1278                 case Q_NEWS_ACCOUNT_ID:
1279                         newsac = account_find_from_id(atoi(p));
1280                         break;
1281                 case Q_SAVE_COPY_FOLDER:
1282                         if (!savecopyfolder) savecopyfolder = g_strdup(p);
1283                         break;
1284                 case Q_REPLY_MESSAGE_ID:
1285                         if (!replymessageid) replymessageid = g_strdup(p);
1286                         break;
1287                 case Q_FWD_MESSAGE_ID:
1288                         if (!fwdmessageid) fwdmessageid = g_strdup(p);
1289                         break;
1290                 }
1291         }
1292         filepos = ftell(fp);
1293
1294         if (to_list) {
1295                 debug_print("Sending message by mail\n");
1296                 if (!from) {
1297                         g_warning("Queued message header is broken.\n");
1298                         mailval = -1;
1299                 } else if (mailac && mailac->use_mail_command &&
1300                            mailac->mail_command && (* mailac->mail_command)) {
1301                         mailval = send_message_local(mailac->mail_command, fp);
1302                         local = 1;
1303                 } else if (prefs_common.use_extsend && prefs_common.extsend_cmd) {
1304                         mailval = send_message_local(prefs_common.extsend_cmd, fp);
1305                         local = 1;
1306                 } else {
1307                         if (!mailac) {
1308                                 mailac = account_find_from_smtp_server(from, smtpserver);
1309                                 if (!mailac) {
1310                                         g_warning("Account not found. "
1311                                                     "Using current account...\n");
1312                                         mailac = cur_account;
1313                                 }
1314                         }
1315
1316                         if (mailac)
1317                                 mailval = send_message_smtp(mailac, to_list, fp);
1318                         else {
1319                                 PrefsAccount tmp_ac;
1320
1321                                 g_warning("Account not found.\n");
1322
1323                                 memset(&tmp_ac, 0, sizeof(PrefsAccount));
1324                                 tmp_ac.address = from;
1325                                 tmp_ac.smtp_server = smtpserver;
1326                                 tmp_ac.smtpport = SMTP_PORT;
1327                                 mailval = send_message_smtp(&tmp_ac, to_list, fp);
1328                         }
1329                 }
1330                 if (mailval < 0) {
1331                         if (!local)
1332                                 alertpanel_error_log(
1333                                         _("Error occurred while sending the message to `%s'."),
1334                                         mailac ? mailac->smtp_server : smtpserver);
1335                         else
1336                                 alertpanel_error_log(
1337                                         _("Error occurred while sending the message with command `%s'."),
1338                                         (mailac && mailac->use_mail_command && 
1339                                          mailac->mail_command && (*mailac->mail_command)) ? 
1340                                                 mailac->mail_command : prefs_common.extsend_cmd);
1341                 }
1342         }
1343
1344         fseek(fp, filepos, SEEK_SET);
1345         if (newsgroup_list && (newsval == 0)) {
1346                 Folder *folder;
1347                 gchar *tmp = NULL;
1348                 FILE *tmpfp;
1349
1350                 /* write to temporary file */
1351                 tmp = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
1352                             G_DIR_SEPARATOR, (gint)file);
1353                 if ((tmpfp = fopen(tmp, "wb")) == NULL) {
1354                         FILE_OP_ERROR(tmp, "fopen");
1355                         newsval = -1;
1356                         alertpanel_error(_("Could not create temporary file for news sending."));
1357                 } else {
1358                         if (change_file_mode_rw(tmpfp, tmp) < 0) {
1359                                 FILE_OP_ERROR(tmp, "chmod");
1360                                 g_warning("can't change file mode\n");
1361                         }
1362
1363                         while ((newsval == 0) && fgets(buf, sizeof(buf), fp) != NULL) {
1364                                 if (fputs(buf, tmpfp) == EOF) {
1365                                         FILE_OP_ERROR(tmp, "fputs");
1366                                         newsval = -1;
1367                                         alertpanel_error(_("Error when writing temporary file for news sending."));
1368                                 }
1369                         }
1370                         fclose(tmpfp);
1371
1372                         if (newsval == 0) {
1373                                 debug_print("Sending message by news\n");
1374
1375                                 folder = FOLDER(newsac->folder);
1376
1377                                 newsval = news_post(folder, tmp);
1378                                 if (newsval < 0) {
1379                                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1380                                                  newsac->nntp_server);
1381                                 }
1382                         }
1383                         unlink(tmp);
1384                 }
1385                 g_free(tmp);
1386         }
1387
1388         slist_free_strings(to_list);
1389         g_slist_free(to_list);
1390         slist_free_strings(newsgroup_list);
1391         g_slist_free(newsgroup_list);
1392         g_free(from);
1393         g_free(smtpserver);
1394         fclose(fp);
1395
1396         /* save message to outbox */
1397         if (mailval == 0 && newsval == 0 && savecopyfolder) {
1398                 FolderItem *outbox;
1399
1400                 debug_print("saving sent message...\n");
1401
1402                 outbox = folder_find_item_from_identifier(savecopyfolder);
1403                 if (!outbox)
1404                         outbox = folder_get_default_outbox();
1405
1406                 procmsg_save_to_outbox(outbox, file, TRUE);
1407         }
1408
1409         if (replymessageid != NULL || fwdmessageid != NULL) {
1410                 gchar **tokens;
1411                 FolderItem *item;
1412                 
1413                 if (replymessageid != NULL)
1414                         tokens = g_strsplit(replymessageid, "\x7f", 0);
1415                 else
1416                         tokens = g_strsplit(fwdmessageid, "\x7f", 0);
1417                 item = folder_find_item_from_identifier(tokens[0]);
1418                 if (item != NULL) {
1419                         MsgInfo *msginfo;
1420                         
1421                         msginfo = folder_item_get_msginfo(item, atoi(tokens[1]));
1422                         if ((msginfo != NULL) && (strcmp(msginfo->msgid, tokens[2]) != 0)) {
1423                                 procmsg_msginfo_free(msginfo);
1424                                 msginfo = NULL;
1425                         }
1426                         
1427                         if (msginfo == NULL) {
1428                                 msginfo = folder_item_get_msginfo_by_msgid(item, tokens[2]);
1429                         }
1430                         
1431                         if (msginfo != NULL) {
1432                                 if (replymessageid != NULL) {
1433                                         procmsg_msginfo_unset_flags(msginfo, MSG_FORWARDED, 0);
1434                                         procmsg_msginfo_set_flags(msginfo, MSG_REPLIED, 0);
1435                                 } 
1436                                 else {
1437                                         procmsg_msginfo_unset_flags(msginfo, MSG_REPLIED, 0);
1438                                         procmsg_msginfo_set_flags(msginfo, MSG_FORWARDED, 0);
1439                                 }
1440                                 procmsg_msginfo_free(msginfo);
1441                         }
1442                 }
1443                 g_strfreev(tokens);
1444         }
1445
1446         g_free(savecopyfolder);
1447         g_free(replymessageid);
1448         g_free(fwdmessageid);
1449         
1450         return (newsval != 0 ? newsval : mailval);
1451 }
1452
1453 #define CHANGE_FLAGS(msginfo) \
1454 { \
1455 if (msginfo->folder->folder->change_flags != NULL) \
1456 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
1457                                       msginfo->folder, \
1458                                       msginfo); \
1459 }
1460
1461 void procmsg_msginfo_set_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1462 {
1463         FolderItem *item;
1464         MsgInfoUpdate msginfo_update;
1465
1466         g_return_if_fail(msginfo != NULL);
1467         item = msginfo->folder;
1468         g_return_if_fail(item != NULL);
1469         
1470         debug_print("Setting flags for message %d in folder %s\n", msginfo->msgnum, item->path);
1471
1472         /* if new flag is set */
1473         if ((perm_flags & MSG_NEW) && !MSG_IS_NEW(msginfo->flags) &&
1474            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1475                 item->new++;
1476         }
1477
1478         /* if unread flag is set */
1479         if ((perm_flags & MSG_UNREAD) && !MSG_IS_UNREAD(msginfo->flags) &&
1480            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1481                 item->unread++;
1482         }
1483
1484         if (!MSG_IS_UNREAD(msginfo->flags) &&(perm_flags & MSG_UNREAD)
1485         && procmsg_msg_has_marked_parent(msginfo)) {
1486                 item->unreadmarked++;
1487         }
1488         
1489         if (!MSG_IS_MARKED(msginfo->flags) && (perm_flags & MSG_MARKED)) {
1490                 procmsg_update_unread_children(msginfo, TRUE);
1491         }
1492
1493
1494         /* if ignore thread flag is set */
1495         if ((perm_flags & MSG_IGNORE_THREAD) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1496                 if (MSG_IS_NEW(msginfo->flags) || (perm_flags & MSG_NEW)) {
1497                         item->new--;
1498                 }
1499                 if (MSG_IS_UNREAD(msginfo->flags) || (perm_flags & MSG_UNREAD)) {
1500                         item->unread--;
1501                 }
1502                 if ((perm_flags & MSG_UNREAD) || (MSG_IS_UNREAD(msginfo->flags)
1503                 && procmsg_msg_has_marked_parent(msginfo))) {
1504                         item->unreadmarked--;
1505                 }
1506                 if ((perm_flags & MSG_MARKED) || (MSG_IS_MARKED(msginfo->flags)
1507                 && !MSG_IS_IGNORE_THREAD(msginfo->flags))) {
1508                         procmsg_update_unread_children(msginfo, FALSE);
1509                 }
1510
1511         }
1512
1513         if (MSG_IS_IMAP(msginfo->flags))
1514                 imap_msg_set_perm_flags(msginfo, perm_flags);
1515
1516         msginfo->flags.perm_flags |= perm_flags;
1517         msginfo->flags.tmp_flags |= tmp_flags;
1518
1519         msginfo_update.msginfo = msginfo;
1520         hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
1521         folder_item_update(msginfo->folder, F_ITEM_UPDATE_MSGCNT);
1522
1523         CHANGE_FLAGS(msginfo);
1524         procmsg_msginfo_write_flags(msginfo);
1525 }
1526
1527 void procmsg_msginfo_unset_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1528 {
1529         FolderItem *item;
1530         MsgInfoUpdate msginfo_update;
1531
1532         g_return_if_fail(msginfo != NULL);
1533         item = msginfo->folder;
1534         g_return_if_fail(item != NULL); 
1535         
1536         debug_print("Unsetting flags for message %d in folder %s\n", msginfo->msgnum, item->path);
1537
1538         /* if new flag is unset */
1539         if ((perm_flags & MSG_NEW) && MSG_IS_NEW(msginfo->flags) &&
1540            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1541                 item->new--;
1542         }
1543
1544         /* if unread flag is unset */
1545         if ((perm_flags & MSG_UNREAD) && MSG_IS_UNREAD(msginfo->flags) &&
1546            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1547                 item->unread--;
1548         }
1549         
1550         if (MSG_IS_UNREAD(msginfo->flags) && (perm_flags & MSG_UNREAD)
1551         && !MSG_IS_IGNORE_THREAD(msginfo->flags)
1552         && procmsg_msg_has_marked_parent(msginfo)) {
1553                 item->unreadmarked--;
1554         }
1555
1556         if (MSG_IS_MARKED(msginfo->flags) && (perm_flags & MSG_MARKED)
1557         && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1558                 procmsg_update_unread_children(msginfo, FALSE);
1559         }
1560
1561         /* if ignore thread flag is unset */
1562         if ((perm_flags & MSG_IGNORE_THREAD) && MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1563                 if (MSG_IS_NEW(msginfo->flags) && !(perm_flags & MSG_NEW)) {
1564                         item->new++;
1565                 }
1566                 if (MSG_IS_UNREAD(msginfo->flags) && !(perm_flags & MSG_UNREAD)) {
1567                         item->unread++;
1568                 }
1569                 if (MSG_IS_UNREAD(msginfo->flags) && !(perm_flags & MSG_UNREAD)
1570                 && procmsg_msg_has_marked_parent(msginfo)) {
1571                         item->unreadmarked++;
1572                 }
1573                 if (MSG_IS_MARKED(msginfo->flags) && !(perm_flags & MSG_MARKED)) {
1574                         procmsg_update_unread_children(msginfo, TRUE);
1575                 }
1576
1577         }
1578
1579         if (MSG_IS_IMAP(msginfo->flags))
1580                 imap_msg_unset_perm_flags(msginfo, perm_flags);
1581
1582         msginfo->flags.perm_flags &= ~perm_flags;
1583         msginfo->flags.tmp_flags &= ~tmp_flags;
1584
1585         msginfo_update.msginfo = msginfo;
1586         hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
1587         folder_item_update(msginfo->folder, F_ITEM_UPDATE_MSGCNT);
1588
1589         CHANGE_FLAGS(msginfo);
1590         procmsg_msginfo_write_flags(msginfo);
1591 }
1592
1593 void procmsg_msginfo_write_flags(MsgInfo *msginfo)
1594 {
1595         gchar *destdir;
1596         FILE *fp;
1597
1598         destdir = folder_item_get_path(msginfo->folder);
1599         if (!is_dir_exist(destdir))
1600                 make_dir_hier(destdir);
1601
1602         if ((fp = procmsg_open_mark_file(destdir, TRUE))) {
1603                 procmsg_write_flags(msginfo, fp);
1604                 fclose(fp);
1605         } else {
1606                 g_warning("Can't open mark file.\n");
1607         }
1608         
1609         g_free(destdir);
1610 }
1611
1612 /*!
1613  *\brief        check for flags (e.g. mark) in prior msgs of current thread
1614  *
1615  *\param        info Current message
1616  *\param        perm_flags Flags to be checked
1617  *\param        parentmsgs Hash of prior msgs to avoid loops
1618  *
1619  *\return       gboolean TRUE if perm_flags are found
1620  */
1621 gboolean procmsg_msg_has_flagged_parent_real(MsgInfo *info,
1622                 MsgPermFlags perm_flags, GHashTable *parentmsgs)
1623 {
1624         MsgInfo *tmp;
1625
1626         g_return_val_if_fail(info != NULL, FALSE);
1627
1628         if (info != NULL && info->folder != NULL && info->inreplyto != NULL) {
1629                 tmp = folder_item_get_msginfo_by_msgid(info->folder,
1630                                 info->inreplyto);
1631                 if (tmp && (tmp->flags.perm_flags & perm_flags)) {
1632                         procmsg_msginfo_free(tmp);
1633                         return TRUE;
1634                 } else if (tmp != NULL) {
1635                         gboolean result;
1636
1637                         if (g_hash_table_lookup(parentmsgs, info)) {
1638                                 debug_print("loop detected: %s%c%d\n",
1639                                         folder_item_get_path(info->folder),
1640                                         G_DIR_SEPARATOR, info->msgnum);
1641                                 result = FALSE;
1642                         } else {
1643                                 g_hash_table_insert(parentmsgs, info, "1");
1644                                 result = procmsg_msg_has_flagged_parent_real(
1645                                     tmp, perm_flags, parentmsgs);
1646                         }
1647                         procmsg_msginfo_free(tmp);
1648                         return result;
1649                 } else {
1650                         return FALSE;
1651                 }
1652         } else
1653                 return FALSE;
1654 }
1655
1656 /*!
1657  *\brief        Callback for cleaning up hash of parentmsgs
1658  */
1659 gboolean parentmsgs_hash_remove(gpointer key,
1660                             gpointer value,
1661                             gpointer user_data)
1662 {
1663         return TRUE;
1664 }
1665
1666 /*!
1667  *\brief        Set up list of parentmsgs
1668  *              See procmsg_msg_has_flagged_parent_real()
1669  */
1670 gboolean procmsg_msg_has_flagged_parent(MsgInfo *info, MsgPermFlags perm_flags)
1671 {
1672         gboolean result;
1673         GHashTable *parentmsgs = g_hash_table_new(NULL, NULL); 
1674
1675         result = procmsg_msg_has_flagged_parent_real(info, perm_flags, parentmsgs);
1676         g_hash_table_foreach_remove(parentmsgs, parentmsgs_hash_remove, NULL);
1677         g_hash_table_destroy(parentmsgs);
1678         return result;
1679 }
1680
1681 /*!
1682  *\brief        Check if msgs prior in thread are marked
1683  *              See procmsg_msg_has_flagged_parent_real()
1684  */
1685 gboolean procmsg_msg_has_marked_parent(MsgInfo *info)
1686 {
1687         return procmsg_msg_has_flagged_parent(info, MSG_MARKED);
1688 }
1689
1690
1691 GSList *procmsg_find_children_func(MsgInfo *info, 
1692                                    GSList *children, GSList *all)
1693 {
1694         GSList *cur;
1695
1696         g_return_val_if_fail(info!=NULL, children);
1697         if (info->msgid == NULL)
1698                 return children;
1699
1700         for (cur = all; cur != NULL; cur = g_slist_next(cur)) {
1701                 MsgInfo *tmp = (MsgInfo *)cur->data;
1702                 if (tmp->inreplyto && !strcmp(tmp->inreplyto, info->msgid)) {
1703                         /* Check if message is already in the list */
1704                         if ((children == NULL) || 
1705                             (g_slist_index(children, tmp) == -1)) {
1706                                 children = g_slist_prepend(children,
1707                                                 procmsg_msginfo_new_ref(tmp));
1708                                 children = procmsg_find_children_func(tmp, 
1709                                                         children, 
1710                                                         all);
1711                         }
1712                 }
1713         }
1714         return children;
1715 }
1716
1717 GSList *procmsg_find_children (MsgInfo *info)
1718 {
1719         GSList *children;
1720         GSList *all, *cur;
1721
1722         g_return_val_if_fail(info!=NULL, NULL);
1723         all = folder_item_get_msg_list(info->folder);
1724         children = procmsg_find_children_func(info, NULL, all);
1725         if (children != NULL) {
1726                 for (cur = all; cur != NULL; cur = g_slist_next(cur)) {
1727                         /* this will not free the used pointers
1728                            created with procmsg_msginfo_new_ref */
1729                         procmsg_msginfo_free((MsgInfo *)cur->data);
1730                 }
1731         }
1732         g_slist_free(all);
1733
1734         return children;
1735 }
1736
1737 void procmsg_update_unread_children(MsgInfo *info, gboolean newly_marked)
1738 {
1739         GSList *children = procmsg_find_children(info);
1740         GSList *cur;
1741         for (cur = children; cur != NULL; cur = g_slist_next(cur)) {
1742                 MsgInfo *tmp = (MsgInfo *)cur->data;
1743                 if(MSG_IS_UNREAD(tmp->flags) && !MSG_IS_IGNORE_THREAD(tmp->flags)) {
1744                         if(newly_marked) 
1745                                 info->folder->unreadmarked++;
1746                         else
1747                                 info->folder->unreadmarked--;
1748                         folder_item_update(info->folder, F_ITEM_UPDATE_MSGCNT);
1749                 }
1750                 procmsg_msginfo_free(tmp);
1751         }
1752         g_slist_free(children);
1753 }
1754
1755 /**
1756  * Set the destination folder for a copy or move operation
1757  *
1758  * \param msginfo The message which's destination folder is changed
1759  * \param to_folder The destination folder for the operation
1760  */
1761 void procmsg_msginfo_set_to_folder(MsgInfo *msginfo, FolderItem *to_folder)
1762 {
1763         if(msginfo->to_folder != NULL) {
1764                 msginfo->to_folder->op_count--;
1765                 folder_item_update(msginfo->to_folder, F_ITEM_UPDATE_MSGCNT);
1766         }
1767         msginfo->to_folder = to_folder;
1768         if(to_folder != NULL) {
1769                 to_folder->op_count++;
1770                 folder_item_update(msginfo->to_folder, F_ITEM_UPDATE_MSGCNT);
1771         }
1772 }