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