src/procmsg.[ch]
[claws.git] / src / procmsg.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #include "defs.h"
21
22 #include <glib.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25
26 #include "intl.h"
27 #include "main.h"
28 #include "utils.h"
29 #include "procmsg.h"
30 #include "procheader.h"
31 #include "send.h"
32 #include "procmime.h"
33 #include "statusbar.h"
34 #include "folder.h"
35 #include "prefs_common.h"
36 #include "account.h"
37 #if USE_GPGME
38 #  include "rfc2015.h"
39 #endif
40 #include "alertpanel.h"
41 #include "news.h"
42
43 typedef struct _FlagInfo        FlagInfo;
44
45 struct _FlagInfo
46 {
47         guint    msgnum;
48         MsgFlags flags;
49 };
50
51 static void mark_sum_func                       (gpointer        key,
52                                                  gpointer        value,
53                                                  gpointer        data);
54
55 static GHashTable *procmsg_read_mark_file       (const gchar    *folder);
56 static gint procmsg_cmp_msgnum                  (gconstpointer   a,
57                                                  gconstpointer   b);
58 static gint procmsg_cmp_flag_msgnum             (gconstpointer   a,
59                                                  gconstpointer   b);
60
61
62 GHashTable *procmsg_msg_hash_table_create(GSList *mlist)
63 {
64         GHashTable *msg_table;
65
66         if (mlist == NULL) return NULL;
67
68         msg_table = g_hash_table_new(NULL, g_direct_equal);
69         procmsg_msg_hash_table_append(msg_table, mlist);
70
71         return msg_table;
72 }
73
74 void procmsg_msg_hash_table_append(GHashTable *msg_table, GSList *mlist)
75 {
76         GSList *cur;
77         MsgInfo *msginfo;
78
79         if (msg_table == NULL || mlist == NULL) return;
80
81         for (cur = mlist; cur != NULL; cur = cur->next) {
82                 msginfo = (MsgInfo *)cur->data;
83
84                 g_hash_table_insert(msg_table,
85                                     GUINT_TO_POINTER(msginfo->msgnum),
86                                     msginfo);
87         }
88 }
89
90 GHashTable *procmsg_to_folder_hash_table_create(GSList *mlist)
91 {
92         GHashTable *msg_table;
93         GSList *cur;
94         MsgInfo *msginfo;
95
96         if (mlist == NULL) return NULL;
97
98         msg_table = g_hash_table_new(NULL, g_direct_equal);
99
100         for (cur = mlist; cur != NULL; cur = cur->next) {
101                 msginfo = (MsgInfo *)cur->data;
102                 g_hash_table_insert(msg_table, msginfo->to_folder, msginfo);
103         }
104
105         return msg_table;
106 }
107
108 static gint procmsg_read_cache_data_str(FILE *fp, gchar **str)
109 {
110         gchar buf[BUFFSIZE];
111         gint ret = 0;
112         size_t len;
113
114         if (fread(&len, sizeof(len), 1, fp) == 1) {
115                 if (len < 0)
116                         ret = -1;
117                 else {
118                         gchar *tmp = NULL;
119
120                         while (len > 0) {
121                                 size_t size = MIN(len, BUFFSIZE - 1);
122
123                                 if (fread(buf, size, 1, fp) != 1) {
124                                         ret = -1;
125                                         if (tmp) g_free(tmp);
126                                         *str = NULL;
127                                         break;
128                                 }
129
130                                 buf[size] = '\0';
131                                 if (tmp) {
132                                         *str = g_strconcat(tmp, buf, NULL);
133                                         g_free(tmp);
134                                         tmp = *str;
135                                 } else
136                                         tmp = *str = g_strdup(buf);
137
138                                 len -= size;
139                         }
140                 }
141         } else
142                 ret = -1;
143
144         if (ret < 0)
145                 g_warning(_("Cache data is corrupted\n"));
146
147         return ret;
148 }
149
150 #define READ_CACHE_DATA(data, fp) \
151 { \
152         if (procmsg_read_cache_data_str(fp, &data) < 0) { \
153                 procmsg_msginfo_free(msginfo); \
154                 break; \
155         } \
156 }
157
158 #define READ_CACHE_DATA_INT(n, fp) \
159 { \
160         if (fread(&n, sizeof(n), 1, fp) != 1) { \
161                 g_warning(_("Cache data is corrupted\n")); \
162                 procmsg_msginfo_free(msginfo); \
163                 break; \
164         } \
165 }
166
167 GSList *procmsg_read_cache(FolderItem *item, gboolean scan_file)
168 {
169         GSList *mlist = NULL;
170         GSList *last = NULL;
171         gchar *cache_file;
172         FILE *fp;
173         MsgInfo *msginfo;
174         MsgFlags default_flags;
175         gchar file_buf[BUFFSIZE];
176         gint ver;
177         guint num;
178         FolderType type;
179
180         g_return_val_if_fail(item != NULL, NULL);
181         g_return_val_if_fail(item->folder != NULL, NULL);
182         type = item->folder->type;
183
184         default_flags.perm_flags = MSG_NEW|MSG_UNREAD;
185         default_flags.tmp_flags = MSG_CACHED;
186         if (type == F_MH || type == F_IMAP) {
187                 if (item->stype == F_QUEUE) {
188                         MSG_SET_TMP_FLAGS(default_flags, MSG_QUEUED);
189                 } else if (item->stype == F_DRAFT) {
190                         MSG_SET_TMP_FLAGS(default_flags, MSG_DRAFT);
191                 }
192         }
193         if (type == F_IMAP) {
194                 MSG_SET_TMP_FLAGS(default_flags, MSG_IMAP);
195         } else if (type == F_NEWS) {
196                 MSG_SET_TMP_FLAGS(default_flags, MSG_NEWS);
197         }
198
199         if (type == F_MH) {
200                 gchar *path;
201
202                 path = folder_item_get_path(item);
203                 if (change_dir(path) < 0) {
204                         g_free(path);
205                         return NULL;
206                 }
207                 g_free(path);
208         }
209         cache_file = folder_item_get_cache_file(item);
210         if ((fp = fopen(cache_file, "rb")) == NULL) {
211                 debug_print(_("\tNo cache file\n"));
212                 g_free(cache_file);
213                 return NULL;
214         }
215         setvbuf(fp, file_buf, _IOFBF, sizeof(file_buf));
216         g_free(cache_file);
217
218         debug_print(_("\tReading summary cache...\n"));
219
220         /* compare cache version */
221         if (fread(&ver, sizeof(ver), 1, fp) != 1 ||
222             CACHE_VERSION != ver) {
223                 debug_print(_("Cache version is different. Discarding it.\n"));
224                 fclose(fp);
225                 return NULL;
226         }
227
228         while (fread(&num, sizeof(num), 1, fp) == 1) {
229                 msginfo = g_new0(MsgInfo, 1);
230                 msginfo->msgnum = num;
231                 READ_CACHE_DATA_INT(msginfo->size, fp);
232                 READ_CACHE_DATA_INT(msginfo->mtime, fp);
233                 READ_CACHE_DATA_INT(msginfo->date_t, fp);
234                 READ_CACHE_DATA_INT(msginfo->flags.tmp_flags, fp);
235
236                 READ_CACHE_DATA(msginfo->fromname, fp);
237
238                 READ_CACHE_DATA(msginfo->date, fp);
239                 READ_CACHE_DATA(msginfo->from, fp);
240                 READ_CACHE_DATA(msginfo->to, fp);
241                 READ_CACHE_DATA(msginfo->cc, fp);
242                 READ_CACHE_DATA(msginfo->newsgroups, fp);
243                 READ_CACHE_DATA(msginfo->subject, fp);
244                 READ_CACHE_DATA(msginfo->msgid, fp);
245                 READ_CACHE_DATA(msginfo->inreplyto, fp);
246                 READ_CACHE_DATA(msginfo->references, fp);
247                 READ_CACHE_DATA(msginfo->xref, fp);
248
249
250                 MSG_SET_PERM_FLAGS(msginfo->flags, default_flags.perm_flags);
251                 MSG_SET_TMP_FLAGS(msginfo->flags, default_flags.tmp_flags);
252
253                 /* if the message file doesn't exist or is changed,
254                    don't add the data */
255                 if (type == F_MH && scan_file &&
256                     folder_item_is_msg_changed(item, msginfo))
257                         procmsg_msginfo_free(msginfo);
258                 else {
259                         msginfo->folder = item;
260
261                         if (!mlist)
262                                 last = mlist = g_slist_append(NULL, msginfo);
263                         else {
264                                 last = g_slist_append(last, msginfo);
265                                 last = last->next;
266                         }
267                 }
268         }
269
270         fclose(fp);
271         debug_print(_("done.\n"));
272
273         return mlist;
274 }
275
276 #undef READ_CACHE_DATA
277 #undef READ_CACHE_DATA_INT
278
279 void procmsg_set_flags(GSList *mlist, FolderItem *item)
280 {
281         GSList *cur, *tmp;
282         gint newmsg = 0;
283         gint lastnum = 0;
284         gchar *markdir;
285         MsgInfo *msginfo;
286         GHashTable *mark_table;
287         MsgFlags *flags;
288
289         if (!mlist) return;
290         g_return_if_fail(item != NULL);
291         g_return_if_fail(item->folder != NULL);
292
293         debug_print(_("\tMarking the messages...\n"));
294
295         markdir = folder_item_get_path(item);
296         if (!is_dir_exist(markdir))
297                 make_dir_hier(markdir);
298
299         mark_table = procmsg_read_mark_file(markdir);
300         g_free(markdir);
301
302         if (!mark_table) return;
303
304         for (cur = mlist; cur != NULL; cur = cur->next) {
305                 msginfo = (MsgInfo *)cur->data;
306
307                 if (lastnum < msginfo->msgnum)
308                         lastnum = msginfo->msgnum;
309
310                 flags = g_hash_table_lookup
311                         (mark_table, GUINT_TO_POINTER(msginfo->msgnum));
312
313                 if (flags != NULL) {
314                         /* add the permanent flags only */
315                         msginfo->flags.perm_flags = flags->perm_flags;
316                         if (item->folder->type == F_IMAP) {
317                                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_IMAP);
318                         } else if (item->folder->type == F_NEWS) {
319                                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_NEWS);
320                         }
321                 } else {
322                         /* not found (new message) */
323                         if (newmsg == 0) {
324                                 for (tmp = mlist; tmp != cur; tmp = tmp->next)
325                                         MSG_UNSET_PERM_FLAGS
326                                                 (((MsgInfo *)tmp->data)->flags,
327                                                  MSG_NEW);
328                         }
329                         newmsg++;
330                 }
331         }
332
333         item->last_num = lastnum;
334
335         debug_print(_("done.\n"));
336         if (newmsg)
337                 debug_print(_("\t%d new message(s)\n"), newmsg);
338
339         hash_free_value_mem(mark_table);
340         g_hash_table_destroy(mark_table);
341 }
342
343 gint procmsg_get_last_num_in_cache(GSList *mlist)
344 {
345         GSList *cur;
346         MsgInfo *msginfo;
347         gint last = 0;
348
349         if (mlist == NULL) return 0;
350
351         for (cur = mlist; cur != NULL; cur = cur->next) {
352                 msginfo = (MsgInfo *)cur->data;
353                 if (msginfo && msginfo->msgnum > last)
354                         last = msginfo->msgnum;
355         }
356
357         return last;
358 }
359
360 void procmsg_msg_list_free(GSList *mlist)
361 {
362         GSList *cur;
363         MsgInfo *msginfo;
364
365         for (cur = mlist; cur != NULL; cur = cur->next) {
366                 msginfo = (MsgInfo *)cur->data;
367                 procmsg_msginfo_free(msginfo);
368         }
369         g_slist_free(mlist);
370 }
371
372 void procmsg_write_cache(MsgInfo *msginfo, FILE *fp)
373 {
374         MsgTmpFlags flags = msginfo->flags.tmp_flags & MSG_CACHED_FLAG_MASK;
375
376         WRITE_CACHE_DATA_INT(msginfo->msgnum, fp);
377         WRITE_CACHE_DATA_INT(msginfo->size, fp);
378         WRITE_CACHE_DATA_INT(msginfo->mtime, fp);
379         WRITE_CACHE_DATA_INT(msginfo->date_t, fp);
380         WRITE_CACHE_DATA_INT(flags, fp);
381
382         WRITE_CACHE_DATA(msginfo->fromname, fp);
383
384         WRITE_CACHE_DATA(msginfo->date, fp);
385         WRITE_CACHE_DATA(msginfo->from, fp);
386         WRITE_CACHE_DATA(msginfo->to, fp);
387         WRITE_CACHE_DATA(msginfo->cc, fp);
388         WRITE_CACHE_DATA(msginfo->newsgroups, fp);
389         WRITE_CACHE_DATA(msginfo->subject, fp);
390         WRITE_CACHE_DATA(msginfo->msgid, fp);
391         WRITE_CACHE_DATA(msginfo->inreplyto, fp);
392         WRITE_CACHE_DATA(msginfo->references, fp);
393         WRITE_CACHE_DATA(msginfo->xref, fp);
394
395 }
396
397 void procmsg_write_flags(MsgInfo *msginfo, FILE *fp)
398 {
399         MsgPermFlags flags = msginfo->flags.perm_flags;
400
401         WRITE_CACHE_DATA_INT(msginfo->msgnum, fp);
402         WRITE_CACHE_DATA_INT(flags, fp);
403 }
404
405 void procmsg_flush_mark_queue(FolderItem *item, FILE *fp)
406 {
407         MsgInfo *flaginfo;
408
409         g_return_if_fail(item != NULL);
410         g_return_if_fail(fp != NULL);
411
412         while (item->mark_queue != NULL) {
413                 flaginfo = (MsgInfo *)item->mark_queue->data;
414                 procmsg_write_flags(flaginfo, fp);
415                 procmsg_msginfo_free(flaginfo);
416                 item->mark_queue = g_slist_remove(item->mark_queue, flaginfo);
417         }
418 }
419
420 void procmsg_add_flags(FolderItem *item, gint num, MsgFlags flags)
421 {
422         FILE *fp;
423         gchar *path;
424         MsgInfo msginfo;
425
426         g_return_if_fail(item != NULL);
427
428         if (item->opened) {
429                 MsgInfo *queue_msginfo;
430
431                 queue_msginfo = g_new0(MsgInfo, 1);
432                 queue_msginfo->msgnum = num;
433                 queue_msginfo->flags = flags;
434                 item->mark_queue = g_slist_append
435                         (item->mark_queue, queue_msginfo);
436                 return;
437         }
438
439         path = folder_item_get_path(item);
440         g_return_if_fail(path != NULL);
441
442         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL) {
443                 g_warning(_("can't open mark file\n"));
444                 g_free(path);
445                 return;
446         }
447         g_free(path);
448
449         msginfo.msgnum = num;
450         msginfo.flags = flags;
451
452         procmsg_write_flags(&msginfo, fp);
453         fclose(fp);
454 }
455
456 struct MarkSum {
457         gint *new;
458         gint *unread;
459         gint *total;
460         gint *min;
461         gint *max;
462         gint first;
463 };
464
465 static void mark_sum_func(gpointer key, gpointer value, gpointer data)
466 {
467         MsgFlags *flags = value;
468         gint num = GPOINTER_TO_INT(key);
469         struct MarkSum *marksum = data;
470
471         if (marksum->first <= num) {
472                 if (MSG_IS_NEW(*flags) && !MSG_IS_IGNORE_THREAD(*flags)) (*marksum->new)++;
473                 if (MSG_IS_UNREAD(*flags) && !MSG_IS_IGNORE_THREAD(*flags)) (*marksum->unread)++;
474                 if (num > *marksum->max) *marksum->max = num;
475                 if (num < *marksum->min || *marksum->min == 0) *marksum->min = num;
476                 (*marksum->total)++;
477         }
478
479         g_free(flags);
480 }
481
482 void procmsg_get_mark_sum(const gchar *folder,
483                           gint *new, gint *unread, gint *total,
484                           gint *min, gint *max,
485                           gint first)
486 {
487         GHashTable *mark_table;
488         struct MarkSum marksum;
489
490         *new = *unread = *total = *min = *max = 0;
491         marksum.new    = new;
492         marksum.unread = unread;
493         marksum.total  = total;
494         marksum.min    = min;
495         marksum.max    = max;
496         marksum.first  = first;
497
498         mark_table = procmsg_read_mark_file(folder);
499
500         if (mark_table) {
501                 g_hash_table_foreach(mark_table, mark_sum_func, &marksum);
502                 g_hash_table_destroy(mark_table);
503         }
504         debug_print("mark->new = %d, mark->unread = %d, mark->total = %d\n",
505                     *(marksum.new), *(marksum.unread), *(marksum.total));
506 }
507
508 static GHashTable *procmsg_read_mark_file(const gchar *folder)
509 {
510         FILE *fp;
511         GHashTable *mark_table = NULL;
512         gint num;
513         MsgFlags *flags;
514         MsgPermFlags perm_flags;
515
516         if ((fp = procmsg_open_mark_file(folder, FALSE)) == NULL)
517                 return NULL;
518
519         mark_table = g_hash_table_new(NULL, g_direct_equal);
520
521         while (fread(&num, sizeof(num), 1, fp) == 1) {
522                 if (fread(&perm_flags, sizeof(perm_flags), 1, fp) != 1) break;
523
524                 flags = g_new0(MsgFlags, 1);
525                 flags->perm_flags = perm_flags;
526
527                 g_hash_table_insert(mark_table, GUINT_TO_POINTER(num), flags);
528         }
529
530         fclose(fp);
531         return mark_table;
532 }
533
534 FILE *procmsg_open_mark_file(const gchar *folder, gboolean append)
535 {
536         gchar *markfile;
537         FILE *fp;
538         gint ver;
539
540         markfile = g_strconcat(folder, G_DIR_SEPARATOR_S, MARK_FILE, NULL);
541
542         if ((fp = fopen(markfile, "rb")) == NULL)
543                 debug_print(_("Mark file not found.\n"));
544         else if (fread(&ver, sizeof(ver), 1, fp) != 1 || MARK_VERSION != ver) {
545                 debug_print(_("Mark version is different (%d != %d). "
546                               "Discarding it.\n"), ver, MARK_VERSION);
547                 fclose(fp);
548                 fp = NULL;
549         }
550
551         /* read mode */
552         if (append == FALSE) {
553                 g_free(markfile);
554                 return fp;
555         }
556
557         if (fp) {
558                 /* reopen with append mode */
559                 fclose(fp);
560                 if ((fp = fopen(markfile, "ab")) == NULL)
561                         g_warning(_("Can't open mark file with append mode.\n"));
562         } else {
563                 /* open with overwrite mode if mark file doesn't exist or
564                    version is different */
565                 if ((fp = fopen(markfile, "wb")) == NULL)
566                         g_warning(_("Can't open mark file with write mode.\n"));
567                 else {
568                         ver = MARK_VERSION;
569                         WRITE_CACHE_DATA_INT(ver, fp);
570                 }
571         }
572
573         g_free(markfile);
574         return fp;
575 }
576
577 /* return the reversed thread tree */
578 GNode *procmsg_get_thread_tree(GSList *mlist)
579 {
580         GNode *root, *parent, *node, *next;
581         GHashTable *msgid_table;
582         GHashTable *subject_table;
583         MsgInfo *msginfo;
584         const gchar *msgid;
585         const gchar *subject;
586
587         root = g_node_new(NULL);
588         msgid_table = g_hash_table_new(g_str_hash, g_str_equal);
589         subject_table = g_hash_table_new(g_str_hash, g_str_equal);
590
591         for (; mlist != NULL; mlist = mlist->next) {
592                 msginfo = (MsgInfo *)mlist->data;
593                 parent = root;
594
595                 if (msginfo->inreplyto) {
596                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
597                         if (parent == NULL) {
598                                 parent = root;
599                         } else {
600                                 if(MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags)) {
601                                         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_IGNORE_THREAD);
602                                 }
603                         }
604                 }
605                 node = g_node_insert_data_before
606                         (parent, parent == root ? parent->children : NULL,
607                          msginfo);
608                 if ((msgid = msginfo->msgid) &&
609                     g_hash_table_lookup(msgid_table, msgid) == NULL)
610                         g_hash_table_insert(msgid_table, (gchar *)msgid, node);
611
612                 subject = msginfo->subject;
613                 if (subject_table_lookup(subject_table,
614                                          (gchar *) subject) == NULL)
615                         subject_table_insert(subject_table, (gchar *)subject,
616                                              node);
617         }
618
619         /* complete the unfinished threads */
620         for (node = root->children; node != NULL; ) {
621                 next = node->next;
622                 msginfo = (MsgInfo *)node->data;
623                 parent = NULL;
624                 if (msginfo->inreplyto) 
625                         parent = g_hash_table_lookup(msgid_table, msginfo->inreplyto);
626                 if (parent && parent != node) {
627                         g_node_unlink(node);
628                         g_node_insert_before
629                                 (parent, parent->children, node);
630                         /* CLAWS: ignore thread */
631                         if(MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags)) {
632                                 MSG_SET_PERM_FLAGS(msginfo->flags, MSG_IGNORE_THREAD);
633                         }
634                 }
635                 node = next;
636         }
637
638         /* CLAWS: now see if the first level (below root) still has some nodes that can be
639          * threaded by subject line. we need to handle this in a special way to prevent
640          * circular reference from a node that has already been threaded by IN-REPLY-TO
641          * but is also in the subject line hash table */
642         for (node = root->children; node != NULL; ) {
643                 next = node->next;
644                 msginfo = (MsgInfo *) node->data;
645                 parent = NULL;
646                 if (subject_is_reply(msginfo->subject)) {
647                         parent = subject_table_lookup(subject_table,
648                                                       msginfo->subject);
649                         /* the node may already be threaded by IN-REPLY-TO,
650                            so go up in the tree to find the parent node */
651                         if (parent != NULL) {
652                                 if (g_node_is_ancestor(node, parent))
653                                         parent = NULL;
654                                 if (parent == node)
655                                         parent = NULL;
656                         }
657
658                         if (parent) {
659                                 g_node_unlink(node);
660                                 g_node_append(parent, node);
661                                 /* CLAWS: ignore thread */
662                                 if(MSG_IS_IGNORE_THREAD(((MsgInfo *)parent->data)->flags)) {
663                                         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_IGNORE_THREAD);
664                                 }
665                         }
666                 }                                       
667                 node = next;
668         }               
669                 
670         g_hash_table_destroy(subject_table);
671         g_hash_table_destroy(msgid_table);
672
673         return root;
674 }
675
676 void procmsg_move_messages(GSList *mlist)
677 {
678         GSList *cur, *movelist = NULL;
679         MsgInfo *msginfo;
680         FolderItem *dest = NULL;
681         GHashTable *hash;
682
683         if (!mlist) return;
684
685         hash = procmsg_to_folder_hash_table_create(mlist);
686         folder_item_scan_foreach(hash);
687         g_hash_table_destroy(hash);
688
689         for (cur = mlist; cur != NULL; cur = cur->next) {
690                 msginfo = (MsgInfo *)cur->data;
691                 if (!dest) {
692                         dest = msginfo->to_folder;
693                         movelist = g_slist_append(movelist, msginfo);
694                 } else if (dest == msginfo->to_folder) {
695                         movelist = g_slist_append(movelist, msginfo);
696                 } else {
697                         folder_item_move_msgs_with_dest(dest, movelist);
698                         g_slist_free(movelist);
699                         movelist = NULL;
700                         dest = msginfo->to_folder;
701                         movelist = g_slist_append(movelist, msginfo);
702                 }
703         }
704
705         if (movelist) {
706                 folder_item_move_msgs_with_dest(dest, movelist);
707                 g_slist_free(movelist);
708         }
709 }
710
711 void procmsg_copy_messages(GSList *mlist)
712 {
713         GSList *cur, *copylist = NULL;
714         MsgInfo *msginfo;
715         FolderItem *dest = NULL;
716         GHashTable *hash;
717
718         if (!mlist) return;
719
720         hash = procmsg_to_folder_hash_table_create(mlist);
721         folder_item_scan_foreach(hash);
722         g_hash_table_destroy(hash);
723
724         for (cur = mlist; cur != NULL; cur = cur->next) {
725                 msginfo = (MsgInfo *)cur->data;
726                 if (!dest) {
727                         dest = msginfo->to_folder;
728                         copylist = g_slist_append(copylist, msginfo);
729                 } else if (dest == msginfo->to_folder) {
730                         copylist = g_slist_append(copylist, msginfo);
731                 } else {
732                         folder_item_copy_msgs_with_dest(dest, copylist);
733                         g_slist_free(copylist);
734                         copylist = NULL;
735                         dest = msginfo->to_folder;
736                         copylist = g_slist_append(copylist, msginfo);
737                 }
738         }
739
740         if (copylist) {
741                 folder_item_copy_msgs_with_dest(dest, copylist);
742                 g_slist_free(copylist);
743         }
744 }
745
746 gchar *procmsg_get_message_file_path(MsgInfo *msginfo)
747 {
748         gchar *path, *file;
749
750         g_return_val_if_fail(msginfo != NULL, NULL);
751
752         if (msginfo->plaintext_file)
753                 file = g_strdup(msginfo->plaintext_file);
754         else {
755                 path = folder_item_get_path(msginfo->folder);
756                 file = g_strconcat(path, G_DIR_SEPARATOR_S,
757                                    itos(msginfo->msgnum), NULL);
758                 g_free(path);
759         }
760
761         return file;
762 }
763
764 gchar *procmsg_get_message_file(MsgInfo *msginfo)
765 {
766         gchar *filename = NULL;
767
768         g_return_val_if_fail(msginfo != NULL, NULL);
769
770         filename = folder_item_fetch_msg(msginfo->folder, msginfo->msgnum);
771         if (!filename)
772                 g_warning(_("can't fetch message %d\n"), msginfo->msgnum);
773
774         return filename;
775 }
776
777 FILE *procmsg_open_message(MsgInfo *msginfo)
778 {
779         FILE *fp;
780         gchar *file;
781
782         g_return_val_if_fail(msginfo != NULL, NULL);
783
784         file = procmsg_get_message_file_path(msginfo);
785         g_return_val_if_fail(file != NULL, NULL);
786
787         if (!is_file_exist(file)) {
788                 g_free(file);
789                 file = procmsg_get_message_file(msginfo);
790                 g_return_val_if_fail(file != NULL, NULL);
791         }
792
793         if ((fp = fopen(file, "rb")) == NULL) {
794                 FILE_OP_ERROR(file, "fopen");
795                 g_free(file);
796                 return NULL;
797         }
798
799         g_free(file);
800
801         if (MSG_IS_QUEUED(msginfo->flags)) {
802                 gchar buf[BUFFSIZE];
803
804                 while (fgets(buf, sizeof(buf), fp) != NULL)
805                         if (buf[0] == '\r' || buf[0] == '\n') break;
806         }
807
808         return fp;
809 }
810
811 #if USE_GPGME
812 FILE *procmsg_open_message_decrypted(MsgInfo *msginfo, MimeInfo **mimeinfo)
813 {
814         FILE *fp;
815         MimeInfo *mimeinfo_;
816
817         g_return_val_if_fail(msginfo != NULL, NULL);
818
819         if (mimeinfo) *mimeinfo = NULL;
820
821         if ((fp = procmsg_open_message(msginfo)) == NULL) return NULL;
822
823         mimeinfo_ = procmime_scan_mime_header(fp);
824         if (!mimeinfo_) {
825                 fclose(fp);
826                 return NULL;
827         }
828
829         if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
830             rfc2015_is_encrypted(mimeinfo_)) {
831                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
832         }
833
834         if (MSG_IS_ENCRYPTED(msginfo->flags) &&
835             !msginfo->plaintext_file &&
836             !msginfo->decryption_failed) {
837                 rfc2015_decrypt_message(msginfo, mimeinfo_, fp);
838                 if (msginfo->plaintext_file &&
839                     !msginfo->decryption_failed) {
840                         fclose(fp);
841                         procmime_mimeinfo_free_all(mimeinfo_);
842                         if ((fp = procmsg_open_message(msginfo)) == NULL)
843                                 return NULL;
844                         mimeinfo_ = procmime_scan_mime_header(fp);
845                         if (!mimeinfo_) {
846                                 fclose(fp);
847                                 return NULL;
848                         }
849                 }
850         }
851
852         if (mimeinfo) *mimeinfo = mimeinfo_;
853         return fp;
854 }
855 #endif
856
857 gboolean procmsg_msg_exist(MsgInfo *msginfo)
858 {
859         gchar *path;
860         gboolean ret;
861
862         if (!msginfo) return FALSE;
863
864         path = folder_item_get_path(msginfo->folder);
865         change_dir(path);
866         ret = !folder_item_is_msg_changed(msginfo->folder, msginfo);
867         g_free(path);
868
869         return ret;
870 }
871
872 void procmsg_empty_trash(void)
873 {
874         FolderItem *trash;
875         GList *cur;
876
877         for (cur = folder_get_list(); cur != NULL; cur = cur->next) {
878                 trash = FOLDER(cur->data)->trash;
879                 if (trash && trash->total > 0)
880                         folder_item_remove_all_msg(trash);
881         }
882 }
883
884 gint procmsg_send_queue(FolderItem *queue, gboolean save_msgs)
885 {
886         gint i;
887         gint ret = 0;
888
889         if (!queue)
890                 queue = folder_get_default_queue();
891         g_return_val_if_fail(queue != NULL, -1);
892
893         folder_item_scan(queue);
894         if (queue->last_num < 0) return -1;
895         else if (queue->last_num == 0) return 0;
896
897         for (i = 1; i <= queue->last_num; i++) {
898                 gchar *file;
899
900                 file = folder_item_fetch_msg(queue, i);
901                 if (file) {
902                         if (procmsg_send_message_queue(file) < 0) {
903                                 g_warning(_("Sending queued message %d failed.\n"), i);
904                                 ret = -1;
905                         } else {
906                         /* CLAWS: 
907                          * We save in procmsg_send_message_queue because
908                          * we need the destination folder from the queue
909                          * header
910                                                 
911                                 if (save_msgs)
912                                         procmsg_save_to_outbox
913                                                 (queue->folder->outbox,
914                                                  file, TRUE);
915 */
916                                 folder_item_remove_msg(queue, i);
917                         }
918                         g_free(file);
919                 }
920         }
921
922         return ret;
923 }
924
925 gint procmsg_save_to_outbox(FolderItem *outbox, const gchar *file,
926                             gboolean is_queued)
927 {
928         gint num;
929         FILE *fp;
930         MsgFlags flag = {0, 0};
931
932         debug_print(_("saving sent message...\n"));
933
934         if (!outbox)
935                 outbox = folder_get_default_outbox();
936         g_return_val_if_fail(outbox != NULL, -1);
937
938         /* remove queueing headers */
939         if (is_queued) {
940                 gchar tmp[MAXPATHLEN + 1];
941                 gchar buf[BUFFSIZE];
942                 FILE *outfp;
943
944                 g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.out.%08x",
945                            get_rc_dir(), G_DIR_SEPARATOR, (guint)random());
946                 if ((fp = fopen(file, "rb")) == NULL) {
947                         FILE_OP_ERROR(file, "fopen");
948                         return -1;
949                 }
950                 if ((outfp = fopen(tmp, "wb")) == NULL) {
951                         FILE_OP_ERROR(tmp, "fopen");
952                         fclose(fp);
953                         return -1;
954                 }
955                 while (fgets(buf, sizeof(buf), fp) != NULL)
956                         if (buf[0] == '\r' || buf[0] == '\n') break;
957                 while (fgets(buf, sizeof(buf), fp) != NULL)
958                         fputs(buf, outfp);
959                 fclose(outfp);
960                 fclose(fp);
961                 Xstrdup_a(file, tmp, return -1);
962         }
963
964         folder_item_scan(outbox);
965         if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
966                 g_warning(_("can't save message\n"));
967                 return -1;
968         }
969
970         if(is_queued) {
971                 unlink(file);
972         }
973
974         procmsg_add_flags(outbox, num, flag);
975
976         return 0;
977 }
978
979 void procmsg_print_message(MsgInfo *msginfo, const gchar *cmdline)
980 {
981         static const gchar *def_cmd = "lpr %s";
982         static guint id = 0;
983         gchar *prtmp;
984         FILE *tmpfp, *prfp;
985         gchar buf[1024];
986         gchar *p;
987
988         g_return_if_fail(msginfo);
989
990         if ((tmpfp = procmime_get_first_text_content(msginfo)) == NULL) {
991                 g_warning(_("Can't get text part\n"));
992                 return;
993         }
994
995         prtmp = g_strdup_printf("%s%cprinttmp.%08x",
996                                 get_mime_tmp_dir(), G_DIR_SEPARATOR, id++);
997
998         if ((prfp = fopen(prtmp, "wb")) == NULL) {
999                 FILE_OP_ERROR(prtmp, "fopen");
1000                 g_free(prtmp);
1001                 fclose(tmpfp);
1002                 return;
1003         }
1004
1005         if (msginfo->date) fprintf(prfp, "Date: %s\n", msginfo->date);
1006         if (msginfo->from) fprintf(prfp, "From: %s\n", msginfo->from);
1007         if (msginfo->to)   fprintf(prfp, "To: %s\n", msginfo->to);
1008         if (msginfo->cc)   fprintf(prfp, "Cc: %s\n", msginfo->cc);
1009         if (msginfo->newsgroups)
1010                 fprintf(prfp, "Newsgroups: %s\n", msginfo->newsgroups);
1011         if (msginfo->subject) fprintf(prfp, "Subject: %s\n", msginfo->subject);
1012         fputc('\n', prfp);
1013
1014         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
1015                 fputs(buf, prfp);
1016
1017         fclose(prfp);
1018         fclose(tmpfp);
1019
1020         if (cmdline && (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
1021             !strchr(p + 2, '%'))
1022                 g_snprintf(buf, sizeof(buf) - 1, cmdline, prtmp);
1023         else {
1024                 if (cmdline)
1025                         g_warning(_("Print command line is invalid: `%s'\n"),
1026                                   cmdline);
1027                 g_snprintf(buf, sizeof(buf) - 1, def_cmd, prtmp);
1028         }
1029
1030         g_free(prtmp);
1031
1032         g_strchomp(buf);
1033         if (buf[strlen(buf) - 1] != '&') strcat(buf, "&");
1034         system(buf);
1035 }
1036
1037 MsgInfo *procmsg_msginfo_copy(MsgInfo *msginfo)
1038 {
1039         MsgInfo *newmsginfo;
1040
1041         if (msginfo == NULL) return NULL;
1042
1043         newmsginfo = g_new0(MsgInfo, 1);
1044
1045 #define MEMBCOPY(mmb)   newmsginfo->mmb = msginfo->mmb
1046 #define MEMBDUP(mmb)    newmsginfo->mmb = msginfo->mmb ? \
1047                         g_strdup(msginfo->mmb) : NULL
1048
1049         MEMBCOPY(msgnum);
1050         MEMBCOPY(size);
1051         MEMBCOPY(mtime);
1052         MEMBCOPY(date_t);
1053         MEMBCOPY(flags);
1054
1055         MEMBDUP(fromname);
1056
1057         MEMBDUP(date);
1058         MEMBDUP(from);
1059         MEMBDUP(to);
1060         MEMBDUP(cc);
1061         MEMBDUP(newsgroups);
1062         MEMBDUP(subject);
1063         MEMBDUP(msgid);
1064         MEMBDUP(inreplyto);
1065         MEMBDUP(xref);
1066
1067         MEMBCOPY(folder);
1068         MEMBCOPY(to_folder);
1069
1070         MEMBDUP(xface);
1071         MEMBDUP(dispositionnotificationto);
1072         MEMBDUP(returnreceiptto);
1073         MEMBDUP(references);
1074
1075         MEMBCOPY(score);
1076         MEMBCOPY(threadscore);
1077
1078         return newmsginfo;
1079 }
1080
1081 void procmsg_msginfo_free(MsgInfo *msginfo)
1082 {
1083         if (msginfo == NULL) return;
1084
1085         g_free(msginfo->fromspace);
1086         g_free(msginfo->references);
1087         g_free(msginfo->returnreceiptto);
1088         g_free(msginfo->dispositionnotificationto);
1089         g_free(msginfo->xface);
1090
1091         g_free(msginfo->fromname);
1092
1093         g_free(msginfo->date);
1094         g_free(msginfo->from);
1095         g_free(msginfo->to);
1096         g_free(msginfo->cc);
1097         g_free(msginfo->newsgroups);
1098         g_free(msginfo->subject);
1099         g_free(msginfo->msgid);
1100         g_free(msginfo->inreplyto);
1101         g_free(msginfo->xref);
1102
1103         g_free(msginfo);
1104 }
1105
1106 static gint procmsg_cmp_msgnum(gconstpointer a, gconstpointer b)
1107 {
1108         const MsgInfo *msginfo = a;
1109         const guint msgnum = GPOINTER_TO_UINT(b);
1110
1111         if (!msginfo)
1112                 return -1;
1113
1114         return msginfo->msgnum - msgnum;
1115 }
1116
1117 gint procmsg_cmp_msgnum_for_sort(gconstpointer a, gconstpointer b)
1118 {
1119         const MsgInfo *msginfo1 = a;
1120         const MsgInfo *msginfo2 = b;
1121
1122         if (!msginfo1)
1123                 return -1;
1124         if (!msginfo2)
1125                 return -1;
1126
1127         return msginfo1->msgnum - msginfo2->msgnum;
1128 }
1129
1130 static gint procmsg_cmp_flag_msgnum(gconstpointer a, gconstpointer b)
1131 {
1132         const FlagInfo *finfo = a;
1133         const guint msgnum = GPOINTER_TO_UINT(b);
1134
1135         if (!finfo)
1136                 return -1;
1137
1138         return finfo->msgnum - msgnum;
1139 }
1140
1141 enum
1142 {
1143         Q_SENDER           = 0,
1144         Q_SMTPSERVER       = 1,
1145         Q_RECIPIENTS       = 2,
1146         Q_NEWSGROUPS       = 3,
1147         Q_MAIL_ACCOUNT_ID  = 4,
1148         Q_NEWS_ACCOUNT_ID  = 5,
1149         Q_SAVE_COPY_FOLDER = 6
1150 };
1151
1152 gint procmsg_send_message_queue(const gchar *file)
1153 {
1154         static HeaderEntry qentry[] = {{"S:",    NULL, FALSE},
1155                                        {"SSV:",  NULL, FALSE},
1156                                        {"R:",    NULL, FALSE},
1157                                        {"NG:",   NULL, FALSE},
1158                                        {"MAID:", NULL, FALSE},
1159                                        {"NAID:", NULL, FALSE},
1160                                        {"SCF:",  NULL, FALSE},
1161                                        {NULL,    NULL, FALSE}};
1162         FILE *fp;
1163         gint filepos;
1164         gint mailval = 0, newsval = 0;
1165         gchar *from = NULL;
1166         gchar *smtpserver = NULL;
1167         GSList *to_list = NULL;
1168         GSList *newsgroup_list = NULL;
1169         gchar *savecopyfolder = NULL;
1170         gchar buf[BUFFSIZE];
1171         gint hnum;
1172         PrefsAccount *mailac = NULL, *newsac = NULL;
1173         int local = 0;
1174
1175         g_return_val_if_fail(file != NULL, -1);
1176
1177         if ((fp = fopen(file, "rb")) == NULL) {
1178                 FILE_OP_ERROR(file, "fopen");
1179                 return -1;
1180         }
1181
1182         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, qentry))
1183                != -1) {
1184                 gchar *p = buf + strlen(qentry[hnum].name);
1185
1186                 switch (hnum) {
1187                 case Q_SENDER:
1188                         if (!from) from = g_strdup(p);
1189                         break;
1190                 case Q_SMTPSERVER:
1191                         if (!smtpserver) smtpserver = g_strdup(p);
1192                         break;
1193                 case Q_RECIPIENTS:
1194                         to_list = address_list_append(to_list, p);
1195                         break;
1196                 case Q_NEWSGROUPS:
1197                         newsgroup_list = newsgroup_list_append(newsgroup_list, p);
1198                         break;
1199                 case Q_MAIL_ACCOUNT_ID:
1200                         mailac = account_find_from_id(atoi(p));
1201                         break;
1202                 case Q_NEWS_ACCOUNT_ID:
1203                         newsac = account_find_from_id(atoi(p));
1204                         break;
1205                 case Q_SAVE_COPY_FOLDER:
1206                         if (!savecopyfolder) savecopyfolder = g_strdup(p);
1207                         break;
1208                 }
1209         }
1210         filepos = ftell(fp);
1211
1212         fseek(fp, filepos, SEEK_SET);
1213         if (to_list) {
1214                 debug_print(_("Sending message by mail\n"));
1215                 if(!from) {
1216                         g_warning(_("Queued message header is broken.\n"));
1217                         mailval = -1;
1218                 } else if (mailac && mailac->use_mail_command &&
1219                            mailac->mail_command && (* mailac->mail_command)) {
1220                         mailval = send_message_local(mailac->mail_command, fp);
1221                         local = 1;
1222                 } else if (prefs_common.use_extsend && prefs_common.extsend_cmd) {
1223                         mailval = send_message_local(prefs_common.extsend_cmd, fp);
1224                         local = 1;
1225                 } else {
1226                         if (!mailac) {
1227                                 mailac = account_find_from_smtp_server(from, smtpserver);
1228                                 if (!mailac) {
1229                                         g_warning(_("Account not found. "
1230                                                     "Using current account...\n"));
1231                                         mailac = cur_account;
1232                                 }
1233                         }
1234
1235                         if (mailac)
1236                                 mailval = send_message_smtp(mailac, to_list, fp);
1237                         else {
1238                                 PrefsAccount tmp_ac;
1239
1240                                 g_warning(_("Account not found.\n"));
1241
1242                                 memset(&tmp_ac, 0, sizeof(PrefsAccount));
1243                                 tmp_ac.address = from;
1244                                 tmp_ac.smtp_server = smtpserver;
1245                                 tmp_ac.smtpport = SMTP_PORT;
1246                                 mailval = send_message_smtp(&tmp_ac, to_list, fp);
1247                         }
1248                 }
1249                 if (mailval < 0) {
1250                         if (!local)
1251                                 alertpanel_error(
1252                                         _("Error occurred while sending the message to `%s'."),
1253                                         mailac ? mailac->smtp_server : smtpserver);
1254                         else
1255                                 alertpanel_error(
1256                                         _("Error occurred while sending the message with command `%s'."),
1257                                         (mailac && mailac->use_mail_command && 
1258                                          mailac->mail_command && (*mailac->mail_command)) ? 
1259                                                 mailac->mail_command : prefs_common.extsend_cmd);
1260                 }
1261         }
1262
1263         if(newsgroup_list && (newsval == 0)) {
1264                 Folder *folder;
1265                 gchar *tmp = NULL;
1266                 FILE *tmpfp;
1267
1268                 /* write to temporary file */
1269                 tmp = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
1270                             G_DIR_SEPARATOR, (gint)file);
1271                 if ((tmpfp = fopen(tmp, "wb")) == NULL) {
1272                         FILE_OP_ERROR(tmp, "fopen");
1273                         newsval = -1;
1274                         alertpanel_error(_("Could not create temporary file for news sending."));
1275                 } else {
1276                         if (change_file_mode_rw(tmpfp, tmp) < 0) {
1277                                 FILE_OP_ERROR(tmp, "chmod");
1278                                 g_warning(_("can't change file mode\n"));
1279                         }
1280
1281                         while ((newsval == 0) && fgets(buf, sizeof(buf), fp) != NULL) {
1282                                 if (fputs(buf, tmpfp) == EOF) {
1283                                         FILE_OP_ERROR(tmp, "fputs");
1284                                         newsval = -1;
1285                                         alertpanel_error(_("Error when writing temporary file for news sending."));
1286                                 }
1287                         }
1288                         fclose(tmpfp);
1289
1290                         if(newsval == 0) {
1291                                 debug_print(_("Sending message by news\n"));
1292
1293                                 folder = FOLDER(newsac->folder);
1294
1295                                 newsval = news_post(folder, tmp);
1296                                 if (newsval < 0) {
1297                                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1298                                                  newsac->nntp_server);
1299                                 }
1300                         }
1301                         unlink(tmp);
1302                 }
1303                 g_free(tmp);
1304         }
1305
1306         slist_free_strings(to_list);
1307         g_slist_free(to_list);
1308         slist_free_strings(newsgroup_list);
1309         g_slist_free(newsgroup_list);
1310         g_free(from);
1311         g_free(smtpserver);
1312         fclose(fp);
1313
1314         /* save message to outbox */
1315         if (mailval == 0 && newsval == 0 && savecopyfolder) {
1316                 FolderItem *outbox;
1317
1318                 debug_print(_("saving sent message...\n"));
1319
1320                 outbox = folder_find_item_from_identifier(savecopyfolder);
1321                 if(!outbox)
1322                         outbox = folder_get_default_outbox();
1323
1324                 procmsg_save_to_outbox(outbox, file, TRUE);
1325         }
1326
1327         return (newsval != 0 ? newsval : mailval);
1328 }