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