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