db179c1b3f843ec6e141e5a808ab107536f5bad2
[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         for (cur = mlist; cur != NULL; cur = cur->next) {
663                 msginfo = (MsgInfo *)cur->data;
664                 if (!dest) {
665                         dest = msginfo->to_folder;
666                         movelist = g_slist_append(movelist, msginfo);
667                 } else if (dest == msginfo->to_folder) {
668                         movelist = g_slist_append(movelist, msginfo);
669                 } else {
670                         folder_item_move_msgs_with_dest(dest, movelist);
671                         g_slist_free(movelist);
672                         movelist = NULL;
673                         dest = msginfo->to_folder;
674                         movelist = g_slist_append(movelist, msginfo);
675                 }
676         }
677
678         if (movelist) {
679                 folder_item_move_msgs_with_dest(dest, movelist);
680                 g_slist_free(movelist);
681         }
682 }
683
684 void procmsg_copy_messages(GSList *mlist)
685 {
686         GSList *cur, *copylist = NULL;
687         MsgInfo *msginfo;
688         FolderItem *dest = NULL;
689
690         if (!mlist) return;
691
692         /* 
693         
694         Horrible: Scanning 2 times for every copy!
695
696         hash = procmsg_to_folder_hash_table_create(mlist);
697         folder_item_scan_foreach(hash);
698         g_hash_table_destroy(hash);
699         */
700
701         for (cur = mlist; cur != NULL; cur = cur->next) {
702                 msginfo = (MsgInfo *)cur->data;
703                 if (!dest) {
704                         dest = msginfo->to_folder;
705                         copylist = g_slist_append(copylist, msginfo);
706                 } else if (dest == msginfo->to_folder) {
707                         copylist = g_slist_append(copylist, msginfo);
708                 } else {
709                         folder_item_copy_msgs_with_dest(dest, copylist);
710                         g_slist_free(copylist);
711                         copylist = NULL;
712                         dest = msginfo->to_folder;
713                         copylist = g_slist_append(copylist, msginfo);
714                 }
715         }
716
717         if (copylist) {
718                 folder_item_copy_msgs_with_dest(dest, copylist);
719                 g_slist_free(copylist);
720         }
721 }
722
723 gchar *procmsg_get_message_file_path(MsgInfo *msginfo)
724 {
725         gchar *path, *file;
726
727         g_return_val_if_fail(msginfo != NULL, NULL);
728
729         if (msginfo->plaintext_file)
730                 file = g_strdup(msginfo->plaintext_file);
731         else {
732                 path = folder_item_get_path(msginfo->folder);
733                 file = g_strconcat(path, G_DIR_SEPARATOR_S,
734                                    itos(msginfo->msgnum), NULL);
735                 g_free(path);
736         }
737
738         return file;
739 }
740
741 gchar *procmsg_get_message_file(MsgInfo *msginfo)
742 {
743         gchar *filename = NULL;
744
745         g_return_val_if_fail(msginfo != NULL, NULL);
746
747         filename = folder_item_fetch_msg(msginfo->folder, msginfo->msgnum);
748         if (!filename)
749                 g_warning("can't fetch message %d\n", msginfo->msgnum);
750
751         return filename;
752 }
753
754 FILE *procmsg_open_message(MsgInfo *msginfo)
755 {
756         FILE *fp;
757         gchar *file;
758
759         g_return_val_if_fail(msginfo != NULL, NULL);
760
761         file = procmsg_get_message_file_path(msginfo);
762         g_return_val_if_fail(file != NULL, NULL);
763
764         if (!is_file_exist(file)) {
765                 g_free(file);
766                 file = procmsg_get_message_file(msginfo);
767                 g_return_val_if_fail(file != NULL, NULL);
768         }
769
770         if ((fp = fopen(file, "rb")) == NULL) {
771                 FILE_OP_ERROR(file, "fopen");
772                 g_free(file);
773                 return NULL;
774         }
775
776         g_free(file);
777
778         if (MSG_IS_QUEUED(msginfo->flags) || MSG_IS_DRAFT(msginfo->flags)) {
779                 gchar buf[BUFFSIZE];
780
781                 while (fgets(buf, sizeof(buf), fp) != NULL)
782                         if (buf[0] == '\r' || buf[0] == '\n') break;
783         }
784
785         return fp;
786 }
787
788 #if USE_GPGME
789 FILE *procmsg_open_message_decrypted(MsgInfo *msginfo, MimeInfo **mimeinfo)
790 {
791         FILE *fp;
792         MimeInfo *mimeinfo_;
793
794         g_return_val_if_fail(msginfo != NULL, NULL);
795
796         if (mimeinfo) *mimeinfo = NULL;
797
798         if ((fp = procmsg_open_message(msginfo)) == NULL) return NULL;
799
800         mimeinfo_ = procmime_scan_mime_header(fp);
801         if (!mimeinfo_) {
802                 fclose(fp);
803                 return NULL;
804         }
805
806         if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
807             rfc2015_is_encrypted(mimeinfo_)) {
808                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
809         }
810
811         if (MSG_IS_ENCRYPTED(msginfo->flags) &&
812             !msginfo->plaintext_file &&
813             !msginfo->decryption_failed) {
814                 rfc2015_decrypt_message(msginfo, mimeinfo_, fp);
815                 if (msginfo->plaintext_file &&
816                     !msginfo->decryption_failed) {
817                         fclose(fp);
818                         procmime_mimeinfo_free_all(mimeinfo_);
819                         if ((fp = procmsg_open_message(msginfo)) == NULL)
820                                 return NULL;
821                         mimeinfo_ = procmime_scan_mime_header(fp);
822                         if (!mimeinfo_) {
823                                 fclose(fp);
824                                 return NULL;
825                         }
826                 }
827         }
828
829         if (mimeinfo) *mimeinfo = mimeinfo_;
830         return fp;
831 }
832 #endif
833
834 gboolean procmsg_msg_exist(MsgInfo *msginfo)
835 {
836         gchar *path;
837         gboolean ret;
838
839         if (!msginfo) return FALSE;
840
841         path = folder_item_get_path(msginfo->folder);
842         change_dir(path);
843         ret = !folder_item_is_msg_changed(msginfo->folder, msginfo);
844         g_free(path);
845
846         return ret;
847 }
848
849 void procmsg_empty_trash(void)
850 {
851         FolderItem *trash;
852         GList *cur;
853
854         for (cur = folder_get_list(); cur != NULL; cur = cur->next) {
855                 trash = FOLDER(cur->data)->trash;
856                 if (trash && trash->total > 0)
857                         folder_item_remove_all_msg(trash);
858         }
859 }
860
861 gint procmsg_send_queue(FolderItem *queue, gboolean save_msgs)
862 {
863         gint ret = 0;
864         GSList *list, *elem;
865
866         if (!queue)
867                 queue = folder_get_default_queue();
868         g_return_val_if_fail(queue != NULL, -1);
869
870         folder_item_scan(queue);
871         list = folder_item_get_msg_list(queue);
872
873
874         for (elem = list; elem != NULL; elem = elem->next) {
875                 gchar *file;
876                 MsgInfo *msginfo;
877                 
878                 msginfo = (MsgInfo *)(elem->data);
879
880                 file = folder_item_fetch_msg(queue, msginfo->msgnum);
881                 if (file) {
882                         if (procmsg_send_message_queue(file) < 0) {
883                                 g_warning("Sending queued message %d failed.\n", msginfo->msgnum);
884                                 ret = -1;
885                         } else {
886                         /* CLAWS: 
887                          * We save in procmsg_send_message_queue because
888                          * we need the destination folder from the queue
889                          * header
890                                                 
891                                 if (save_msgs)
892                                         procmsg_save_to_outbox
893                                                 (queue->folder->outbox,
894                                                  file, TRUE);
895 */
896                                 folder_item_remove_msg(queue, msginfo->msgnum);
897                         }
898                         g_free(file);
899                 }
900                 procmsg_msginfo_free(msginfo);
901         }
902
903         folder_update_item(queue, FALSE);
904
905         return ret;
906 }
907
908 gint procmsg_remove_special_headers(const gchar *in, const gchar *out)
909 {
910         FILE *fp, *outfp;
911         gchar buf[BUFFSIZE];
912         
913         if ((fp = fopen(in, "rb")) == NULL) {
914                 FILE_OP_ERROR(in, "fopen");
915                 return -1;
916         }
917         if ((outfp = fopen(out, "wb")) == NULL) {
918                 FILE_OP_ERROR(out, "fopen");
919                 fclose(fp);
920                 return -1;
921         }
922         while (fgets(buf, sizeof(buf), fp) != NULL)
923                 if (buf[0] == '\r' || buf[0] == '\n') break;
924         while (fgets(buf, sizeof(buf), fp) != NULL)
925                 fputs(buf, outfp);
926         fclose(outfp);
927         fclose(fp);
928         return 0;
929
930 }
931 gint procmsg_save_to_outbox(FolderItem *outbox, const gchar *file,
932                             gboolean is_queued)
933 {
934         gint num;
935         MsgInfo *msginfo;
936
937         debug_print("saving sent message...\n");
938
939         if (!outbox)
940                 outbox = folder_get_default_outbox();
941         g_return_val_if_fail(outbox != NULL, -1);
942
943         /* remove queueing headers */
944         if (is_queued) {
945                 gchar tmp[MAXPATHLEN + 1];
946
947                 g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.out.%08x",
948                            get_rc_dir(), G_DIR_SEPARATOR, (guint)random());
949                 
950                 if (procmsg_remove_special_headers(file, tmp) !=0)
951                         return -1;
952
953                 folder_item_scan(outbox);
954                 if ((num = folder_item_add_msg(outbox, tmp, TRUE)) < 0) {
955                         g_warning("can't save message\n");
956                         unlink(tmp);
957                         return -1;
958                 }
959         } else {
960                 folder_item_scan(outbox);
961                 if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
962                         g_warning("can't save message\n");
963                         return -1;
964                 }
965                 return -1;
966         }
967         msginfo = folder_item_get_msginfo(outbox, num);
968         if (msginfo != NULL) {
969             procmsg_msginfo_unset_flags(msginfo, ~0, 0);
970             procmsg_msginfo_free(msginfo);
971         }
972         folder_update_item(outbox, TRUE);
973
974         return 0;
975 }
976
977 void procmsg_print_message(MsgInfo *msginfo, const gchar *cmdline)
978 {
979         static const gchar *def_cmd = "lpr %s";
980         static guint id = 0;
981         gchar *prtmp;
982         FILE *tmpfp, *prfp;
983         gchar buf[1024];
984         gchar *p;
985
986         g_return_if_fail(msginfo);
987
988         if ((tmpfp = procmime_get_first_text_content(msginfo)) == NULL) {
989                 g_warning("Can't get text part\n");
990                 return;
991         }
992
993         prtmp = g_strdup_printf("%s%cprinttmp.%08x",
994                                 get_mime_tmp_dir(), G_DIR_SEPARATOR, id++);
995
996         if ((prfp = fopen(prtmp, "wb")) == NULL) {
997                 FILE_OP_ERROR(prtmp, "fopen");
998                 g_free(prtmp);
999                 fclose(tmpfp);
1000                 return;
1001         }
1002
1003         if (msginfo->date) fprintf(prfp, "Date: %s\n", msginfo->date);
1004         if (msginfo->from) fprintf(prfp, "From: %s\n", msginfo->from);
1005         if (msginfo->to)   fprintf(prfp, "To: %s\n", msginfo->to);
1006         if (msginfo->cc)   fprintf(prfp, "Cc: %s\n", msginfo->cc);
1007         if (msginfo->newsgroups)
1008                 fprintf(prfp, "Newsgroups: %s\n", msginfo->newsgroups);
1009         if (msginfo->subject) fprintf(prfp, "Subject: %s\n", msginfo->subject);
1010         fputc('\n', prfp);
1011
1012         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
1013                 fputs(buf, prfp);
1014
1015         fclose(prfp);
1016         fclose(tmpfp);
1017
1018         if (cmdline && (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
1019             !strchr(p + 2, '%'))
1020                 g_snprintf(buf, sizeof(buf) - 1, cmdline, prtmp);
1021         else {
1022                 if (cmdline)
1023                         g_warning("Print command line is invalid: `%s'\n",
1024                                   cmdline);
1025                 g_snprintf(buf, sizeof(buf) - 1, def_cmd, prtmp);
1026         }
1027
1028         g_free(prtmp);
1029
1030         g_strchomp(buf);
1031         if (buf[strlen(buf) - 1] != '&') strcat(buf, "&");
1032         system(buf);
1033 }
1034
1035 MsgInfo *procmsg_msginfo_new_ref(MsgInfo *msginfo)
1036 {
1037         msginfo->refcnt++;
1038         
1039         return msginfo;
1040 }
1041
1042 MsgInfo *procmsg_msginfo_new()
1043 {
1044         MsgInfo *newmsginfo;
1045
1046         newmsginfo = g_new0(MsgInfo, 1);
1047         newmsginfo->refcnt = 1;
1048         
1049         return newmsginfo;
1050 }
1051
1052 MsgInfo *procmsg_msginfo_copy(MsgInfo *msginfo)
1053 {
1054         MsgInfo *newmsginfo;
1055
1056         if (msginfo == NULL) return NULL;
1057
1058         newmsginfo = g_new0(MsgInfo, 1);
1059
1060         newmsginfo->refcnt = 1;
1061
1062 #define MEMBCOPY(mmb)   newmsginfo->mmb = msginfo->mmb
1063 #define MEMBDUP(mmb)    newmsginfo->mmb = msginfo->mmb ? \
1064                         g_strdup(msginfo->mmb) : NULL
1065
1066         MEMBCOPY(msgnum);
1067         MEMBCOPY(size);
1068         MEMBCOPY(mtime);
1069         MEMBCOPY(date_t);
1070         MEMBCOPY(flags);
1071
1072         MEMBDUP(fromname);
1073
1074         MEMBDUP(date);
1075         MEMBDUP(from);
1076         MEMBDUP(to);
1077         MEMBDUP(cc);
1078         MEMBDUP(newsgroups);
1079         MEMBDUP(subject);
1080         MEMBDUP(msgid);
1081         MEMBDUP(inreplyto);
1082         MEMBDUP(xref);
1083
1084         MEMBCOPY(folder);
1085         MEMBCOPY(to_folder);
1086
1087         MEMBDUP(xface);
1088         MEMBDUP(dispositionnotificationto);
1089         MEMBDUP(returnreceiptto);
1090         MEMBDUP(references);
1091
1092         MEMBCOPY(score);
1093         MEMBCOPY(threadscore);
1094
1095         return newmsginfo;
1096 }
1097
1098 MsgInfo *procmsg_msginfo_get_full_info(MsgInfo *msginfo)
1099 {
1100         MsgInfo *full_msginfo;
1101         gchar *file;
1102
1103         if (msginfo == NULL) return NULL;
1104
1105         file = procmsg_get_message_file(msginfo);
1106         if (!file) {
1107                 g_warning("procmsg_msginfo_get_full_info(): can't get message file.\n");
1108                 return NULL;
1109         }
1110
1111         full_msginfo = procheader_parse_file(file, msginfo->flags, TRUE, FALSE);
1112         g_free(file);
1113         if (!full_msginfo) return NULL;
1114
1115         full_msginfo->msgnum = msginfo->msgnum;
1116         full_msginfo->size = msginfo->size;
1117         full_msginfo->mtime = msginfo->mtime;
1118         full_msginfo->folder = msginfo->folder;
1119         full_msginfo->to_folder = msginfo->to_folder;
1120 #if USE_GPGME
1121         full_msginfo->plaintext_file = g_strdup(msginfo->plaintext_file);
1122         full_msginfo->decryption_failed = msginfo->decryption_failed;
1123 #endif
1124
1125         return full_msginfo;
1126 }
1127
1128 void procmsg_msginfo_free(MsgInfo *msginfo)
1129 {
1130         if (msginfo == NULL) return;
1131
1132         msginfo->refcnt--;
1133         if (msginfo->refcnt > 0)
1134                 return;
1135
1136         g_free(msginfo->fromspace);
1137         g_free(msginfo->references);
1138         g_free(msginfo->returnreceiptto);
1139         g_free(msginfo->dispositionnotificationto);
1140         g_free(msginfo->xface);
1141
1142         g_free(msginfo->fromname);
1143
1144         g_free(msginfo->date);
1145         g_free(msginfo->from);
1146         g_free(msginfo->to);
1147         g_free(msginfo->cc);
1148         g_free(msginfo->newsgroups);
1149         g_free(msginfo->subject);
1150         g_free(msginfo->msgid);
1151         g_free(msginfo->inreplyto);
1152         g_free(msginfo->xref);
1153
1154         g_free(msginfo);
1155 }
1156
1157 guint procmsg_msginfo_memusage(MsgInfo *msginfo)
1158 {
1159         guint memusage = 0;
1160         
1161         memusage += sizeof(MsgInfo);
1162         if (msginfo->fromname)
1163                 memusage += strlen(msginfo->fromname);
1164         if (msginfo->date)
1165                 memusage += strlen(msginfo->date);
1166         if (msginfo->from)
1167                 memusage += strlen(msginfo->from);
1168         if (msginfo->to)
1169                 memusage += strlen(msginfo->to);
1170         if (msginfo->cc)
1171                 memusage += strlen(msginfo->cc);
1172         if (msginfo->newsgroups)
1173                 memusage += strlen(msginfo->newsgroups);
1174         if (msginfo->subject)
1175                 memusage += strlen(msginfo->subject);
1176         if (msginfo->msgid)
1177                 memusage += strlen(msginfo->msgid);
1178         if (msginfo->inreplyto)
1179                 memusage += strlen(msginfo->inreplyto);
1180         if (msginfo->xface)
1181                 memusage += strlen(msginfo->xface);
1182         if (msginfo->dispositionnotificationto)
1183                 memusage += strlen(msginfo->dispositionnotificationto);
1184         if (msginfo->returnreceiptto)
1185                 memusage += strlen(msginfo->returnreceiptto);
1186         if (msginfo->references)
1187                 memusage += strlen(msginfo->references);
1188         if (msginfo->fromspace)
1189                 memusage += strlen(msginfo->fromspace);
1190
1191         return memusage;
1192 }
1193
1194 gint procmsg_cmp_msgnum_for_sort(gconstpointer a, gconstpointer b)
1195 {
1196         const MsgInfo *msginfo1 = a;
1197         const MsgInfo *msginfo2 = b;
1198
1199         if (!msginfo1)
1200                 return -1;
1201         if (!msginfo2)
1202                 return -1;
1203
1204         return msginfo1->msgnum - msginfo2->msgnum;
1205 }
1206
1207 enum
1208 {
1209         Q_SENDER           = 0,
1210         Q_SMTPSERVER       = 1,
1211         Q_RECIPIENTS       = 2,
1212         Q_NEWSGROUPS       = 3,
1213         Q_MAIL_ACCOUNT_ID  = 4,
1214         Q_NEWS_ACCOUNT_ID  = 5,
1215         Q_SAVE_COPY_FOLDER = 6,
1216         Q_REPLY_MESSAGE_ID = 7,
1217 };
1218
1219 gint procmsg_send_message_queue(const gchar *file)
1220 {
1221         static HeaderEntry qentry[] = {{"S:",    NULL, FALSE},
1222                                        {"SSV:",  NULL, FALSE},
1223                                        {"R:",    NULL, FALSE},
1224                                        {"NG:",   NULL, FALSE},
1225                                        {"MAID:", NULL, FALSE},
1226                                        {"NAID:", NULL, FALSE},
1227                                        {"SCF:",  NULL, FALSE},
1228                                        {"RMID:", NULL, FALSE},
1229                                        {NULL,    NULL, FALSE}};
1230         FILE *fp;
1231         gint filepos;
1232         gint mailval = 0, newsval = 0;
1233         gchar *from = NULL;
1234         gchar *smtpserver = NULL;
1235         GSList *to_list = NULL;
1236         GSList *newsgroup_list = NULL;
1237         gchar *savecopyfolder = NULL;
1238         gchar *replymessageid = NULL;
1239         gchar buf[BUFFSIZE];
1240         gint hnum;
1241         PrefsAccount *mailac = NULL, *newsac = NULL;
1242         int local = 0;
1243
1244         g_return_val_if_fail(file != NULL, -1);
1245
1246         if ((fp = fopen(file, "rb")) == NULL) {
1247                 FILE_OP_ERROR(file, "fopen");
1248                 return -1;
1249         }
1250
1251         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, qentry))
1252                != -1) {
1253                 gchar *p = buf + strlen(qentry[hnum].name);
1254
1255                 switch (hnum) {
1256                 case Q_SENDER:
1257                         if (!from) from = g_strdup(p);
1258                         break;
1259                 case Q_SMTPSERVER:
1260                         if (!smtpserver) smtpserver = g_strdup(p);
1261                         break;
1262                 case Q_RECIPIENTS:
1263                         to_list = address_list_append(to_list, p);
1264                         break;
1265                 case Q_NEWSGROUPS:
1266                         newsgroup_list = newsgroup_list_append(newsgroup_list, p);
1267                         break;
1268                 case Q_MAIL_ACCOUNT_ID:
1269                         mailac = account_find_from_id(atoi(p));
1270                         break;
1271                 case Q_NEWS_ACCOUNT_ID:
1272                         newsac = account_find_from_id(atoi(p));
1273                         break;
1274                 case Q_SAVE_COPY_FOLDER:
1275                         if (!savecopyfolder) savecopyfolder = g_strdup(p);
1276                         break;
1277                 case Q_REPLY_MESSAGE_ID:
1278                         if (!replymessageid) replymessageid = g_strdup(p);
1279                         break;
1280                 }
1281         }
1282         filepos = ftell(fp);
1283
1284         if (to_list) {
1285                 debug_print("Sending message by mail\n");
1286                 if (!from) {
1287                         g_warning("Queued message header is broken.\n");
1288                         mailval = -1;
1289                 } else if (mailac && mailac->use_mail_command &&
1290                            mailac->mail_command && (* mailac->mail_command)) {
1291                         mailval = send_message_local(mailac->mail_command, fp);
1292                         local = 1;
1293                 } else if (prefs_common.use_extsend && prefs_common.extsend_cmd) {
1294                         mailval = send_message_local(prefs_common.extsend_cmd, fp);
1295                         local = 1;
1296                 } else {
1297                         if (!mailac) {
1298                                 mailac = account_find_from_smtp_server(from, smtpserver);
1299                                 if (!mailac) {
1300                                         g_warning("Account not found. "
1301                                                     "Using current account...\n");
1302                                         mailac = cur_account;
1303                                 }
1304                         }
1305
1306                         if (mailac)
1307                                 mailval = send_message_smtp(mailac, to_list, fp);
1308                         else {
1309                                 PrefsAccount tmp_ac;
1310
1311                                 g_warning("Account not found.\n");
1312
1313                                 memset(&tmp_ac, 0, sizeof(PrefsAccount));
1314                                 tmp_ac.address = from;
1315                                 tmp_ac.smtp_server = smtpserver;
1316                                 tmp_ac.smtpport = SMTP_PORT;
1317                                 mailval = send_message_smtp(&tmp_ac, to_list, fp);
1318                         }
1319                 }
1320                 if (mailval < 0) {
1321                         if (!local)
1322                                 alertpanel_error(
1323                                         _("Error occurred while sending the message to `%s'."),
1324                                         mailac ? mailac->smtp_server : smtpserver);
1325                         else
1326                                 alertpanel_error(
1327                                         _("Error occurred while sending the message with command `%s'."),
1328                                         (mailac && mailac->use_mail_command && 
1329                                          mailac->mail_command && (*mailac->mail_command)) ? 
1330                                                 mailac->mail_command : prefs_common.extsend_cmd);
1331                 }
1332         }
1333
1334         fseek(fp, filepos, SEEK_SET);
1335         if (newsgroup_list && (newsval == 0)) {
1336                 Folder *folder;
1337                 gchar *tmp = NULL;
1338                 FILE *tmpfp;
1339
1340                 /* write to temporary file */
1341                 tmp = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
1342                             G_DIR_SEPARATOR, (gint)file);
1343                 if ((tmpfp = fopen(tmp, "wb")) == NULL) {
1344                         FILE_OP_ERROR(tmp, "fopen");
1345                         newsval = -1;
1346                         alertpanel_error(_("Could not create temporary file for news sending."));
1347                 } else {
1348                         if (change_file_mode_rw(tmpfp, tmp) < 0) {
1349                                 FILE_OP_ERROR(tmp, "chmod");
1350                                 g_warning("can't change file mode\n");
1351                         }
1352
1353                         while ((newsval == 0) && fgets(buf, sizeof(buf), fp) != NULL) {
1354                                 if (fputs(buf, tmpfp) == EOF) {
1355                                         FILE_OP_ERROR(tmp, "fputs");
1356                                         newsval = -1;
1357                                         alertpanel_error(_("Error when writing temporary file for news sending."));
1358                                 }
1359                         }
1360                         fclose(tmpfp);
1361
1362                         if (newsval == 0) {
1363                                 debug_print("Sending message by news\n");
1364
1365                                 folder = FOLDER(newsac->folder);
1366
1367                                 newsval = news_post(folder, tmp);
1368                                 if (newsval < 0) {
1369                                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1370                                                  newsac->nntp_server);
1371                                 }
1372                         }
1373                         unlink(tmp);
1374                 }
1375                 g_free(tmp);
1376         }
1377
1378         slist_free_strings(to_list);
1379         g_slist_free(to_list);
1380         slist_free_strings(newsgroup_list);
1381         g_slist_free(newsgroup_list);
1382         g_free(from);
1383         g_free(smtpserver);
1384         fclose(fp);
1385
1386         /* save message to outbox */
1387         if (mailval == 0 && newsval == 0 && savecopyfolder) {
1388                 FolderItem *outbox;
1389
1390                 debug_print("saving sent message...\n");
1391
1392                 outbox = folder_find_item_from_identifier(savecopyfolder);
1393                 if (!outbox)
1394                         outbox = folder_get_default_outbox();
1395
1396                 procmsg_save_to_outbox(outbox, file, TRUE);
1397         }
1398
1399         if (replymessageid != NULL) {
1400                 gchar **tokens;
1401                 FolderItem *item;
1402                 
1403                 tokens = g_strsplit(replymessageid, "\x7f", 0);
1404                 item = folder_find_item_from_identifier(tokens[0]);
1405                 if (item != NULL) {
1406                         MsgInfo *msginfo;
1407                         
1408                         msginfo = folder_item_get_msginfo(item, atoi(tokens[1]));
1409                         if ((msginfo != NULL) && (strcmp(msginfo->msgid, tokens[2]) != 0)) {
1410                                 procmsg_msginfo_free(msginfo);
1411                                 msginfo = NULL;
1412                         }
1413                         
1414                         if (msginfo == NULL) {
1415                                 msginfo = folder_item_get_msginfo_by_msgid(item, tokens[2]);
1416                         }
1417                         
1418                         if (msginfo != NULL) {
1419                                 procmsg_msginfo_unset_flags(msginfo, MSG_FORWARDED, 0);
1420                                 procmsg_msginfo_set_flags(msginfo, MSG_REPLIED, 0);
1421
1422                                 procmsg_msginfo_free(msginfo);
1423                         }
1424                 }
1425                 g_strfreev(tokens);
1426         }
1427
1428         g_free(savecopyfolder);
1429         g_free(replymessageid);
1430         
1431         return (newsval != 0 ? newsval : mailval);
1432 }
1433
1434 #define CHANGE_FLAGS(msginfo) \
1435 { \
1436 if (msginfo->folder->folder->change_flags != NULL) \
1437 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
1438                                       msginfo->folder, \
1439                                       msginfo); \
1440 }
1441
1442 void procmsg_msginfo_set_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1443 {
1444         FolderItem *item;
1445         MsgInfoUpdate msginfo_update;
1446
1447         g_return_if_fail(msginfo != NULL);
1448         item = msginfo->folder;
1449         g_return_if_fail(item != NULL);
1450         
1451         debug_print("Setting flags for message %d in folder %s\n", msginfo->msgnum, item->path);
1452
1453         /* if new flag is set */
1454         if ((perm_flags & MSG_NEW) && !MSG_IS_NEW(msginfo->flags) &&
1455            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1456                 item->new++;
1457                 item->need_update = TRUE;
1458         }
1459
1460         /* if unread flag is set */
1461         if ((perm_flags & MSG_UNREAD) && !MSG_IS_UNREAD(msginfo->flags) &&
1462            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1463                 item->unread++;
1464                 item->need_update = TRUE;
1465         }
1466
1467         if (!MSG_IS_UNREAD(msginfo->flags) &&(perm_flags & MSG_UNREAD)
1468         && procmsg_msg_has_marked_parent(msginfo)) {
1469                 item->unreadmarked++;
1470                 item->need_update = TRUE;
1471         }
1472         
1473         if (!MSG_IS_MARKED(msginfo->flags) && (perm_flags & MSG_MARKED)) {
1474                 procmsg_update_unread_children(msginfo, TRUE);
1475         }
1476
1477
1478         /* if ignore thread flag is set */
1479         if ((perm_flags & MSG_IGNORE_THREAD) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1480                 if (MSG_IS_NEW(msginfo->flags) || (perm_flags & MSG_NEW)) {
1481                         item->new--;
1482                         item->need_update = TRUE;
1483                 }
1484                 if (MSG_IS_UNREAD(msginfo->flags) || (perm_flags & MSG_UNREAD)) {
1485                         item->unread--;
1486                         item->need_update = TRUE;
1487                 }
1488                 if ((perm_flags & MSG_UNREAD) || (MSG_IS_UNREAD(msginfo->flags)
1489                 && procmsg_msg_has_marked_parent(msginfo))) {
1490                         item->unreadmarked--;
1491                         item->need_update = TRUE;
1492                 }
1493                 if ((perm_flags & MSG_MARKED) || (MSG_IS_MARKED(msginfo->flags)
1494                 && !MSG_IS_IGNORE_THREAD(msginfo->flags))) {
1495                         procmsg_update_unread_children(msginfo, FALSE);
1496                 }
1497
1498         }
1499
1500         if (MSG_IS_IMAP(msginfo->flags))
1501                 imap_msg_set_perm_flags(msginfo, perm_flags);
1502
1503         msginfo->flags.perm_flags |= perm_flags;
1504         msginfo->flags.tmp_flags |= tmp_flags;
1505
1506         msginfo_update.msginfo = msginfo;
1507         hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
1508
1509         CHANGE_FLAGS(msginfo);
1510         procmsg_msginfo_write_flags(msginfo);
1511 }
1512
1513 void procmsg_msginfo_unset_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1514 {
1515         FolderItem *item;
1516         MsgInfoUpdate msginfo_update;
1517
1518         g_return_if_fail(msginfo != NULL);
1519         item = msginfo->folder;
1520         g_return_if_fail(item != NULL); 
1521         
1522         debug_print("Unsetting flags for message %d in folder %s\n", msginfo->msgnum, item->path);
1523
1524         /* if new flag is unset */
1525         if ((perm_flags & MSG_NEW) && MSG_IS_NEW(msginfo->flags) &&
1526            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1527                 item->new--;
1528                 item->need_update = TRUE;
1529         }
1530
1531         /* if unread flag is unset */
1532         if ((perm_flags & MSG_UNREAD) && MSG_IS_UNREAD(msginfo->flags) &&
1533            !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1534                 item->unread--;
1535                 item->need_update = TRUE;
1536         }
1537         
1538         if (MSG_IS_UNREAD(msginfo->flags) && (perm_flags & MSG_UNREAD)
1539         && !MSG_IS_IGNORE_THREAD(msginfo->flags)
1540         && procmsg_msg_has_marked_parent(msginfo)) {
1541                 item->unreadmarked--;
1542                 item->need_update = TRUE;
1543         }
1544
1545         if (MSG_IS_MARKED(msginfo->flags) && (perm_flags & MSG_MARKED)
1546         && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1547                 procmsg_update_unread_children(msginfo, FALSE);
1548         }
1549
1550         /* if ignore thread flag is unset */
1551         if ((perm_flags & MSG_IGNORE_THREAD) && MSG_IS_IGNORE_THREAD(msginfo->flags)) {
1552                 if (MSG_IS_NEW(msginfo->flags) && !(perm_flags & MSG_NEW)) {
1553                         item->new++;
1554                         item->need_update = TRUE;
1555                 }
1556                 if (MSG_IS_UNREAD(msginfo->flags) && !(perm_flags & MSG_UNREAD)) {
1557                         item->unread++;
1558                         item->need_update = TRUE;
1559                 }
1560                 if (MSG_IS_UNREAD(msginfo->flags) && !(perm_flags & MSG_UNREAD)
1561                 && procmsg_msg_has_marked_parent(msginfo)) {
1562                         item->unreadmarked++;
1563                         item->need_update = TRUE;
1564                 }
1565                 if (MSG_IS_MARKED(msginfo->flags) && !(perm_flags & MSG_MARKED)) {
1566                         procmsg_update_unread_children(msginfo, TRUE);
1567                 }
1568
1569         }
1570
1571         if (MSG_IS_IMAP(msginfo->flags))
1572                 imap_msg_unset_perm_flags(msginfo, perm_flags);
1573
1574         msginfo->flags.perm_flags &= ~perm_flags;
1575         msginfo->flags.tmp_flags &= ~tmp_flags;
1576
1577         msginfo_update.msginfo = msginfo;
1578         hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
1579
1580         CHANGE_FLAGS(msginfo);
1581         procmsg_msginfo_write_flags(msginfo);
1582 }
1583
1584 void procmsg_msginfo_write_flags(MsgInfo *msginfo)
1585 {
1586         gchar *destdir;
1587         FILE *fp;
1588
1589         destdir = folder_item_get_path(msginfo->folder);
1590         if (!is_dir_exist(destdir))
1591                 make_dir_hier(destdir);
1592
1593         if ((fp = procmsg_open_mark_file(destdir, TRUE))) {
1594                 procmsg_write_flags(msginfo, fp);
1595                 fclose(fp);
1596         } else {
1597                 g_warning("Can't open mark file.\n");
1598         }
1599         
1600         g_free(destdir);
1601 }
1602
1603 /*!
1604  *\brief        check for flags (e.g. mark) in prior msgs of current thread
1605  *
1606  *\param        info Current message
1607  *\param        perm_flags Flags to be checked
1608  *\param        parentmsgs Hash of prior msgs to avoid loops
1609  *
1610  *\return       gboolean TRUE if perm_flags are found
1611  */
1612 gboolean procmsg_msg_has_flagged_parent_real(MsgInfo *info,
1613                 MsgPermFlags perm_flags, GHashTable *parentmsgs)
1614 {
1615         MsgInfo *tmp;
1616
1617         g_return_val_if_fail(info != NULL, FALSE);
1618
1619         if (info != NULL && info->folder != NULL && info->inreplyto != NULL) {
1620                 tmp = folder_item_get_msginfo_by_msgid(info->folder,
1621                                 info->inreplyto);
1622                 if (tmp && (tmp->flags.perm_flags & perm_flags)) {
1623                         procmsg_msginfo_free(tmp);
1624                         return TRUE;
1625                 } else if (tmp != NULL) {
1626                         gboolean result;
1627
1628                         if (g_hash_table_lookup(parentmsgs, info)) {
1629                                 debug_print("loop detected: %s%c%d\n",
1630                                         folder_item_get_path(info->folder),
1631                                         G_DIR_SEPARATOR, info->msgnum);
1632                                 result = FALSE;
1633                         } else {
1634                                 g_hash_table_insert(parentmsgs, info, "1");
1635                                 result = procmsg_msg_has_flagged_parent_real(
1636                                     tmp, perm_flags, parentmsgs);
1637                         }
1638                         procmsg_msginfo_free(tmp);
1639                         return result;
1640                 } else {
1641                         return FALSE;
1642                 }
1643         } else
1644                 return FALSE;
1645 }
1646
1647 /*!
1648  *\brief        Callback for cleaning up hash of parentmsgs
1649  */
1650 gboolean parentmsgs_hash_remove(gpointer key,
1651                             gpointer value,
1652                             gpointer user_data)
1653 {
1654         return TRUE;
1655 }
1656
1657 /*!
1658  *\brief        Set up list of parentmsgs
1659  *              See procmsg_msg_has_flagged_parent_real()
1660  */
1661 gboolean procmsg_msg_has_flagged_parent(MsgInfo *info, MsgPermFlags perm_flags)
1662 {
1663         gboolean result;
1664         GHashTable *parentmsgs = g_hash_table_new(NULL, NULL); 
1665
1666         result = procmsg_msg_has_flagged_parent_real(info, perm_flags, parentmsgs);
1667         g_hash_table_foreach_remove(parentmsgs, parentmsgs_hash_remove, NULL);
1668         g_hash_table_destroy(parentmsgs);
1669         return result;
1670 }
1671
1672 /*!
1673  *\brief        Check if msgs prior in thread are marked
1674  *              See procmsg_msg_has_flagged_parent_real()
1675  */
1676 gboolean procmsg_msg_has_marked_parent(MsgInfo *info)
1677 {
1678         return procmsg_msg_has_flagged_parent(info, MSG_MARKED);
1679 }
1680
1681
1682 GSList *procmsg_find_children (MsgInfo *info)
1683 {
1684         GSList *children = NULL;
1685         GSList *all, *cur;
1686         
1687         g_return_val_if_fail(info!=NULL, NULL);
1688         if (info->msgid == NULL)
1689                 return NULL;
1690         all = folder_item_get_msg_list(info->folder);
1691         for (cur = all; cur != NULL; cur = g_slist_next(cur)) {
1692                 MsgInfo *tmp = (MsgInfo *)cur->data;
1693                 if (tmp->inreplyto && !strcmp(tmp->inreplyto, info->msgid)) {
1694                         GSList *grand_children;
1695                         children = g_slist_prepend(children, tmp);
1696                         grand_children = procmsg_find_children(tmp);
1697                         children = slist_concat_unique(children, grand_children);
1698                         g_slist_free(grand_children);
1699                 }
1700                 if (tmp && tmp != info)
1701                         procmsg_msginfo_free(tmp);
1702         }
1703         
1704         return children;
1705 }
1706
1707 static void procmsg_update_unread_children (MsgInfo *info, gboolean newly_marked)
1708 {
1709         GSList *children = procmsg_find_children(info);
1710         GSList *cur;
1711         for (cur = children; cur != NULL; cur = g_slist_next(cur)) {
1712                 MsgInfo *tmp = (MsgInfo *)cur->data;
1713                 if(MSG_IS_UNREAD(tmp->flags) && !MSG_IS_IGNORE_THREAD(tmp->flags)) {
1714                         if(newly_marked) 
1715                                 info->folder->unreadmarked++;
1716                         else
1717                                 info->folder->unreadmarked--;
1718                         info->folder->need_update = TRUE;
1719                 }
1720                 procmsg_msginfo_free(tmp);
1721         }
1722 }