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