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