8ca00746377e4ae9cea6c7b1a24731fe8f190ea3
[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                                 if (save_msgs)
853                                         procmsg_save_to_outbox
854                                                 (queue->folder->outbox,
855                                                  file, TRUE);
856                                 folder_item_remove_msg(queue, i);
857                         }
858                         g_free(file);
859                 }
860         }
861
862         return ret;
863 }
864
865 gint procmsg_save_to_outbox(FolderItem *outbox, const gchar *file,
866                             gboolean is_queued)
867 {
868         gint num;
869         FILE *fp;
870         gchar *path;
871
872         debug_print(_("saving sent message...\n"));
873
874         if (!outbox)
875                 outbox = folder_get_default_outbox();
876         g_return_val_if_fail(outbox != NULL, -1);
877
878         /* remove queueing headers */
879         if (is_queued) {
880                 gchar tmp[MAXPATHLEN + 1];
881                 gchar buf[BUFFSIZE];
882                 FILE *outfp;
883
884                 g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.out.%08x",
885                            get_rc_dir(), G_DIR_SEPARATOR, (guint)random());
886                 if ((fp = fopen(file, "rb")) == NULL) {
887                         FILE_OP_ERROR(file, "fopen");
888                         return -1;
889                 }
890                 if ((outfp = fopen(tmp, "wb")) == NULL) {
891                         FILE_OP_ERROR(tmp, "fopen");
892                         fclose(fp);
893                         return -1;
894                 }
895                 while (fgets(buf, sizeof(buf), fp) != NULL)
896                         if (buf[0] == '\r' || buf[0] == '\n') break;
897                 while (fgets(buf, sizeof(buf), fp) != NULL)
898                         fputs(buf, outfp);
899                 fclose(outfp);
900                 fclose(fp);
901                 Xstrdup_a(file, tmp, return -1);
902         }
903
904         folder_item_scan(outbox);
905         if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
906                 g_warning(_("can't save message\n"));
907                 return -1;
908         }
909
910         path = folder_item_get_path(outbox);
911         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
912                 g_warning(_("can't open mark file\n"));
913         else {
914                 MsgInfo newmsginfo;
915
916                 newmsginfo.msgnum = num;
917                 newmsginfo.flags.perm_flags = 0;
918                 newmsginfo.flags.tmp_flags = 0;
919                 procmsg_write_flags(&newmsginfo, fp);
920                 fclose(fp);
921         }
922         g_free(path);
923
924         return 0;
925 }
926
927 void procmsg_print_message(MsgInfo *msginfo, const gchar *cmdline)
928 {
929         static const gchar *def_cmd = "lpr %s";
930         static guint id = 0;
931         gchar *prtmp;
932         FILE *tmpfp, *prfp;
933         gchar buf[1024];
934         gchar *p;
935
936         g_return_if_fail(msginfo);
937
938         if ((tmpfp = procmime_get_first_text_content(msginfo)) == NULL) {
939                 g_warning(_("Can't get text part\n"));
940                 return;
941         }
942
943         prtmp = g_strdup_printf("%s%cprinttmp.%08x",
944                                 get_mime_tmp_dir(), G_DIR_SEPARATOR, id++);
945
946         if ((prfp = fopen(prtmp, "wb")) == NULL) {
947                 FILE_OP_ERROR(prtmp, "fopen");
948                 g_free(prtmp);
949                 fclose(tmpfp);
950                 return;
951         }
952
953         if (msginfo->date) fprintf(prfp, "Date: %s\n", msginfo->date);
954         if (msginfo->from) fprintf(prfp, "From: %s\n", msginfo->from);
955         if (msginfo->to)   fprintf(prfp, "To: %s\n", msginfo->to);
956         if (msginfo->cc)   fprintf(prfp, "Cc: %s\n", msginfo->cc);
957         if (msginfo->newsgroups)
958                 fprintf(prfp, "Newsgroups: %s\n", msginfo->newsgroups);
959         if (msginfo->subject) fprintf(prfp, "Subject: %s\n", msginfo->subject);
960         fputc('\n', prfp);
961
962         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
963                 fputs(buf, prfp);
964
965         fclose(prfp);
966         fclose(tmpfp);
967
968         if (cmdline && (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
969             !strchr(p + 2, '%'))
970                 g_snprintf(buf, sizeof(buf) - 1, cmdline, prtmp);
971         else {
972                 if (cmdline)
973                         g_warning(_("Print command line is invalid: `%s'\n"),
974                                   cmdline);
975                 g_snprintf(buf, sizeof(buf) - 1, def_cmd, prtmp);
976         }
977
978         g_free(prtmp);
979
980         g_strchomp(buf);
981         if (buf[strlen(buf) - 1] != '&') strcat(buf, "&");
982         system(buf);
983 }
984
985 MsgInfo *procmsg_msginfo_copy(MsgInfo *msginfo)
986 {
987         MsgInfo *newmsginfo;
988
989         if (msginfo == NULL) return NULL;
990
991         newmsginfo = g_new0(MsgInfo, 1);
992
993 #define MEMBCOPY(mmb)   newmsginfo->mmb = msginfo->mmb
994 #define MEMBDUP(mmb)    newmsginfo->mmb = msginfo->mmb ? \
995                         g_strdup(msginfo->mmb) : NULL
996
997         MEMBCOPY(msgnum);
998         MEMBCOPY(size);
999         MEMBCOPY(mtime);
1000         MEMBCOPY(date_t);
1001         MEMBCOPY(flags);
1002
1003         MEMBDUP(fromname);
1004
1005         MEMBDUP(date);
1006         MEMBDUP(from);
1007         MEMBDUP(to);
1008         MEMBDUP(cc);
1009         MEMBDUP(newsgroups);
1010         MEMBDUP(subject);
1011         MEMBDUP(msgid);
1012         MEMBDUP(inreplyto);
1013         MEMBDUP(xref);
1014
1015         MEMBCOPY(folder);
1016         MEMBCOPY(to_folder);
1017
1018         MEMBDUP(xface);
1019         MEMBDUP(dispositionnotificationto);
1020         MEMBDUP(returnreceiptto);
1021         MEMBDUP(references);
1022
1023         MEMBCOPY(score);
1024         MEMBCOPY(threadscore);
1025
1026         return newmsginfo;
1027 }
1028
1029 void procmsg_msginfo_free(MsgInfo *msginfo)
1030 {
1031         if (msginfo == NULL) return;
1032
1033         g_free(msginfo->fromspace);
1034         g_free(msginfo->references);
1035         g_free(msginfo->returnreceiptto);
1036         g_free(msginfo->dispositionnotificationto);
1037         g_free(msginfo->xface);
1038
1039         g_free(msginfo->fromname);
1040
1041         g_free(msginfo->date);
1042         g_free(msginfo->from);
1043         g_free(msginfo->to);
1044         g_free(msginfo->cc);
1045         g_free(msginfo->newsgroups);
1046         g_free(msginfo->subject);
1047         g_free(msginfo->msgid);
1048         g_free(msginfo->inreplyto);
1049         g_free(msginfo->xref);
1050
1051         g_free(msginfo);
1052 }
1053
1054 static gint procmsg_cmp_msgnum(gconstpointer a, gconstpointer b)
1055 {
1056         const MsgInfo *msginfo = a;
1057         const guint msgnum = GPOINTER_TO_UINT(b);
1058
1059         if (!msginfo)
1060                 return -1;
1061
1062         return msginfo->msgnum - msgnum;
1063 }
1064
1065 gint procmsg_cmp_msgnum_for_sort(gconstpointer a, gconstpointer b)
1066 {
1067         const MsgInfo *msginfo1 = a;
1068         const MsgInfo *msginfo2 = b;
1069
1070         if (!msginfo1)
1071                 return -1;
1072         if (!msginfo2)
1073                 return -1;
1074
1075         return msginfo1->msgnum - msginfo2->msgnum;
1076 }
1077
1078 static gint procmsg_cmp_flag_msgnum(gconstpointer a, gconstpointer b)
1079 {
1080         const FlagInfo *finfo = a;
1081         const guint msgnum = GPOINTER_TO_UINT(b);
1082
1083         if (!finfo)
1084                 return -1;
1085
1086         return finfo->msgnum - msgnum;
1087 }
1088
1089 enum
1090 {
1091         Q_SENDER           = 0,
1092         Q_SMTPSERVER       = 1,
1093         Q_RECIPIENTS       = 2,
1094         Q_NEWSGROUPS       = 3,
1095         Q_MAIL_ACCOUNT_ID  = 4,
1096         Q_NEWS_ACCOUNT_ID  = 5,
1097         Q_SAVE_COPY_FOLDER = 6
1098 };
1099
1100 gint procmsg_send_message_queue(const gchar *file)
1101 {
1102         static HeaderEntry qentry[] = {{"S:",    NULL, FALSE},
1103                                        {"SSV:",  NULL, FALSE},
1104                                        {"R:",    NULL, FALSE},
1105                                        {"NG:",   NULL, FALSE},
1106                                        {"MAID:", NULL, FALSE},
1107                                        {"NAID:", NULL, FALSE},
1108                                        {"SCF:",  NULL, FALSE},
1109                                        {NULL,    NULL, FALSE}};
1110         FILE *fp;
1111         gint filepos;
1112         gint mailval = 0, newsval = 0;
1113         gchar *from = NULL;
1114         gchar *smtpserver = NULL;
1115         GSList *to_list = NULL;
1116         GSList *newsgroup_list = NULL;
1117         gchar *savecopyfolder = NULL;
1118         gchar buf[BUFFSIZE];
1119         gint hnum;
1120         PrefsAccount *mailac = NULL, *newsac = NULL;
1121         gchar *tmp = NULL;
1122         int local = 0;
1123
1124         g_return_val_if_fail(file != NULL, -1);
1125
1126         if ((fp = fopen(file, "rb")) == NULL) {
1127                 FILE_OP_ERROR(file, "fopen");
1128                 return -1;
1129         }
1130
1131         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, qentry))
1132                != -1) {
1133                 gchar *p = buf + strlen(qentry[hnum].name);
1134
1135                 switch (hnum) {
1136                 case Q_SENDER:
1137                         if (!from) from = g_strdup(p);
1138                         break;
1139                 case Q_SMTPSERVER:
1140                         if (!smtpserver) smtpserver = g_strdup(p);
1141                         break;
1142                 case Q_RECIPIENTS:
1143                         to_list = address_list_append(to_list, p);
1144                         break;
1145                 case Q_NEWSGROUPS:
1146                         newsgroup_list = newsgroup_list_append(newsgroup_list, p);
1147                         break;
1148                 case Q_MAIL_ACCOUNT_ID:
1149                         mailac = account_find_from_id(atoi(p));
1150                         break;
1151                 case Q_NEWS_ACCOUNT_ID:
1152                         newsac = account_find_from_id(atoi(p));
1153                         break;
1154                 case Q_SAVE_COPY_FOLDER:
1155                         if (!savecopyfolder) savecopyfolder = g_strdup(p);
1156                         break;
1157                 }
1158         }
1159         filepos = ftell(fp);
1160
1161         if(newsgroup_list || prefs_common.savemsg) {
1162                 FILE *tmpfp;
1163
1164                 /* write to temporary file */
1165                 tmp = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
1166                             G_DIR_SEPARATOR, (gint)file);
1167                 if ((tmpfp = fopen(tmp, "wb")) == NULL) {
1168                         FILE_OP_ERROR(tmp, "fopen");
1169                         newsval = -1;
1170                 }
1171                 if (change_file_mode_rw(tmpfp, tmp) < 0) {
1172                         FILE_OP_ERROR(tmp, "chmod");
1173                         g_warning(_("can't change file mode\n"));
1174                 }
1175
1176                 while ((newsval == 0) && fgets(buf, sizeof(buf), fp) != NULL) {
1177                         if (fputs(buf, tmpfp) == EOF) {
1178                                 FILE_OP_ERROR(tmp, "fputs");
1179                                 newsval = -1;
1180                         }
1181                 }
1182                 fclose(tmpfp);
1183         }
1184
1185         fseek(fp, filepos, SEEK_SET);
1186         if (to_list) {
1187                 debug_print(_("Sending message by mail\n"));
1188                 if(!from) {
1189                         g_warning(_("Queued message header is broken.\n"));
1190                         mailval = -1;
1191                 } else if (mailac && mailac->use_mail_command &&
1192                            mailac->mail_command && (* mailac->mail_command)) {
1193                         mailval = send_message_local(mailac->mail_command, fp);
1194                         local = 1;
1195                 } else if (prefs_common.use_extsend && prefs_common.extsend_cmd) {
1196                         mailval = send_message_local(prefs_common.extsend_cmd, fp);
1197                         local = 1;
1198                 } else {
1199                         if (!mailac) {
1200                                 mailac = account_find_from_smtp_server(from, smtpserver);
1201                                 if (!mailac) {
1202                                         g_warning(_("Account not found. "
1203                                                     "Using current account...\n"));
1204                                         mailac = cur_account;
1205                                 }
1206                         }
1207
1208                         if (mailac)
1209                                 mailval = send_message_smtp(mailac, to_list, fp);
1210                         else {
1211                                 PrefsAccount tmp_ac;
1212
1213                                 g_warning(_("Account not found.\n"));
1214
1215                                 memset(&tmp_ac, 0, sizeof(PrefsAccount));
1216                                 tmp_ac.address = from;
1217                                 tmp_ac.smtp_server = smtpserver;
1218                                 tmp_ac.smtpport = SMTP_PORT;
1219                                 mailval = send_message_smtp(&tmp_ac, to_list, fp);
1220                         }
1221                 }
1222                 if (mailval < 0) {
1223                         if (!local)
1224                                 alertpanel_error(
1225                                         _("Error occurred while sending the message to `%s'."),
1226                                         mailac ? mailac->smtp_server : smtpserver);
1227                         else
1228                                 alertpanel_error(
1229                                         _("Error occurred while sending the message with command `%s'."),
1230                                         (mailac && mailac->use_mail_command && 
1231                                          mailac->mail_command && (*mailac->mail_command)) ? 
1232                                                 mailac->mail_command : prefs_common.extsend_cmd);
1233                 }
1234         }
1235
1236         if(newsgroup_list && (newsval == 0)) {
1237                 Folder *folder;
1238
1239                 debug_print(_("Sending message by news\n"));
1240
1241                 folder = FOLDER(newsac->folder);
1242
1243                 newsval = news_post(folder, tmp);
1244                 if (newsval < 0) {
1245                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1246                                  newsac->nntp_server);
1247                 }
1248         }
1249
1250         /* save message to outbox */
1251         if (mailval == 0 && newsval == 0 && savecopyfolder) {
1252                 FolderItem *folder;
1253                 gchar *path;
1254                 gint num;
1255                 FILE *fp;
1256
1257                 debug_print(_("saving sent message...\n"));
1258
1259                 folder = folder_find_item_from_identifier(savecopyfolder);
1260                 if(!folder)
1261                         folder = folder_get_default_outbox();
1262                 path = folder_item_get_path(folder);
1263                 if (!is_dir_exist(path))
1264                         make_dir_hier(path);
1265
1266                 folder_item_scan(folder);
1267                 if ((num = folder_item_add_msg(folder, tmp, FALSE)) < 0) {
1268                         g_warning(_("can't save message\n"));
1269                 }
1270
1271                 if(num) {
1272                         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
1273                                 g_warning(_("can't open mark file\n"));
1274                         else {
1275                                 MsgInfo newmsginfo;
1276
1277                                 newmsginfo.msgnum = num;
1278                                 newmsginfo.flags.perm_flags = 0;
1279                                 newmsginfo.flags.tmp_flags = 0;
1280                                 procmsg_write_flags(&newmsginfo, fp);
1281                                 fclose(fp);
1282                         }
1283                 }
1284                 g_free(path);
1285         }
1286
1287         slist_free_strings(to_list);
1288         g_slist_free(to_list);
1289         slist_free_strings(newsgroup_list);
1290         g_slist_free(newsgroup_list);
1291         g_free(from);
1292         g_free(smtpserver);
1293         fclose(fp);
1294         if(tmp) {
1295                 unlink(tmp);
1296                 g_free(tmp);
1297         }
1298
1299         return (newsval != 0 ? newsval : mailval);
1300 }