sync with 0.8.1cvs21
[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 #include "imap.h"
43
44 typedef struct _FlagInfo        FlagInfo;
45
46 struct _FlagInfo
47 {
48         guint    msgnum;
49         MsgFlags flags;
50 };
51
52 static GHashTable *procmsg_read_mark_file       (const gchar    *folder);
53 void   procmsg_msginfo_write_flags              (MsgInfo        *msginfo);
54
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 /* return the reversed thread tree */
535 GNode *procmsg_get_thread_tree(GSList *mlist)
536 {
537         GNode *root, *parent, *node, *next;
538         GHashTable *msgid_table;
539         GHashTable *subject_table;
540         MsgInfo *msginfo;
541         const gchar *msgid;
542         const gchar *subject;
543         GNode *found_subject;
544
545         root = g_node_new(NULL);
546         msgid_table = g_hash_table_new(g_str_hash, g_str_equal);
547         subject_table = g_hash_table_new(g_str_hash, g_str_equal);
548
549         for (; mlist != NULL; mlist = mlist->next) {
550                 msginfo = (MsgInfo *)mlist->data;
551                 parent = root;
552
553                 if (msginfo->inreplyto) {
554                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
555                         if (parent == NULL) {
556                                 parent = root;
557                         } else {
558                                 if(MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
559                                         procmsg_msginfo_set_flags(msginfo, MSG_IGNORE_THREAD, 0);
560                                 }
561                         }
562                 }
563                 node = g_node_insert_data_before
564                         (parent, parent == root ? parent->children : NULL,
565                          msginfo);
566                 if ((msgid = msginfo->msgid) &&
567                     g_hash_table_lookup(msgid_table, msgid) == NULL)
568                         g_hash_table_insert(msgid_table, (gchar *)msgid, node);
569
570                 subject = msginfo->subject;
571                 found_subject = subject_table_lookup(subject_table,
572                                                      (gchar *) subject);
573                 if (found_subject == NULL)
574                         subject_table_insert(subject_table, (gchar *) subject,
575                                              node);
576                 else {
577                         /* replace if msg in table is older than current one 
578                          * can add here more stuff.  */
579                         if ( ((MsgInfo*)(found_subject->data))->date_t >
580                              ((MsgInfo*)(node->data))->date_t )  {
581                                 subject_table_remove(subject_table, (gchar *) subject);
582                                 subject_table_insert(subject_table, (gchar *) subject, node);
583                         }       
584                 }
585         }
586
587         /* complete the unfinished threads */
588         for (node = root->children; node != NULL; ) {
589                 next = node->next;
590                 msginfo = (MsgInfo *)node->data;
591                 parent = NULL;
592                 if (msginfo->inreplyto) 
593                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
594                 if (parent && parent != node) {
595                         g_node_unlink(node);
596                         g_node_insert_before
597                                 (parent, parent->children, node);
598                         /* CLAWS: ignore thread */
599                         if(MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
600                                 procmsg_msginfo_set_flags(msginfo, MSG_IGNORE_THREAD, 0);
601                         }
602                 }
603                 node = next;
604         }
605
606         /* CLAWS: now see if the first level (below root) still has some nodes that can be
607          * threaded by subject line. we need to handle this in a special way to prevent
608          * circular reference from a node that has already been threaded by IN-REPLY-TO
609          * but is also in the subject line hash table */
610         for (node = root->children; node != NULL; ) {
611                 next = node->next;
612                 msginfo = (MsgInfo *) node->data;
613                 parent = NULL;
614                 if (subject_is_reply(msginfo->subject)) {
615                         parent = subject_table_lookup(subject_table,
616                                                       msginfo->subject);
617                         /* the node may already be threaded by IN-REPLY-TO,
618                            so go up in the tree to find the parent node */
619                         if (parent != NULL) {
620                                 if (g_node_is_ancestor(node, parent))
621                                         parent = NULL;
622                                 if (parent == node)
623                                         parent = NULL;
624                         }
625
626                         if (parent) {
627                                 g_node_unlink(node);
628                                 g_node_append(parent, node);
629                                 /* CLAWS: ignore thread */
630                                 if(MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
631                                         procmsg_msginfo_set_flags(msginfo, MSG_IGNORE_THREAD, 0);
632                                 }
633                         }
634                 }                                       
635                 node = next;
636         }               
637                 
638         g_hash_table_destroy(subject_table);
639         g_hash_table_destroy(msgid_table);
640
641         return root;
642 }
643
644 void procmsg_move_messages(GSList *mlist)
645 {
646         GSList *cur, *movelist = NULL;
647         MsgInfo *msginfo;
648         FolderItem *dest = NULL;
649
650         if (!mlist) return;
651
652         for (cur = mlist; cur != NULL; cur = cur->next) {
653                 msginfo = (MsgInfo *)cur->data;
654                 if (!dest) {
655                         dest = msginfo->to_folder;
656                         movelist = g_slist_append(movelist, msginfo);
657                 } else if (dest == msginfo->to_folder) {
658                         movelist = g_slist_append(movelist, msginfo);
659                 } else {
660                         folder_item_move_msgs_with_dest(dest, movelist);
661                         g_slist_free(movelist);
662                         movelist = NULL;
663                         dest = msginfo->to_folder;
664                         movelist = g_slist_append(movelist, msginfo);
665                 }
666         }
667
668         if (movelist) {
669                 folder_item_move_msgs_with_dest(dest, movelist);
670                 g_slist_free(movelist);
671         }
672 }
673
674 void procmsg_copy_messages(GSList *mlist)
675 {
676         GSList *cur, *copylist = NULL;
677         MsgInfo *msginfo;
678         FolderItem *dest = NULL;
679
680         if (!mlist) return;
681
682         /* 
683         
684         Horrible: Scanning 2 times for every copy!
685
686         hash = procmsg_to_folder_hash_table_create(mlist);
687         folder_item_scan_foreach(hash);
688         g_hash_table_destroy(hash);
689         */
690
691         for (cur = mlist; cur != NULL; cur = cur->next) {
692                 msginfo = (MsgInfo *)cur->data;
693                 if (!dest) {
694                         dest = msginfo->to_folder;
695                         copylist = g_slist_append(copylist, msginfo);
696                 } else if (dest == msginfo->to_folder) {
697                         copylist = g_slist_append(copylist, msginfo);
698                 } else {
699                         folder_item_copy_msgs_with_dest(dest, copylist);
700                         g_slist_free(copylist);
701                         copylist = NULL;
702                         dest = msginfo->to_folder;
703                         copylist = g_slist_append(copylist, msginfo);
704                 }
705         }
706
707         if (copylist) {
708                 folder_item_copy_msgs_with_dest(dest, copylist);
709                 g_slist_free(copylist);
710         }
711 }
712
713 gchar *procmsg_get_message_file_path(MsgInfo *msginfo)
714 {
715         gchar *path, *file;
716
717         g_return_val_if_fail(msginfo != NULL, NULL);
718
719         if (msginfo->plaintext_file)
720                 file = g_strdup(msginfo->plaintext_file);
721         else {
722                 path = folder_item_get_path(msginfo->folder);
723                 file = g_strconcat(path, G_DIR_SEPARATOR_S,
724                                    itos(msginfo->msgnum), NULL);
725                 g_free(path);
726         }
727
728         return file;
729 }
730
731 gchar *procmsg_get_message_file(MsgInfo *msginfo)
732 {
733         gchar *filename = NULL;
734
735         g_return_val_if_fail(msginfo != NULL, NULL);
736
737         filename = folder_item_fetch_msg(msginfo->folder, msginfo->msgnum);
738         if (!filename)
739                 g_warning(_("can't fetch message %d\n"), msginfo->msgnum);
740
741         return filename;
742 }
743
744 FILE *procmsg_open_message(MsgInfo *msginfo)
745 {
746         FILE *fp;
747         gchar *file;
748
749         g_return_val_if_fail(msginfo != NULL, NULL);
750
751         file = procmsg_get_message_file_path(msginfo);
752         g_return_val_if_fail(file != NULL, NULL);
753
754         if (!is_file_exist(file)) {
755                 g_free(file);
756                 file = procmsg_get_message_file(msginfo);
757                 g_return_val_if_fail(file != NULL, NULL);
758         }
759
760         if ((fp = fopen(file, "rb")) == NULL) {
761                 FILE_OP_ERROR(file, "fopen");
762                 g_free(file);
763                 return NULL;
764         }
765
766         g_free(file);
767
768         if (MSG_IS_QUEUED(msginfo->flags)) {
769                 gchar buf[BUFFSIZE];
770
771                 while (fgets(buf, sizeof(buf), fp) != NULL)
772                         if (buf[0] == '\r' || buf[0] == '\n') break;
773         }
774
775         return fp;
776 }
777
778 #if USE_GPGME
779 FILE *procmsg_open_message_decrypted(MsgInfo *msginfo, MimeInfo **mimeinfo)
780 {
781         FILE *fp;
782         MimeInfo *mimeinfo_;
783
784         g_return_val_if_fail(msginfo != NULL, NULL);
785
786         if (mimeinfo) *mimeinfo = NULL;
787
788         if ((fp = procmsg_open_message(msginfo)) == NULL) return NULL;
789
790         mimeinfo_ = procmime_scan_mime_header(fp);
791         if (!mimeinfo_) {
792                 fclose(fp);
793                 return NULL;
794         }
795
796         if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
797             rfc2015_is_encrypted(mimeinfo_)) {
798                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
799         }
800
801         if (MSG_IS_ENCRYPTED(msginfo->flags) &&
802             !msginfo->plaintext_file &&
803             !msginfo->decryption_failed) {
804                 rfc2015_decrypt_message(msginfo, mimeinfo_, fp);
805                 if (msginfo->plaintext_file &&
806                     !msginfo->decryption_failed) {
807                         fclose(fp);
808                         procmime_mimeinfo_free_all(mimeinfo_);
809                         if ((fp = procmsg_open_message(msginfo)) == NULL)
810                                 return NULL;
811                         mimeinfo_ = procmime_scan_mime_header(fp);
812                         if (!mimeinfo_) {
813                                 fclose(fp);
814                                 return NULL;
815                         }
816                 }
817         }
818
819         if (mimeinfo) *mimeinfo = mimeinfo_;
820         return fp;
821 }
822 #endif
823
824 gboolean procmsg_msg_exist(MsgInfo *msginfo)
825 {
826         gchar *path;
827         gboolean ret;
828
829         if (!msginfo) return FALSE;
830
831         path = folder_item_get_path(msginfo->folder);
832         change_dir(path);
833         ret = !folder_item_is_msg_changed(msginfo->folder, msginfo);
834         g_free(path);
835
836         return ret;
837 }
838
839 void procmsg_empty_trash(void)
840 {
841         FolderItem *trash;
842         GList *cur;
843
844         for (cur = folder_get_list(); cur != NULL; cur = cur->next) {
845                 trash = FOLDER(cur->data)->trash;
846                 if (trash && trash->total > 0)
847                         folder_item_remove_all_msg(trash);
848         }
849 }
850
851 gint procmsg_send_queue(FolderItem *queue, gboolean save_msgs)
852 {
853         gint ret = 0;
854         GSList *list, *elem;
855
856         if (!queue)
857                 queue = folder_get_default_queue();
858         g_return_val_if_fail(queue != NULL, -1);
859
860         folder_item_scan(queue);
861         list = folder_item_get_msg_list(queue);
862
863
864         for(elem = list; elem != NULL; elem = elem->next) {
865                 gchar *file;
866                 MsgInfo *msginfo;
867                 
868                 msginfo = (MsgInfo *)(elem->data);
869
870                 file = folder_item_fetch_msg(queue, msginfo->msgnum);
871                 if (file) {
872                         if (procmsg_send_message_queue(file) < 0) {
873                                 g_warning(_("Sending queued message %d failed.\n"), msginfo->msgnum);
874                                 ret = -1;
875                         } else {
876                         /* CLAWS: 
877                          * We save in procmsg_send_message_queue because
878                          * we need the destination folder from the queue
879                          * header
880                                                 
881                                 if (save_msgs)
882                                         procmsg_save_to_outbox
883                                                 (queue->folder->outbox,
884                                                  file, TRUE);
885 */
886                                 folder_item_remove_msg(queue, msginfo->msgnum);
887                         }
888                         g_free(file);
889                 }
890                 procmsg_msginfo_free(msginfo);
891         }
892
893         folderview_update_item(queue, FALSE);
894
895         return ret;
896 }
897
898 gint procmsg_save_to_outbox(FolderItem *outbox, const gchar *file,
899                             gboolean is_queued)
900 {
901         gint num;
902         FILE *fp;
903         MsgInfo *msginfo;
904
905         debug_print("saving sent message...\n");
906
907         if (!outbox)
908                 outbox = folder_get_default_outbox();
909         g_return_val_if_fail(outbox != NULL, -1);
910
911         /* remove queueing headers */
912         if (is_queued) {
913                 gchar tmp[MAXPATHLEN + 1];
914                 gchar buf[BUFFSIZE];
915                 FILE *outfp;
916
917                 g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.out.%08x",
918                            get_rc_dir(), G_DIR_SEPARATOR, (guint)random());
919                 if ((fp = fopen(file, "rb")) == NULL) {
920                         FILE_OP_ERROR(file, "fopen");
921                         return -1;
922                 }
923                 if ((outfp = fopen(tmp, "wb")) == NULL) {
924                         FILE_OP_ERROR(tmp, "fopen");
925                         fclose(fp);
926                         return -1;
927                 }
928                 while (fgets(buf, sizeof(buf), fp) != NULL)
929                         if (buf[0] == '\r' || buf[0] == '\n') break;
930                 while (fgets(buf, sizeof(buf), fp) != NULL)
931                         fputs(buf, outfp);
932                 fclose(outfp);
933                 fclose(fp);
934
935                 folder_item_scan(outbox);
936                 if ((num = folder_item_add_msg(outbox, tmp, TRUE)) < 0) {
937                         g_warning("can't save message\n");
938                         unlink(tmp);
939                         return -1;
940                 }
941         } else {
942                 folder_item_scan(outbox);
943                 if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
944                         g_warning("can't save message\n");
945                         return -1;
946                 }
947                 return -1;
948         }
949         msginfo = folder_item_fetch_msginfo(outbox, num);
950         if(msginfo != NULL) {
951             procmsg_msginfo_unset_flags(msginfo, ~0, ~0);
952             procmsg_msginfo_free(msginfo);
953         }
954
955         if(is_queued) {
956                 unlink(file);
957         }
958
959         return 0;
960 }
961
962 void procmsg_print_message(MsgInfo *msginfo, const gchar *cmdline)
963 {
964         static const gchar *def_cmd = "lpr %s";
965         static guint id = 0;
966         gchar *prtmp;
967         FILE *tmpfp, *prfp;
968         gchar buf[1024];
969         gchar *p;
970
971         g_return_if_fail(msginfo);
972
973         if ((tmpfp = procmime_get_first_text_content(msginfo)) == NULL) {
974                 g_warning(_("Can't get text part\n"));
975                 return;
976         }
977
978         prtmp = g_strdup_printf("%s%cprinttmp.%08x",
979                                 get_mime_tmp_dir(), G_DIR_SEPARATOR, id++);
980
981         if ((prfp = fopen(prtmp, "wb")) == NULL) {
982                 FILE_OP_ERROR(prtmp, "fopen");
983                 g_free(prtmp);
984                 fclose(tmpfp);
985                 return;
986         }
987
988         if (msginfo->date) fprintf(prfp, "Date: %s\n", msginfo->date);
989         if (msginfo->from) fprintf(prfp, "From: %s\n", msginfo->from);
990         if (msginfo->to)   fprintf(prfp, "To: %s\n", msginfo->to);
991         if (msginfo->cc)   fprintf(prfp, "Cc: %s\n", msginfo->cc);
992         if (msginfo->newsgroups)
993                 fprintf(prfp, "Newsgroups: %s\n", msginfo->newsgroups);
994         if (msginfo->subject) fprintf(prfp, "Subject: %s\n", msginfo->subject);
995         fputc('\n', prfp);
996
997         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
998                 fputs(buf, prfp);
999
1000         fclose(prfp);
1001         fclose(tmpfp);
1002
1003         if (cmdline && (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
1004             !strchr(p + 2, '%'))
1005                 g_snprintf(buf, sizeof(buf) - 1, cmdline, prtmp);
1006         else {
1007                 if (cmdline)
1008                         g_warning(_("Print command line is invalid: `%s'\n"),
1009                                   cmdline);
1010                 g_snprintf(buf, sizeof(buf) - 1, def_cmd, prtmp);
1011         }
1012
1013         g_free(prtmp);
1014
1015         g_strchomp(buf);
1016         if (buf[strlen(buf) - 1] != '&') strcat(buf, "&");
1017         system(buf);
1018 }
1019
1020 MsgInfo *procmsg_msginfo_new_ref(MsgInfo *msginfo)
1021 {
1022         msginfo->refcnt++;
1023         
1024         return msginfo;
1025 }
1026
1027 MsgInfo *procmsg_msginfo_new()
1028 {
1029         MsgInfo *newmsginfo;
1030
1031         newmsginfo = g_new0(MsgInfo, 1);
1032         newmsginfo->refcnt = 1;
1033         
1034         return newmsginfo;
1035 }
1036
1037 MsgInfo *procmsg_msginfo_copy(MsgInfo *msginfo)
1038 {
1039         MsgInfo *newmsginfo;
1040
1041         if (msginfo == NULL) return NULL;
1042
1043         newmsginfo = g_new0(MsgInfo, 1);
1044
1045         newmsginfo->refcnt = 1;
1046
1047 #define MEMBCOPY(mmb)   newmsginfo->mmb = msginfo->mmb
1048 #define MEMBDUP(mmb)    newmsginfo->mmb = msginfo->mmb ? \
1049                         g_strdup(msginfo->mmb) : NULL
1050
1051         MEMBCOPY(msgnum);
1052         MEMBCOPY(size);
1053         MEMBCOPY(mtime);
1054         MEMBCOPY(date_t);
1055         MEMBCOPY(flags);
1056
1057         MEMBDUP(fromname);
1058
1059         MEMBDUP(date);
1060         MEMBDUP(from);
1061         MEMBDUP(to);
1062         MEMBDUP(cc);
1063         MEMBDUP(newsgroups);
1064         MEMBDUP(subject);
1065         MEMBDUP(msgid);
1066         MEMBDUP(inreplyto);
1067         MEMBDUP(xref);
1068
1069         MEMBCOPY(folder);
1070         MEMBCOPY(to_folder);
1071
1072         MEMBDUP(xface);
1073         MEMBDUP(dispositionnotificationto);
1074         MEMBDUP(returnreceiptto);
1075         MEMBDUP(references);
1076
1077         MEMBCOPY(score);
1078         MEMBCOPY(threadscore);
1079
1080         return newmsginfo;
1081 }
1082
1083 void procmsg_msginfo_free(MsgInfo *msginfo)
1084 {
1085         if (msginfo == NULL) return;
1086
1087         msginfo->refcnt--;
1088         if(msginfo->refcnt > 0)
1089                 return;
1090
1091         g_free(msginfo->fromspace);
1092         g_free(msginfo->references);
1093         g_free(msginfo->returnreceiptto);
1094         g_free(msginfo->dispositionnotificationto);
1095         g_free(msginfo->xface);
1096
1097         g_free(msginfo->fromname);
1098
1099         g_free(msginfo->date);
1100         g_free(msginfo->from);
1101         g_free(msginfo->to);
1102         g_free(msginfo->cc);
1103         g_free(msginfo->newsgroups);
1104         g_free(msginfo->subject);
1105         g_free(msginfo->msgid);
1106         g_free(msginfo->inreplyto);
1107         g_free(msginfo->xref);
1108
1109         g_free(msginfo);
1110 }
1111
1112 guint procmsg_msginfo_memusage(MsgInfo *msginfo)
1113 {
1114         guint memusage = 0;
1115         
1116         memusage += sizeof(MsgInfo);
1117         if(msginfo->fromname)
1118                 memusage += strlen(msginfo->fromname);
1119         if(msginfo->date)
1120                 memusage += strlen(msginfo->date);
1121         if(msginfo->from)
1122                 memusage += strlen(msginfo->from);
1123         if(msginfo->to)
1124                 memusage += strlen(msginfo->to);
1125         if(msginfo->cc)
1126                 memusage += strlen(msginfo->cc);
1127         if(msginfo->newsgroups)
1128                 memusage += strlen(msginfo->newsgroups);
1129         if(msginfo->subject)
1130                 memusage += strlen(msginfo->subject);
1131         if(msginfo->msgid)
1132                 memusage += strlen(msginfo->msgid);
1133         if(msginfo->inreplyto)
1134                 memusage += strlen(msginfo->inreplyto);
1135         if(msginfo->xface)
1136                 memusage += strlen(msginfo->xface);
1137         if(msginfo->dispositionnotificationto)
1138                 memusage += strlen(msginfo->dispositionnotificationto);
1139         if(msginfo->returnreceiptto)
1140                 memusage += strlen(msginfo->returnreceiptto);
1141         if(msginfo->references)
1142                 memusage += strlen(msginfo->references);
1143         if(msginfo->fromspace)
1144                 memusage += strlen(msginfo->fromspace);
1145
1146         return memusage;
1147 }
1148
1149 gint procmsg_cmp_msgnum_for_sort(gconstpointer a, gconstpointer b)
1150 {
1151         const MsgInfo *msginfo1 = a;
1152         const MsgInfo *msginfo2 = b;
1153
1154         if (!msginfo1)
1155                 return -1;
1156         if (!msginfo2)
1157                 return -1;
1158
1159         return msginfo1->msgnum - msginfo2->msgnum;
1160 }
1161
1162 enum
1163 {
1164         Q_SENDER           = 0,
1165         Q_SMTPSERVER       = 1,
1166         Q_RECIPIENTS       = 2,
1167         Q_NEWSGROUPS       = 3,
1168         Q_MAIL_ACCOUNT_ID  = 4,
1169         Q_NEWS_ACCOUNT_ID  = 5,
1170         Q_SAVE_COPY_FOLDER = 6,
1171         Q_REPLY_MESSAGE_ID = 7,
1172 };
1173
1174 gint procmsg_send_message_queue(const gchar *file)
1175 {
1176         static HeaderEntry qentry[] = {{"S:",    NULL, FALSE},
1177                                        {"SSV:",  NULL, FALSE},
1178                                        {"R:",    NULL, FALSE},
1179                                        {"NG:",   NULL, FALSE},
1180                                        {"MAID:", NULL, FALSE},
1181                                        {"NAID:", NULL, FALSE},
1182                                        {"SCF:",  NULL, FALSE},
1183                                        {"RMID:", NULL, FALSE},
1184                                        {NULL,    NULL, FALSE}};
1185         FILE *fp;
1186         gint filepos;
1187         gint mailval = 0, newsval = 0;
1188         gchar *from = NULL;
1189         gchar *smtpserver = NULL;
1190         GSList *to_list = NULL;
1191         GSList *newsgroup_list = NULL;
1192         gchar *savecopyfolder = NULL;
1193         gchar *replymessageid = NULL;
1194         gchar buf[BUFFSIZE];
1195         gint hnum;
1196         PrefsAccount *mailac = NULL, *newsac = NULL;
1197         int local = 0;
1198
1199         g_return_val_if_fail(file != NULL, -1);
1200
1201         if ((fp = fopen(file, "rb")) == NULL) {
1202                 FILE_OP_ERROR(file, "fopen");
1203                 return -1;
1204         }
1205
1206         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, qentry))
1207                != -1) {
1208                 gchar *p = buf + strlen(qentry[hnum].name);
1209
1210                 switch (hnum) {
1211                 case Q_SENDER:
1212                         if (!from) from = g_strdup(p);
1213                         break;
1214                 case Q_SMTPSERVER:
1215                         if (!smtpserver) smtpserver = g_strdup(p);
1216                         break;
1217                 case Q_RECIPIENTS:
1218                         to_list = address_list_append(to_list, p);
1219                         break;
1220                 case Q_NEWSGROUPS:
1221                         newsgroup_list = newsgroup_list_append(newsgroup_list, p);
1222                         break;
1223                 case Q_MAIL_ACCOUNT_ID:
1224                         mailac = account_find_from_id(atoi(p));
1225                         break;
1226                 case Q_NEWS_ACCOUNT_ID:
1227                         newsac = account_find_from_id(atoi(p));
1228                         break;
1229                 case Q_SAVE_COPY_FOLDER:
1230                         if (!savecopyfolder) savecopyfolder = g_strdup(p);
1231                         break;
1232                 case Q_REPLY_MESSAGE_ID:
1233                         if (!replymessageid) replymessageid = g_strdup(p);
1234                         break;
1235                 }
1236         }
1237         filepos = ftell(fp);
1238
1239         fseek(fp, filepos, SEEK_SET);
1240         if (to_list) {
1241                 debug_print(_("Sending message by mail\n"));
1242                 if(!from) {
1243                         g_warning(_("Queued message header is broken.\n"));
1244                         mailval = -1;
1245                 } else if (mailac && mailac->use_mail_command &&
1246                            mailac->mail_command && (* mailac->mail_command)) {
1247                         mailval = send_message_local(mailac->mail_command, fp);
1248                         local = 1;
1249                 } else if (prefs_common.use_extsend && prefs_common.extsend_cmd) {
1250                         mailval = send_message_local(prefs_common.extsend_cmd, fp);
1251                         local = 1;
1252                 } else {
1253                         if (!mailac) {
1254                                 mailac = account_find_from_smtp_server(from, smtpserver);
1255                                 if (!mailac) {
1256                                         g_warning(_("Account not found. "
1257                                                     "Using current account...\n"));
1258                                         mailac = cur_account;
1259                                 }
1260                         }
1261
1262                         if (mailac)
1263                                 mailval = send_message_smtp(mailac, to_list, fp);
1264                         else {
1265                                 PrefsAccount tmp_ac;
1266
1267                                 g_warning(_("Account not found.\n"));
1268
1269                                 memset(&tmp_ac, 0, sizeof(PrefsAccount));
1270                                 tmp_ac.address = from;
1271                                 tmp_ac.smtp_server = smtpserver;
1272                                 tmp_ac.smtpport = SMTP_PORT;
1273                                 mailval = send_message_smtp(&tmp_ac, to_list, fp);
1274                         }
1275                 }
1276                 if (mailval < 0) {
1277                         if (!local)
1278                                 alertpanel_error(
1279                                         _("Error occurred while sending the message to `%s'."),
1280                                         mailac ? mailac->smtp_server : smtpserver);
1281                         else
1282                                 alertpanel_error(
1283                                         _("Error occurred while sending the message with command `%s'."),
1284                                         (mailac && mailac->use_mail_command && 
1285                                          mailac->mail_command && (*mailac->mail_command)) ? 
1286                                                 mailac->mail_command : prefs_common.extsend_cmd);
1287                 }
1288         }
1289
1290         if(newsgroup_list && (newsval == 0)) {
1291                 Folder *folder;
1292                 gchar *tmp = NULL;
1293                 FILE *tmpfp;
1294
1295                 /* write to temporary file */
1296                 tmp = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
1297                             G_DIR_SEPARATOR, (gint)file);
1298                 if ((tmpfp = fopen(tmp, "wb")) == NULL) {
1299                         FILE_OP_ERROR(tmp, "fopen");
1300                         newsval = -1;
1301                         alertpanel_error(_("Could not create temporary file for news sending."));
1302                 } else {
1303                         if (change_file_mode_rw(tmpfp, tmp) < 0) {
1304                                 FILE_OP_ERROR(tmp, "chmod");
1305                                 g_warning(_("can't change file mode\n"));
1306                         }
1307
1308                         while ((newsval == 0) && fgets(buf, sizeof(buf), fp) != NULL) {
1309                                 if (fputs(buf, tmpfp) == EOF) {
1310                                         FILE_OP_ERROR(tmp, "fputs");
1311                                         newsval = -1;
1312                                         alertpanel_error(_("Error when writing temporary file for news sending."));
1313                                 }
1314                         }
1315                         fclose(tmpfp);
1316
1317                         if(newsval == 0) {
1318                                 debug_print(_("Sending message by news\n"));
1319
1320                                 folder = FOLDER(newsac->folder);
1321
1322                                 newsval = news_post(folder, tmp);
1323                                 if (newsval < 0) {
1324                                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1325                                                  newsac->nntp_server);
1326                                 }
1327                         }
1328                         unlink(tmp);
1329                 }
1330                 g_free(tmp);
1331         }
1332
1333         slist_free_strings(to_list);
1334         g_slist_free(to_list);
1335         slist_free_strings(newsgroup_list);
1336         g_slist_free(newsgroup_list);
1337         g_free(from);
1338         g_free(smtpserver);
1339         fclose(fp);
1340
1341         /* save message to outbox */
1342         if (mailval == 0 && newsval == 0 && savecopyfolder) {
1343                 FolderItem *outbox;
1344
1345                 debug_print(_("saving sent message...\n"));
1346
1347                 outbox = folder_find_item_from_identifier(savecopyfolder);
1348                 if(!outbox)
1349                         outbox = folder_get_default_outbox();
1350
1351                 procmsg_save_to_outbox(outbox, file, TRUE);
1352         }
1353
1354         if(replymessageid != NULL) {
1355                 gchar **tokens;
1356                 FolderItem *item;
1357                 
1358                 tokens = g_strsplit(replymessageid, "\x7f", 0);
1359                 item = folder_find_item_from_identifier(tokens[0]);
1360                 if(item != NULL) {
1361                         MsgInfo *msginfo;
1362                         
1363                         msginfo = folder_item_fetch_msginfo(item, atoi(tokens[1]));
1364                         if((msginfo != NULL) && (strcmp(msginfo->msgid, tokens[2]) != 0)) {
1365                                 procmsg_msginfo_free(msginfo);
1366                                 msginfo = NULL;
1367                         }
1368                         
1369                         if(msginfo == NULL) {
1370                                 msginfo = folder_item_fetch_msginfo_by_id(item, tokens[2]);
1371                         }
1372                         
1373                         if(msginfo != NULL) {
1374                                 procmsg_msginfo_unset_flags(msginfo, MSG_FORWARDED, 0);
1375                                 procmsg_msginfo_set_flags(msginfo, MSG_REPLIED, 0);
1376
1377                                 procmsg_msginfo_free(msginfo);
1378                         }
1379                 }
1380                 g_strfreev(tokens);
1381         }
1382
1383         g_free(savecopyfolder);
1384         g_free(replymessageid);
1385         
1386         return (newsval != 0 ? newsval : mailval);
1387 }
1388
1389 #define CHANGE_FLAGS(msginfo) \
1390 { \
1391 if (msginfo->folder->folder->change_flags != NULL) \
1392 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
1393                                       msginfo->folder, \
1394                                       msginfo); \
1395 }
1396
1397 void procmsg_msginfo_set_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1398 {
1399         gboolean changed = FALSE;
1400         FolderItem *item = msginfo->folder;
1401
1402         debug_print(_("Setting flags for message %d in folder %s\n"), msginfo->msgnum, item->path);
1403
1404         /* if new flag is set */
1405         if((perm_flags & MSG_NEW) && !MSG_IS_NEW(msginfo->flags) &&
1406            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1407                 item->new++;
1408                 changed = TRUE;
1409         }
1410
1411         /* if unread flag is set */
1412         if((perm_flags & MSG_UNREAD) && !MSG_IS_UNREAD(msginfo->flags) &&
1413            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1414                 item->unread++;
1415                 changed = TRUE;
1416         }
1417
1418         /* if ignore thread flag is set */
1419         if((perm_flags & MSG_IGNORE_THREAD) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1420                 if(MSG_IS_NEW(msginfo->flags) || (perm_flags & MSG_NEW)) {
1421                         item->new--;
1422                         changed = TRUE;
1423                 }
1424                 if(MSG_IS_UNREAD(msginfo->flags) || (perm_flags & MSG_UNREAD)) {
1425                         item->unread--;
1426                         changed = TRUE;
1427                 }
1428         }
1429
1430         if (MSG_IS_IMAP(msginfo->flags))
1431                 imap_msg_set_perm_flags(msginfo, perm_flags);
1432
1433         msginfo->flags.perm_flags |= perm_flags;
1434         msginfo->flags.tmp_flags |= tmp_flags;
1435
1436         if(changed) {
1437                 folderview_update_item(item, FALSE);
1438         }
1439         CHANGE_FLAGS(msginfo);
1440         procmsg_msginfo_write_flags(msginfo);
1441 }
1442
1443 void procmsg_msginfo_unset_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1444 {
1445         gboolean changed = FALSE;
1446         FolderItem *item = msginfo->folder;
1447         
1448         debug_print(_("Unsetting flags for message %d in folder %s\n"), msginfo->msgnum, item->path);
1449
1450         /* if new flag is unset */
1451         if((perm_flags & MSG_NEW) && MSG_IS_NEW(msginfo->flags) &&
1452            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1453                 item->new--;
1454                 changed = TRUE;
1455         }
1456
1457         /* if unread flag is unset */
1458         if((perm_flags & MSG_UNREAD) && MSG_IS_UNREAD(msginfo->flags) &&
1459            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1460                 item->unread--;
1461                 changed = TRUE;
1462         }
1463
1464         /* if ignore thread flag is unset */
1465         if((perm_flags & MSG_IGNORE_THREAD) && MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1466                 if(MSG_IS_NEW(msginfo->flags) && !(perm_flags & MSG_NEW)) {
1467                         item->new++;
1468                         changed = TRUE;
1469                 }
1470                 if(MSG_IS_UNREAD(msginfo->flags) && !(perm_flags & MSG_UNREAD)) {
1471                         item->unread++;
1472                         changed = TRUE;
1473                 }
1474         }
1475
1476         if (MSG_IS_IMAP(msginfo->flags))
1477                 imap_msg_unset_perm_flags(msginfo, perm_flags);
1478
1479         msginfo->flags.perm_flags &= ~perm_flags;
1480         msginfo->flags.tmp_flags &= ~tmp_flags;
1481
1482         if(changed) {
1483                 folderview_update_item(item, FALSE);
1484         }
1485         CHANGE_FLAGS(msginfo);
1486         procmsg_msginfo_write_flags(msginfo);
1487 }
1488
1489 void procmsg_msginfo_write_flags(MsgInfo *msginfo)
1490 {
1491         gchar *destdir;
1492         FILE *fp;
1493
1494         destdir = folder_item_get_path(msginfo->folder);
1495         if (!is_dir_exist(destdir))
1496                 make_dir_hier(destdir);
1497
1498         if ((fp = procmsg_open_mark_file(destdir, TRUE))) {
1499                 procmsg_write_flags(msginfo, fp);
1500                 fclose(fp);
1501         } else {
1502                 g_warning(_("Can't open mark file.\n"));
1503         }
1504         
1505         g_free(destdir);
1506 }