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