0.9.0claws76
[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 #include <ctype.h>
26
27 #include "intl.h"
28 #include "main.h"
29 #include "utils.h"
30 #include "procmsg.h"
31 #include "procheader.h"
32 #include "send_message.h"
33 #include "procmime.h"
34 #include "statusbar.h"
35 #include "prefs_filtering.h"
36 #include "filtering.h"
37 #include "folder.h"
38 #include "prefs_common.h"
39 #include "account.h"
40 #if USE_GPGME
41 #  include "rfc2015.h"
42 #endif
43 #include "alertpanel.h"
44 #include "news.h"
45 #include "hooks.h"
46 #include "msgcache.h"
47
48 GHashTable *procmsg_msg_hash_table_create(GSList *mlist)
49 {
50         GHashTable *msg_table;
51
52         if (mlist == NULL) return NULL;
53
54         msg_table = g_hash_table_new(NULL, g_direct_equal);
55         procmsg_msg_hash_table_append(msg_table, mlist);
56
57         return msg_table;
58 }
59
60 void procmsg_msg_hash_table_append(GHashTable *msg_table, GSList *mlist)
61 {
62         GSList *cur;
63         MsgInfo *msginfo;
64
65         if (msg_table == NULL || mlist == NULL) return;
66
67         for (cur = mlist; cur != NULL; cur = cur->next) {
68                 msginfo = (MsgInfo *)cur->data;
69
70                 g_hash_table_insert(msg_table,
71                                     GUINT_TO_POINTER(msginfo->msgnum),
72                                     msginfo);
73         }
74 }
75
76 GHashTable *procmsg_to_folder_hash_table_create(GSList *mlist)
77 {
78         GHashTable *msg_table;
79         GSList *cur;
80         MsgInfo *msginfo;
81
82         if (mlist == NULL) return NULL;
83
84         msg_table = g_hash_table_new(NULL, g_direct_equal);
85
86         for (cur = mlist; cur != NULL; cur = cur->next) {
87                 msginfo = (MsgInfo *)cur->data;
88                 g_hash_table_insert(msg_table, msginfo->to_folder, msginfo);
89         }
90
91         return msg_table;
92 }
93
94 gint procmsg_get_last_num_in_msg_list(GSList *mlist)
95 {
96         GSList *cur;
97         MsgInfo *msginfo;
98         gint last = 0;
99
100         for (cur = mlist; cur != NULL; cur = cur->next) {
101                 msginfo = (MsgInfo *)cur->data;
102                 if (msginfo && msginfo->msgnum > last)
103                         last = msginfo->msgnum;
104         }
105
106         return last;
107 }
108
109 void procmsg_msg_list_free(GSList *mlist)
110 {
111         GSList *cur;
112         MsgInfo *msginfo;
113
114         for (cur = mlist; cur != NULL; cur = cur->next) {
115                 msginfo = (MsgInfo *)cur->data;
116                 procmsg_msginfo_free(msginfo);
117         }
118         g_slist_free(mlist);
119 }
120
121 struct MarkSum {
122         gint *new_msgs;
123         gint *unread_msgs;
124         gint *total_msgs;
125         gint *min;
126         gint *max;
127         gint first;
128 };
129
130 static gboolean procmsg_ignore_node(GNode *node, gpointer data)
131 {
132         MsgInfo *msginfo = (MsgInfo *)node->data;
133         
134         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
135         procmsg_msginfo_set_flags(msginfo, MSG_IGNORE_THREAD, 0);
136
137         return FALSE;
138 }
139
140 /* return the reversed thread tree */
141 GNode *procmsg_get_thread_tree(GSList *mlist)
142 {
143         GNode *root, *parent, *node, *next, *last;
144         GHashTable *msgid_table;
145         GHashTable *subject_table;
146         MsgInfo *msginfo;
147         const gchar *msgid;
148         const gchar *subject;
149         GNode *found_subject;
150
151         root = g_node_new(NULL);
152         msgid_table = g_hash_table_new(g_str_hash, g_str_equal);
153         subject_table = g_hash_table_new(g_str_hash, g_str_equal);
154
155         for (; mlist != NULL; mlist = mlist->next) {
156                 msginfo = (MsgInfo *)mlist->data;
157                 parent = root;
158
159                 if (msginfo->inreplyto) {
160                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
161                         if (parent == NULL) {
162                                 parent = root;
163                         } else {
164                                 if (MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
165                                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
166                                         procmsg_msginfo_set_flags(msginfo, MSG_IGNORE_THREAD, 0);
167                                 }
168                         }
169                 }
170                 node = g_node_insert_data_before
171                         (parent, parent == root ? parent->children : NULL,
172                          msginfo);
173                 if ((msgid = msginfo->msgid) &&
174                     g_hash_table_lookup(msgid_table, msgid) == NULL)
175                         g_hash_table_insert(msgid_table, (gchar *)msgid, node);
176
177                 if (prefs_common.thread_by_subject) {
178                         subject  = msginfo->subject;
179                         subject += subject_get_reply_prefix_length(subject);
180                         found_subject = subject_table_lookup_clean(subject_table,
181                                                                    (gchar *) subject);
182                         if (found_subject == NULL)
183                                 subject_table_insert_clean(subject_table, (gchar *) subject,
184                                                            node);
185                         else {
186                                 /* replace if msg in table is older than current one 
187                                  * can add here more stuff. */
188                                 if ( ((MsgInfo*)(found_subject->data))->date_t > 
189                                      ((MsgInfo*)(node->data))->date_t )  {
190                                         subject_table_remove_clean(subject_table, (gchar *) subject);
191                                         subject_table_insert_clean(subject_table, (gchar *) subject, node);
192                                 } 
193                         }
194                 }
195         }
196
197         /* complete the unfinished threads */
198         for (node = root->children; node != NULL; ) {
199                 next = node->next;
200                 msginfo = (MsgInfo *)node->data;
201                 parent = NULL;
202                 if (msginfo->inreplyto) 
203                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
204                 /* node should not be the parent, and node should not be an ancestor
205                  * of parent (circular reference) */
206                 if (parent && parent != node 
207                 && !g_node_is_ancestor(node, parent)) {
208                         g_node_unlink(node);
209                         g_node_insert_before
210                                 (parent, parent->children, node);
211                         /* CLAWS: ignore thread */
212                         if (MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
213                                 g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, procmsg_ignore_node, NULL);
214                         }
215                 }
216                 last = node; /* CLAWS: need to have the last one for subject threading */
217                 node = next;
218         }
219
220         /* CLAWS: now see if the first level (below root) still has some nodes that can be
221          * threaded by subject line. we need to handle this in a special way to prevent
222          * circular reference from a node that has already been threaded by IN-REPLY-TO
223          * but is also in the subject line hash table */
224         if (prefs_common.thread_by_subject) {
225                 for (node = last; node && node != NULL;) {
226                         next = node->prev;
227                         msginfo = (MsgInfo *) node->data;
228                         subject = msginfo->subject + subject_get_reply_prefix_length(msginfo->subject);
229                         parent = subject_table_lookup_clean(subject_table, (gchar *) subject);
230                         
231                         /* the node may already be threaded by IN-REPLY-TO,
232                            so go up in the tree to find the parent node */
233                         if (parent != NULL) {
234                                 if (g_node_is_ancestor(node, parent))
235                                         parent = NULL;
236                                 if (parent == node)
237                                         parent = NULL;
238                                 /* Make new thread parent if too old compared to previous one; probably
239                                  * breaks ignoring threads for subject threading. This still isn't
240                                  * accurate because the tree isn't sorted by date. */   
241                                 if (parent && abs(difftime(msginfo->date_t, ((MsgInfo *)parent->data)->date_t)) >
242                                                 prefs_common.thread_by_subject_max_age * 3600 * 24) {
243                                         subject_table_remove_clean(subject_table, (gchar *) subject);
244                                         subject_table_insert_clean(subject_table, (gchar *) subject, node);
245                                         parent = NULL;
246                                 }
247                         }
248
249                         if (parent) {
250                                 g_node_unlink(node);
251                                 g_node_append(parent, node);
252                                 /* CLAWS: ignore thread */
253                                 if (MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags)) {
254                                         g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, procmsg_ignore_node, NULL);
255                                 }
256                         }
257                         node = next;
258                 }       
259         }
260         
261         g_hash_table_destroy(subject_table);
262         g_hash_table_destroy(msgid_table);
263
264         return root;
265 }
266
267 void procmsg_move_messages(GSList *mlist)
268 {
269         GSList *cur, *movelist = NULL;
270         MsgInfo *msginfo;
271         FolderItem *dest = NULL;
272
273         if (!mlist) return;
274
275         folder_item_update_freeze();
276
277         for (cur = mlist; cur != NULL; cur = cur->next) {
278                 msginfo = (MsgInfo *)cur->data;
279                 if (!dest) {
280                         dest = msginfo->to_folder;
281                         movelist = g_slist_append(movelist, msginfo);
282                 } else if (dest == msginfo->to_folder) {
283                         movelist = g_slist_append(movelist, msginfo);
284                 } else {
285                         folder_item_move_msgs_with_dest(dest, movelist);
286                         g_slist_free(movelist);
287                         movelist = NULL;
288                         dest = msginfo->to_folder;
289                         movelist = g_slist_append(movelist, msginfo);
290                 }
291                 procmsg_msginfo_set_to_folder(msginfo, NULL);
292         }
293
294         if (movelist) {
295                 folder_item_move_msgs_with_dest(dest, movelist);
296                 g_slist_free(movelist);
297         }
298
299         folder_item_update_thaw();
300 }
301
302 void procmsg_copy_messages(GSList *mlist)
303 {
304         GSList *cur, *copylist = NULL;
305         MsgInfo *msginfo;
306         FolderItem *dest = NULL;
307
308         if (!mlist) return;
309
310         folder_item_update_freeze();
311
312         for (cur = mlist; cur != NULL; cur = cur->next) {
313                 msginfo = (MsgInfo *)cur->data;
314                 if (!dest) {
315                         dest = msginfo->to_folder;
316                         copylist = g_slist_append(copylist, msginfo);
317                 } else if (dest == msginfo->to_folder) {
318                         copylist = g_slist_append(copylist, msginfo);
319                 } else {
320                         folder_item_copy_msgs_with_dest(dest, copylist);
321                         g_slist_free(copylist);
322                         copylist = NULL;
323                         dest = msginfo->to_folder;
324                         copylist = g_slist_append(copylist, msginfo);
325                 }
326                 procmsg_msginfo_set_to_folder(msginfo, NULL);
327         }
328
329         if (copylist) {
330                 folder_item_copy_msgs_with_dest(dest, copylist);
331                 g_slist_free(copylist);
332         }
333
334         folder_item_update_thaw();
335 }
336
337 gchar *procmsg_get_message_file_path(MsgInfo *msginfo)
338 {
339         gchar *file;
340
341         g_return_val_if_fail(msginfo != NULL, NULL);
342
343         if (msginfo->plaintext_file)
344                 file = g_strdup(msginfo->plaintext_file);
345         else {
346                 file = folder_item_fetch_msg(msginfo->folder, msginfo->msgnum);
347         }
348
349         return file;
350 }
351
352 gchar *procmsg_get_message_file(MsgInfo *msginfo)
353 {
354         gchar *filename = NULL;
355
356         g_return_val_if_fail(msginfo != NULL, NULL);
357
358         filename = folder_item_fetch_msg(msginfo->folder, msginfo->msgnum);
359         if (!filename)
360                 g_warning("can't fetch message %d\n", msginfo->msgnum);
361
362         return filename;
363 }
364
365 FILE *procmsg_open_message(MsgInfo *msginfo)
366 {
367         FILE *fp;
368         gchar *file;
369
370         g_return_val_if_fail(msginfo != NULL, NULL);
371
372         file = procmsg_get_message_file_path(msginfo);
373         g_return_val_if_fail(file != NULL, NULL);
374
375         if (!is_file_exist(file)) {
376                 g_free(file);
377                 file = procmsg_get_message_file(msginfo);
378                 g_return_val_if_fail(file != NULL, NULL);
379         }
380
381         if ((fp = fopen(file, "rb")) == NULL) {
382                 FILE_OP_ERROR(file, "fopen");
383                 g_free(file);
384                 return NULL;
385         }
386
387         g_free(file);
388
389         if (MSG_IS_QUEUED(msginfo->flags) || MSG_IS_DRAFT(msginfo->flags)) {
390                 gchar buf[BUFFSIZE];
391
392                 while (fgets(buf, sizeof(buf), fp) != NULL)
393                         if (buf[0] == '\r' || buf[0] == '\n') break;
394         }
395
396         return fp;
397 }
398
399 #if USE_GPGME
400 FILE *procmsg_open_message_decrypted(MsgInfo *msginfo, MimeInfo **mimeinfo)
401 {
402         FILE *fp;
403         MimeInfo *mimeinfo_;
404         glong fpos;
405
406         g_return_val_if_fail(msginfo != NULL, NULL);
407
408         if (mimeinfo) *mimeinfo = NULL;
409
410         if ((fp = procmsg_open_message(msginfo)) == NULL) return NULL;
411
412         mimeinfo_ = procmime_scan_mime_header(fp);
413         if (!mimeinfo_) {
414                 fclose(fp);
415                 return NULL;
416         }
417
418         if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
419             rfc2015_is_encrypted(mimeinfo_)) {
420                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
421         }
422
423         if (MSG_IS_ENCRYPTED(msginfo->flags) &&
424             !msginfo->plaintext_file &&
425             !msginfo->decryption_failed) {
426                 fpos = ftell(fp);
427                 rfc2015_decrypt_message(msginfo, mimeinfo_, fp);
428                 if (msginfo->plaintext_file &&
429                     !msginfo->decryption_failed) {
430                         fclose(fp);
431                         procmime_mimeinfo_free_all(mimeinfo_);
432                         if ((fp = procmsg_open_message(msginfo)) == NULL)
433                                 return NULL;
434                         mimeinfo_ = procmime_scan_mime_header(fp);
435                         if (!mimeinfo_) {
436                                 fclose(fp);
437                                 return NULL;
438                         }
439                 } else {
440                         if (fseek(fp, fpos, SEEK_SET) < 0)
441                                 perror("fseek");
442                 }
443         }
444
445         if (mimeinfo) *mimeinfo = mimeinfo_;
446         return fp;
447 }
448 #endif
449
450 gboolean procmsg_msg_exist(MsgInfo *msginfo)
451 {
452         gchar *path;
453         gboolean ret;
454
455         if (!msginfo) return FALSE;
456
457         path = folder_item_get_path(msginfo->folder);
458         change_dir(path);
459         ret = !folder_item_is_msg_changed(msginfo->folder, msginfo);
460         g_free(path);
461
462         return ret;
463 }
464
465 void procmsg_get_filter_keyword(MsgInfo *msginfo, gchar **header, gchar **key,
466                                 PrefsFilterType type)
467 {
468         static HeaderEntry hentry[] = {{"X-BeenThere:",    NULL, TRUE},
469                                        {"X-ML-Name:",      NULL, TRUE},
470                                        {"X-List:",         NULL, TRUE},
471                                        {"X-Mailing-list:", NULL, TRUE},
472                                        {"List-Id:",        NULL, TRUE},
473                                        {"X-Sequence:",     NULL, TRUE},
474                                        {NULL,              NULL, FALSE}};
475         enum
476         {
477                 H_X_BEENTHERE    = 0,
478                 H_X_ML_NAME      = 1,
479                 H_X_LIST         = 2,
480                 H_X_MAILING_LIST = 3,
481                 H_LIST_ID        = 4,
482                 H_X_SEQUENCE     = 5
483         };
484
485         FILE *fp;
486
487         g_return_if_fail(msginfo != NULL);
488         g_return_if_fail(header != NULL);
489         g_return_if_fail(key != NULL);
490
491         *header = NULL;
492         *key = NULL;
493
494         switch (type) {
495         case FILTER_BY_NONE:
496                 return;
497         case FILTER_BY_AUTO:
498                 if ((fp = procmsg_open_message(msginfo)) == NULL)
499                         return;
500                 procheader_get_header_fields(fp, hentry);
501                 fclose(fp);
502
503 #define SET_FILTER_KEY(hstr, idx)       \
504 {                                       \
505         *header = g_strdup(hstr);       \
506         *key = hentry[idx].body;        \
507         hentry[idx].body = NULL;        \
508 }
509
510                 if (hentry[H_X_BEENTHERE].body != NULL) {
511                         SET_FILTER_KEY("header \"X-BeenThere\"", H_X_BEENTHERE);
512                 } else if (hentry[H_X_ML_NAME].body != NULL) {
513                         SET_FILTER_KEY("header \"X-ML-Name\"", H_X_ML_NAME);
514                 } else if (hentry[H_X_LIST].body != NULL) {
515                         SET_FILTER_KEY("header \"X-List\"", H_X_LIST);
516                 } else if (hentry[H_X_MAILING_LIST].body != NULL) {
517                         SET_FILTER_KEY("header \"X-Mailing-List\"", H_X_MAILING_LIST);
518                 } else if (hentry[H_LIST_ID].body != NULL) {
519                         SET_FILTER_KEY("header \"List-Id\"", H_LIST_ID);
520                         extract_list_id_str(*key);
521                 } else if (hentry[H_X_SEQUENCE].body != NULL) {
522                         gchar *p;
523
524                         SET_FILTER_KEY("X-Sequence", H_X_SEQUENCE);
525                         p = *key;
526                         while (*p != '\0') {
527                                 while (*p != '\0' && !isspace(*p)) p++;
528                                 while (isspace(*p)) p++;
529                                 if (isdigit(*p)) {
530                                         *p = '\0';
531                                         break;
532                                 }
533                         }
534                         g_strstrip(*key);
535                 } else if (msginfo->subject) {
536                         *header = g_strdup("subject");
537                         *key = g_strdup(msginfo->subject);
538                 }
539
540 #undef SET_FILTER_KEY
541
542                 g_free(hentry[H_X_BEENTHERE].body);
543                 hentry[H_X_BEENTHERE].body = NULL;
544                 g_free(hentry[H_X_ML_NAME].body);
545                 hentry[H_X_ML_NAME].body = NULL;
546                 g_free(hentry[H_X_LIST].body);
547                 hentry[H_X_LIST].body = NULL;
548                 g_free(hentry[H_X_MAILING_LIST].body);
549                 hentry[H_X_MAILING_LIST].body = NULL;
550                 g_free(hentry[H_LIST_ID].body);
551                 hentry[H_LIST_ID].body = NULL;
552
553                 break;
554         case FILTER_BY_FROM:
555                 *header = g_strdup("from");
556                 *key = g_strdup(msginfo->from);
557                 break;
558         case FILTER_BY_TO:
559                 *header = g_strdup("to");
560                 *key = g_strdup(msginfo->to);
561                 break;
562         case FILTER_BY_SUBJECT:
563                 *header = g_strdup("subject");
564                 *key = g_strdup(msginfo->subject);
565                 break;
566         default:
567                 break;
568         }
569 }
570
571 void procmsg_empty_trash(void)
572 {
573         FolderItem *trash;
574         GList *cur;
575
576         for (cur = folder_get_list(); cur != NULL; cur = cur->next) {
577                 trash = FOLDER(cur->data)->trash;
578                 if (trash && trash->total_msgs > 0)
579                         folder_item_remove_all_msg(trash);
580         }
581 }
582
583 /*!
584  *\brief        Send messages in queue
585  *
586  *\param        queue Queue folder to process
587  *\param        save_msgs Unused
588  *
589  *\return       Number of messages sent, negative if an error occurred
590  *              positive if no error occurred
591  */
592 gint procmsg_send_queue(FolderItem *queue, gboolean save_msgs)
593 {
594         gint ret = 1, count = 0;
595         GSList *list, *elem;
596
597         if (!queue)
598                 queue = folder_get_default_queue();
599         g_return_val_if_fail(queue != NULL, -1);
600
601         folder_item_scan(queue);
602         list = folder_item_get_msg_list(queue);
603
604         for (elem = list; elem != NULL; elem = elem->next) {
605                 gchar *file;
606                 MsgInfo *msginfo;
607                 
608                 msginfo = (MsgInfo *)(elem->data);
609                 if (!MSG_IS_LOCKED(msginfo->flags)) {
610                         file = folder_item_fetch_msg(queue, msginfo->msgnum);
611                         if (file) {
612                                 if (procmsg_send_message_queue(file) < 0) {
613                                         g_warning("Sending queued message %d failed.\n", 
614                                                   msginfo->msgnum);
615                                         ret = -1;
616                                 } else {
617                                         /* CLAWS: 
618                                          * We save in procmsg_send_message_queue because
619                                          * we need the destination folder from the queue
620                                          * header
621                                                         
622                                         if (save_msgs)
623                                                 procmsg_save_to_outbox
624                                                         (queue->folder->outbox,
625                                                          file, TRUE);
626                                          */
627                                         count++; 
628                                         folder_item_remove_msg(queue, msginfo->msgnum);
629                                 }
630                                 g_free(file);
631                         }
632                 }
633                 /* FIXME: supposedly if only one message is locked, and queue
634                  * is being flushed, the following free says something like 
635                  * "freeing msg ## in folder (nil)". */
636                 procmsg_msginfo_free(msginfo);
637         }
638
639         return ret * count;
640 }
641
642 gint procmsg_remove_special_headers(const gchar *in, const gchar *out)
643 {
644         FILE *fp, *outfp;
645         gchar buf[BUFFSIZE];
646         
647         if ((fp = fopen(in, "rb")) == NULL) {
648                 FILE_OP_ERROR(in, "fopen");
649                 return -1;
650         }
651         if ((outfp = fopen(out, "wb")) == NULL) {
652                 FILE_OP_ERROR(out, "fopen");
653                 fclose(fp);
654                 return -1;
655         }
656         while (fgets(buf, sizeof(buf), fp) != NULL)
657                 if (buf[0] == '\r' || buf[0] == '\n') break;
658         while (fgets(buf, sizeof(buf), fp) != NULL)
659                 fputs(buf, outfp);
660         fclose(outfp);
661         fclose(fp);
662         return 0;
663
664 }
665 gint procmsg_save_to_outbox(FolderItem *outbox, const gchar *file,
666                             gboolean is_queued)
667 {
668         gint num;
669         MsgInfo *msginfo;
670
671         debug_print("saving sent message...\n");
672
673         if (!outbox)
674                 outbox = folder_get_default_outbox();
675         g_return_val_if_fail(outbox != NULL, -1);
676
677         /* remove queueing headers */
678         if (is_queued) {
679                 gchar tmp[MAXPATHLEN + 1];
680
681                 g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.out.%08x",
682                            get_rc_dir(), G_DIR_SEPARATOR, (guint)random());
683                 
684                 if (procmsg_remove_special_headers(file, tmp) !=0)
685                         return -1;
686
687                 folder_item_scan(outbox);
688                 if ((num = folder_item_add_msg(outbox, tmp, TRUE)) < 0) {
689                         g_warning("can't save message\n");
690                         unlink(tmp);
691                         return -1;
692                 }
693         } else {
694                 folder_item_scan(outbox);
695                 if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
696                         g_warning("can't save message\n");
697                         return -1;
698                 }
699                 return -1;
700         }
701         msginfo = folder_item_get_msginfo(outbox, num);
702         if (msginfo != NULL) {
703             procmsg_msginfo_unset_flags(msginfo, ~0, 0);
704             procmsg_msginfo_free(msginfo);
705         }
706         folder_item_update(outbox, TRUE);
707
708         return 0;
709 }
710
711 void procmsg_print_message(MsgInfo *msginfo, const gchar *cmdline)
712 {
713         static const gchar *def_cmd = "lpr %s";
714         static guint id = 0;
715         gchar *prtmp;
716         FILE *tmpfp, *prfp;
717         gchar buf[1024];
718         gchar *p;
719
720         g_return_if_fail(msginfo);
721
722         if ((tmpfp = procmime_get_first_text_content(msginfo)) == NULL) {
723                 g_warning("Can't get text part\n");
724                 return;
725         }
726
727         prtmp = g_strdup_printf("%s%cprinttmp.%08x",
728                                 get_mime_tmp_dir(), G_DIR_SEPARATOR, id++);
729
730         if ((prfp = fopen(prtmp, "wb")) == NULL) {
731                 FILE_OP_ERROR(prtmp, "fopen");
732                 g_free(prtmp);
733                 fclose(tmpfp);
734                 return;
735         }
736
737         if (msginfo->date) fprintf(prfp, "Date: %s\n", msginfo->date);
738         if (msginfo->from) fprintf(prfp, "From: %s\n", msginfo->from);
739         if (msginfo->to)   fprintf(prfp, "To: %s\n", msginfo->to);
740         if (msginfo->cc)   fprintf(prfp, "Cc: %s\n", msginfo->cc);
741         if (msginfo->newsgroups)
742                 fprintf(prfp, "Newsgroups: %s\n", msginfo->newsgroups);
743         if (msginfo->subject) fprintf(prfp, "Subject: %s\n", msginfo->subject);
744         fputc('\n', prfp);
745
746         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
747                 fputs(buf, prfp);
748
749         fclose(prfp);
750         fclose(tmpfp);
751
752         if (cmdline && (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
753             !strchr(p + 2, '%'))
754                 g_snprintf(buf, sizeof(buf) - 1, cmdline, prtmp);
755         else {
756                 if (cmdline)
757                         g_warning("Print command line is invalid: `%s'\n",
758                                   cmdline);
759                 g_snprintf(buf, sizeof(buf) - 1, def_cmd, prtmp);
760         }
761
762         g_free(prtmp);
763
764         g_strchomp(buf);
765         if (buf[strlen(buf) - 1] != '&') strcat(buf, "&");
766         system(buf);
767 }
768
769 MsgInfo *procmsg_msginfo_new_ref(MsgInfo *msginfo)
770 {
771         msginfo->refcnt++;
772         
773         return msginfo;
774 }
775
776 MsgInfo *procmsg_msginfo_new(void)
777 {
778         MsgInfo *newmsginfo;
779
780         newmsginfo = g_new0(MsgInfo, 1);
781         newmsginfo->refcnt = 1;
782         
783         return newmsginfo;
784 }
785
786 MsgInfo *procmsg_msginfo_copy(MsgInfo *msginfo)
787 {
788         MsgInfo *newmsginfo;
789
790         if (msginfo == NULL) return NULL;
791
792         newmsginfo = g_new0(MsgInfo, 1);
793
794         newmsginfo->refcnt = 1;
795
796 #define MEMBCOPY(mmb)   newmsginfo->mmb = msginfo->mmb
797 #define MEMBDUP(mmb)    newmsginfo->mmb = msginfo->mmb ? \
798                         g_strdup(msginfo->mmb) : NULL
799
800         MEMBCOPY(msgnum);
801         MEMBCOPY(size);
802         MEMBCOPY(mtime);
803         MEMBCOPY(date_t);
804         MEMBCOPY(flags);
805
806         MEMBDUP(fromname);
807
808         MEMBDUP(date);
809         MEMBDUP(from);
810         MEMBDUP(to);
811         MEMBDUP(cc);
812         MEMBDUP(newsgroups);
813         MEMBDUP(subject);
814         MEMBDUP(msgid);
815         MEMBDUP(inreplyto);
816         MEMBDUP(xref);
817
818         MEMBCOPY(folder);
819         MEMBCOPY(to_folder);
820
821         MEMBDUP(xface);
822         MEMBDUP(dispositionnotificationto);
823         MEMBDUP(returnreceiptto);
824         MEMBDUP(references);
825
826         MEMBCOPY(score);
827         MEMBCOPY(threadscore);
828
829         return newmsginfo;
830 }
831
832 MsgInfo *procmsg_msginfo_get_full_info(MsgInfo *msginfo)
833 {
834         MsgInfo *full_msginfo;
835         gchar *file;
836
837         if (msginfo == NULL) return NULL;
838
839         file = procmsg_get_message_file(msginfo);
840         if (!file) {
841                 g_warning("procmsg_msginfo_get_full_info(): can't get message file.\n");
842                 return NULL;
843         }
844
845         full_msginfo = procheader_parse_file(file, msginfo->flags, TRUE, FALSE);
846         g_free(file);
847         if (!full_msginfo) return NULL;
848
849         full_msginfo->msgnum = msginfo->msgnum;
850         full_msginfo->size = msginfo->size;
851         full_msginfo->mtime = msginfo->mtime;
852         full_msginfo->folder = msginfo->folder;
853 #if USE_GPGME
854         full_msginfo->plaintext_file = g_strdup(msginfo->plaintext_file);
855         full_msginfo->decryption_failed = msginfo->decryption_failed;
856 #endif
857         procmsg_msginfo_set_to_folder(full_msginfo, msginfo->to_folder);
858
859         return full_msginfo;
860 }
861
862 void procmsg_msginfo_free(MsgInfo *msginfo)
863 {
864         if (msginfo == NULL) return;
865
866         msginfo->refcnt--;
867         if (msginfo->refcnt > 0)
868                 return;
869
870         debug_print("freeing msginfo %d in %s\n", msginfo->msgnum, msginfo->folder ? msginfo->folder->path : "(nil)");
871
872         if (msginfo->to_folder) {
873                 msginfo->to_folder->op_count--;
874                 folder_item_update(msginfo->to_folder, F_ITEM_UPDATE_MSGCNT);
875         }
876
877         g_free(msginfo->fromspace);
878         g_free(msginfo->references);
879         g_free(msginfo->returnreceiptto);
880         g_free(msginfo->dispositionnotificationto);
881         g_free(msginfo->xface);
882
883         g_free(msginfo->fromname);
884
885         g_free(msginfo->date);
886         g_free(msginfo->from);
887         g_free(msginfo->to);
888         g_free(msginfo->cc);
889         g_free(msginfo->newsgroups);
890         g_free(msginfo->subject);
891         g_free(msginfo->msgid);
892         g_free(msginfo->inreplyto);
893         g_free(msginfo->xref);
894
895         g_free(msginfo);
896 }
897
898 guint procmsg_msginfo_memusage(MsgInfo *msginfo)
899 {
900         guint memusage = 0;
901         
902         memusage += sizeof(MsgInfo);
903         if (msginfo->fromname)
904                 memusage += strlen(msginfo->fromname);
905         if (msginfo->date)
906                 memusage += strlen(msginfo->date);
907         if (msginfo->from)
908                 memusage += strlen(msginfo->from);
909         if (msginfo->to)
910                 memusage += strlen(msginfo->to);
911         if (msginfo->cc)
912                 memusage += strlen(msginfo->cc);
913         if (msginfo->newsgroups)
914                 memusage += strlen(msginfo->newsgroups);
915         if (msginfo->subject)
916                 memusage += strlen(msginfo->subject);
917         if (msginfo->msgid)
918                 memusage += strlen(msginfo->msgid);
919         if (msginfo->inreplyto)
920                 memusage += strlen(msginfo->inreplyto);
921         if (msginfo->xface)
922                 memusage += strlen(msginfo->xface);
923         if (msginfo->dispositionnotificationto)
924                 memusage += strlen(msginfo->dispositionnotificationto);
925         if (msginfo->returnreceiptto)
926                 memusage += strlen(msginfo->returnreceiptto);
927         if (msginfo->references)
928                 memusage += strlen(msginfo->references);
929         if (msginfo->fromspace)
930                 memusage += strlen(msginfo->fromspace);
931
932         return memusage;
933 }
934
935 gint procmsg_cmp_msgnum_for_sort(gconstpointer a, gconstpointer b)
936 {
937         const MsgInfo *msginfo1 = a;
938         const MsgInfo *msginfo2 = b;
939
940         if (!msginfo1)
941                 return -1;
942         if (!msginfo2)
943                 return -1;
944
945         return msginfo1->msgnum - msginfo2->msgnum;
946 }
947
948 enum
949 {
950         Q_SENDER           = 0,
951         Q_SMTPSERVER       = 1,
952         Q_RECIPIENTS       = 2,
953         Q_NEWSGROUPS       = 3,
954         Q_MAIL_ACCOUNT_ID  = 4,
955         Q_NEWS_ACCOUNT_ID  = 5,
956         Q_SAVE_COPY_FOLDER = 6,
957         Q_REPLY_MESSAGE_ID = 7,
958         Q_FWD_MESSAGE_ID   = 8
959 };
960
961 gint procmsg_send_message_queue(const gchar *file)
962 {
963         static HeaderEntry qentry[] = {{"S:",    NULL, FALSE},
964                                        {"SSV:",  NULL, FALSE},
965                                        {"R:",    NULL, FALSE},
966                                        {"NG:",   NULL, FALSE},
967                                        {"MAID:", NULL, FALSE},
968                                        {"NAID:", NULL, FALSE},
969                                        {"SCF:",  NULL, FALSE},
970                                        {"RMID:", NULL, FALSE},
971                                        {"FMID:", NULL, FALSE},
972                                        {NULL,    NULL, FALSE}};
973         FILE *fp;
974         gint filepos;
975         gint mailval = 0, newsval = 0;
976         gchar *from = NULL;
977         gchar *smtpserver = NULL;
978         GSList *to_list = NULL;
979         GSList *newsgroup_list = NULL;
980         gchar *savecopyfolder = NULL;
981         gchar *replymessageid = NULL;
982         gchar *fwdmessageid = NULL;
983         gchar buf[BUFFSIZE];
984         gint hnum;
985         PrefsAccount *mailac = NULL, *newsac = NULL;
986         int local = 0;
987
988         g_return_val_if_fail(file != NULL, -1);
989
990         if ((fp = fopen(file, "rb")) == NULL) {
991                 FILE_OP_ERROR(file, "fopen");
992                 return -1;
993         }
994
995         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, qentry))
996                != -1) {
997                 gchar *p = buf + strlen(qentry[hnum].name);
998
999                 switch (hnum) {
1000                 case Q_SENDER:
1001                         if (!from) from = g_strdup(p);
1002                         break;
1003                 case Q_SMTPSERVER:
1004                         if (!smtpserver) smtpserver = g_strdup(p);
1005                         break;
1006                 case Q_RECIPIENTS:
1007                         to_list = address_list_append(to_list, p);
1008                         break;
1009                 case Q_NEWSGROUPS:
1010                         newsgroup_list = newsgroup_list_append(newsgroup_list, p);
1011                         break;
1012                 case Q_MAIL_ACCOUNT_ID:
1013                         mailac = account_find_from_id(atoi(p));
1014                         break;
1015                 case Q_NEWS_ACCOUNT_ID:
1016                         newsac = account_find_from_id(atoi(p));
1017                         break;
1018                 case Q_SAVE_COPY_FOLDER:
1019                         if (!savecopyfolder) savecopyfolder = g_strdup(p);
1020                         break;
1021                 case Q_REPLY_MESSAGE_ID:
1022                         if (!replymessageid) replymessageid = g_strdup(p);
1023                         break;
1024                 case Q_FWD_MESSAGE_ID:
1025                         if (!fwdmessageid) fwdmessageid = g_strdup(p);
1026                         break;
1027                 }
1028         }
1029         filepos = ftell(fp);
1030
1031         if (to_list) {
1032                 debug_print("Sending message by mail\n");
1033                 if (!from) {
1034                         g_warning("Queued message header is broken.\n");
1035                         mailval = -1;
1036                 } else if (mailac && mailac->use_mail_command &&
1037                            mailac->mail_command && (* mailac->mail_command)) {
1038                         mailval = send_message_local(mailac->mail_command, fp);
1039                         local = 1;
1040                 } else if (prefs_common.use_extsend && prefs_common.extsend_cmd) {
1041                         mailval = send_message_local(prefs_common.extsend_cmd, fp);
1042                         local = 1;
1043                 } else {
1044                         if (!mailac) {
1045                                 mailac = account_find_from_smtp_server(from, smtpserver);
1046                                 if (!mailac) {
1047                                         g_warning("Account not found. "
1048                                                     "Using current account...\n");
1049                                         mailac = cur_account;
1050                                 }
1051                         }
1052
1053                         if (mailac)
1054                                 mailval = send_message_smtp(mailac, to_list, fp);
1055                         else {
1056                                 PrefsAccount tmp_ac;
1057
1058                                 g_warning("Account not found.\n");
1059
1060                                 memset(&tmp_ac, 0, sizeof(PrefsAccount));
1061                                 tmp_ac.address = from;
1062                                 tmp_ac.smtp_server = smtpserver;
1063                                 tmp_ac.smtpport = SMTP_PORT;
1064                                 mailval = send_message_smtp(&tmp_ac, to_list, fp);
1065                         }
1066                 }
1067         }
1068
1069         fseek(fp, filepos, SEEK_SET);
1070         if (newsgroup_list && (newsval == 0)) {
1071                 Folder *folder;
1072                 gchar *tmp = NULL;
1073                 FILE *tmpfp;
1074
1075                 /* write to temporary file */
1076                 tmp = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
1077                             G_DIR_SEPARATOR, (gint)file);
1078                 if ((tmpfp = fopen(tmp, "wb")) == NULL) {
1079                         FILE_OP_ERROR(tmp, "fopen");
1080                         newsval = -1;
1081                         alertpanel_error(_("Could not create temporary file for news sending."));
1082                 } else {
1083                         if (change_file_mode_rw(tmpfp, tmp) < 0) {
1084                                 FILE_OP_ERROR(tmp, "chmod");
1085                                 g_warning("can't change file mode\n");
1086                         }
1087
1088                         while ((newsval == 0) && fgets(buf, sizeof(buf), fp) != NULL) {
1089                                 if (fputs(buf, tmpfp) == EOF) {
1090                                         FILE_OP_ERROR(tmp, "fputs");
1091                                         newsval = -1;
1092                                         alertpanel_error(_("Error when writing temporary file for news sending."));
1093                                 }
1094                         }
1095                         fclose(tmpfp);
1096
1097                         if (newsval == 0) {
1098                                 debug_print("Sending message by news\n");
1099
1100                                 folder = FOLDER(newsac->folder);
1101
1102                                 newsval = news_post(folder, tmp);
1103                                 if (newsval < 0) {
1104                                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1105                                                  newsac->nntp_server);
1106                                 }
1107                         }
1108                         unlink(tmp);
1109                 }
1110                 g_free(tmp);
1111         }
1112
1113         slist_free_strings(to_list);
1114         g_slist_free(to_list);
1115         slist_free_strings(newsgroup_list);
1116         g_slist_free(newsgroup_list);
1117         g_free(from);
1118         g_free(smtpserver);
1119         fclose(fp);
1120
1121         /* save message to outbox */
1122         if (mailval == 0 && newsval == 0 && savecopyfolder) {
1123                 FolderItem *outbox;
1124
1125                 debug_print("saving sent message...\n");
1126
1127                 outbox = folder_find_item_from_identifier(savecopyfolder);
1128                 if (!outbox)
1129                         outbox = folder_get_default_outbox();
1130
1131                 procmsg_save_to_outbox(outbox, file, TRUE);
1132         }
1133
1134         if (replymessageid != NULL || fwdmessageid != NULL) {
1135                 gchar **tokens;
1136                 FolderItem *item;
1137                 
1138                 if (replymessageid != NULL)
1139                         tokens = g_strsplit(replymessageid, "\x7f", 0);
1140                 else
1141                         tokens = g_strsplit(fwdmessageid, "\x7f", 0);
1142                 item = folder_find_item_from_identifier(tokens[0]);
1143                 if (item != NULL) {
1144                         MsgInfo *msginfo;
1145                         
1146                         msginfo = folder_item_get_msginfo(item, atoi(tokens[1]));
1147                         
1148                         /*!< note that if the message has no msgid (maybe it was invalid), 
1149                         * we also refuse to do something with the reply to flag */
1150                         if ((msginfo != NULL) && 
1151                             (msginfo->msgid != NULL) &&
1152                             (strcmp(msginfo->msgid, tokens[2]) != 0)) {
1153                                 procmsg_msginfo_free(msginfo);
1154                                 msginfo = NULL;
1155                         }
1156                         
1157                         if (msginfo == NULL) {
1158                                 msginfo = folder_item_get_msginfo_by_msgid(item, tokens[2]);
1159                         }
1160                         
1161                         if (msginfo != NULL) {
1162                                 if (replymessageid != NULL) {
1163                                         procmsg_msginfo_unset_flags(msginfo, MSG_FORWARDED, 0);
1164                                         procmsg_msginfo_set_flags(msginfo, MSG_REPLIED, 0);
1165                                 } 
1166                                 else {
1167                                         procmsg_msginfo_unset_flags(msginfo, MSG_REPLIED, 0);
1168                                         procmsg_msginfo_set_flags(msginfo, MSG_FORWARDED, 0);
1169                                 }
1170                                 procmsg_msginfo_free(msginfo);
1171                         }
1172                 }
1173                 g_strfreev(tokens);
1174         }
1175
1176         g_free(savecopyfolder);
1177         g_free(replymessageid);
1178         g_free(fwdmessageid);
1179         
1180         return (newsval != 0 ? newsval : mailval);
1181 }
1182
1183 static void update_folder_msg_counts(FolderItem *item, MsgInfo *msginfo, MsgPermFlags old_flags)
1184 {
1185         MsgPermFlags new_flags = msginfo->flags.perm_flags;
1186
1187         /* NEW flag */
1188         if (!(old_flags & MSG_NEW) && (new_flags & MSG_NEW)) {
1189                 item->new_msgs++;
1190         }
1191
1192         if ((old_flags & MSG_NEW) && !(new_flags & MSG_NEW)) {
1193                 item->new_msgs--;
1194         }
1195
1196         /* UNREAD flag */
1197         if (!(old_flags & MSG_UNREAD) && (new_flags & MSG_UNREAD)) {
1198                 item->unread_msgs++;
1199                 if (procmsg_msg_has_marked_parent(msginfo))
1200                         item->unreadmarked_msgs++;
1201         }
1202
1203         if ((old_flags & MSG_UNREAD) && !(new_flags & MSG_UNREAD)) {
1204                 item->unread_msgs--;
1205                 if (procmsg_msg_has_marked_parent(msginfo))
1206                         item->unreadmarked_msgs--;
1207         }
1208         
1209         /* MARK flag */
1210         if (!(old_flags & MSG_MARKED) && (new_flags & MSG_MARKED)) {
1211                 procmsg_update_unread_children(msginfo, TRUE);
1212         }
1213
1214         if ((old_flags & MSG_MARKED) && !(new_flags & MSG_MARKED)) {
1215                 procmsg_update_unread_children(msginfo, FALSE);
1216         }
1217 }
1218
1219 void procmsg_msginfo_set_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1220 {
1221         FolderItem *item;
1222         MsgInfoUpdate msginfo_update;
1223         MsgPermFlags perm_flags_new, perm_flags_old;
1224
1225         g_return_if_fail(msginfo != NULL);
1226         item = msginfo->folder;
1227         g_return_if_fail(item != NULL);
1228         
1229         debug_print("Setting flags for message %d in folder %s\n", msginfo->msgnum, item->path);
1230
1231         /* Perm Flags handling */
1232         perm_flags_old = msginfo->flags.perm_flags;
1233         perm_flags_new = msginfo->flags.perm_flags | perm_flags;
1234         if ((perm_flags & MSG_IGNORE_THREAD) || (perm_flags_old & MSG_IGNORE_THREAD)) {
1235                 perm_flags_new &= ~(MSG_NEW | MSG_UNREAD);
1236         }
1237
1238         if (perm_flags_old != perm_flags_new) {
1239                 folder_item_change_msg_flags(msginfo->folder, msginfo, perm_flags_new);
1240
1241                 update_folder_msg_counts(item, msginfo, perm_flags_old);
1242
1243                 msginfo_update.msginfo = msginfo;
1244                 hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
1245                 folder_item_update(msginfo->folder, F_ITEM_UPDATE_MSGCNT);
1246         }
1247
1248         /* Tmp flags hanlding */
1249         msginfo->flags.tmp_flags |= tmp_flags;
1250 }
1251
1252 void procmsg_msginfo_unset_flags(MsgInfo *msginfo, MsgPermFlags perm_flags, MsgTmpFlags tmp_flags)
1253 {
1254         FolderItem *item;
1255         MsgInfoUpdate msginfo_update;
1256         MsgPermFlags perm_flags_new, perm_flags_old;
1257
1258         g_return_if_fail(msginfo != NULL);
1259         item = msginfo->folder;
1260         g_return_if_fail(item != NULL);
1261         
1262         debug_print("Unsetting flags for message %d in folder %s\n", msginfo->msgnum, item->path);
1263
1264         /* Perm Flags handling */
1265         perm_flags_old = msginfo->flags.perm_flags;
1266         perm_flags_new = msginfo->flags.perm_flags & ~perm_flags;
1267         
1268         if (perm_flags_old != perm_flags_new) {
1269                 folder_item_change_msg_flags(msginfo->folder, msginfo, perm_flags_new);
1270
1271                 update_folder_msg_counts(item, msginfo, perm_flags_old);
1272
1273                 msginfo_update.msginfo = msginfo;
1274                 hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
1275                 folder_item_update(msginfo->folder, F_ITEM_UPDATE_MSGCNT);
1276         }
1277
1278         /* Tmp flags hanlding */
1279         msginfo->flags.tmp_flags &= ~tmp_flags;
1280 }
1281
1282 /*!
1283  *\brief        check for flags (e.g. mark) in prior msgs of current thread
1284  *
1285  *\param        info Current message
1286  *\param        perm_flags Flags to be checked
1287  *\param        parentmsgs Hash of prior msgs to avoid loops
1288  *
1289  *\return       gboolean TRUE if perm_flags are found
1290  */
1291 gboolean procmsg_msg_has_flagged_parent_real(MsgInfo *info,
1292                 MsgPermFlags perm_flags, GHashTable *parentmsgs)
1293 {
1294         MsgInfo *tmp;
1295
1296         g_return_val_if_fail(info != NULL, FALSE);
1297
1298         if (info != NULL && info->folder != NULL && info->inreplyto != NULL) {
1299                 tmp = folder_item_get_msginfo_by_msgid(info->folder,
1300                                 info->inreplyto);
1301                 if (tmp && (tmp->flags.perm_flags & perm_flags)) {
1302                         procmsg_msginfo_free(tmp);
1303                         return TRUE;
1304                 } else if (tmp != NULL) {
1305                         gboolean result;
1306
1307                         if (g_hash_table_lookup(parentmsgs, info)) {
1308                                 debug_print("loop detected: %s%c%d\n",
1309                                         folder_item_get_path(info->folder),
1310                                         G_DIR_SEPARATOR, info->msgnum);
1311                                 result = FALSE;
1312                         } else {
1313                                 g_hash_table_insert(parentmsgs, info, "1");
1314                                 result = procmsg_msg_has_flagged_parent_real(
1315                                     tmp, perm_flags, parentmsgs);
1316                         }
1317                         procmsg_msginfo_free(tmp);
1318                         return result;
1319                 } else {
1320                         return FALSE;
1321                 }
1322         } else
1323                 return FALSE;
1324 }
1325
1326 /*!
1327  *\brief        Callback for cleaning up hash of parentmsgs
1328  */
1329 gboolean parentmsgs_hash_remove(gpointer key,
1330                             gpointer value,
1331                             gpointer user_data)
1332 {
1333         return TRUE;
1334 }
1335
1336 /*!
1337  *\brief        Set up list of parentmsgs
1338  *              See procmsg_msg_has_flagged_parent_real()
1339  */
1340 gboolean procmsg_msg_has_flagged_parent(MsgInfo *info, MsgPermFlags perm_flags)
1341 {
1342         gboolean result;
1343         GHashTable *parentmsgs = g_hash_table_new(NULL, NULL); 
1344
1345         result = procmsg_msg_has_flagged_parent_real(info, perm_flags, parentmsgs);
1346         g_hash_table_foreach_remove(parentmsgs, parentmsgs_hash_remove, NULL);
1347         g_hash_table_destroy(parentmsgs);
1348         return result;
1349 }
1350
1351 /*!
1352  *\brief        Check if msgs prior in thread are marked
1353  *              See procmsg_msg_has_flagged_parent_real()
1354  */
1355 gboolean procmsg_msg_has_marked_parent(MsgInfo *info)
1356 {
1357         return procmsg_msg_has_flagged_parent(info, MSG_MARKED);
1358 }
1359
1360
1361 GSList *procmsg_find_children_func(MsgInfo *info, 
1362                                    GSList *children, GSList *all)
1363 {
1364         GSList *cur;
1365
1366         g_return_val_if_fail(info!=NULL, children);
1367         if (info->msgid == NULL)
1368                 return children;
1369
1370         for (cur = all; cur != NULL; cur = g_slist_next(cur)) {
1371                 MsgInfo *tmp = (MsgInfo *)cur->data;
1372                 if (tmp->inreplyto && !strcmp(tmp->inreplyto, info->msgid)) {
1373                         /* Check if message is already in the list */
1374                         if ((children == NULL) || 
1375                             (g_slist_index(children, tmp) == -1)) {
1376                                 children = g_slist_prepend(children,
1377                                                 procmsg_msginfo_new_ref(tmp));
1378                                 children = procmsg_find_children_func(tmp, 
1379                                                         children, 
1380                                                         all);
1381                         }
1382                 }
1383         }
1384         return children;
1385 }
1386
1387 GSList *procmsg_find_children (MsgInfo *info)
1388 {
1389         GSList *children;
1390         GSList *all, *cur;
1391
1392         g_return_val_if_fail(info!=NULL, NULL);
1393         all = folder_item_get_msg_list(info->folder);
1394         children = procmsg_find_children_func(info, NULL, all);
1395         if (children != NULL) {
1396                 for (cur = all; cur != NULL; cur = g_slist_next(cur)) {
1397                         /* this will not free the used pointers
1398                            created with procmsg_msginfo_new_ref */
1399                         procmsg_msginfo_free((MsgInfo *)cur->data);
1400                 }
1401         }
1402         g_slist_free(all);
1403
1404         return children;
1405 }
1406
1407 void procmsg_update_unread_children(MsgInfo *info, gboolean newly_marked)
1408 {
1409         GSList *children = procmsg_find_children(info);
1410         GSList *cur;
1411         for (cur = children; cur != NULL; cur = g_slist_next(cur)) {
1412                 MsgInfo *tmp = (MsgInfo *)cur->data;
1413                 if(MSG_IS_UNREAD(tmp->flags) && !MSG_IS_IGNORE_THREAD(tmp->flags)) {
1414                         if(newly_marked) 
1415                                 info->folder->unreadmarked_msgs++;
1416                         else
1417                                 info->folder->unreadmarked_msgs--;
1418                         folder_item_update(info->folder, F_ITEM_UPDATE_MSGCNT);
1419                 }
1420                 procmsg_msginfo_free(tmp);
1421         }
1422         g_slist_free(children);
1423 }
1424
1425 /**
1426  * Set the destination folder for a copy or move operation
1427  *
1428  * \param msginfo The message which's destination folder is changed
1429  * \param to_folder The destination folder for the operation
1430  */
1431 void procmsg_msginfo_set_to_folder(MsgInfo *msginfo, FolderItem *to_folder)
1432 {
1433         if(msginfo->to_folder != NULL) {
1434                 msginfo->to_folder->op_count--;
1435                 folder_item_update(msginfo->to_folder, F_ITEM_UPDATE_MSGCNT);
1436         }
1437         msginfo->to_folder = to_folder;
1438         if(to_folder != NULL) {
1439                 to_folder->op_count++;
1440                 folder_item_update(msginfo->to_folder, F_ITEM_UPDATE_MSGCNT);
1441         }
1442 }
1443
1444 /**
1445  * Apply filtering actions to the msginfo
1446  *
1447  * \param msginfo The MsgInfo describing the message that should be filtered
1448  * \return TRUE if the message was moved and MsgInfo is now invalid,
1449  *         FALSE otherwise
1450  */
1451 gboolean procmsg_msginfo_filter(MsgInfo *msginfo)
1452 {
1453         MailFilteringData mail_filtering_data;
1454                         
1455         mail_filtering_data.msginfo = msginfo;                  
1456         if (hooks_invoke(MAIL_FILTERING_HOOKLIST, &mail_filtering_data))
1457                 return TRUE;
1458
1459         /* filter if enabled in prefs or move to inbox if not */
1460         if((global_processing != NULL) &&
1461            filter_message_by_msginfo(global_processing, msginfo))
1462                 return TRUE;
1463
1464         return FALSE;
1465 }