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