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