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