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