2007-07-03 [colin] 2.10.0cvs4
[claws.git] / src / folder.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <unistd.h>
33 #include <stdlib.h>
34 #ifdef WIN32
35 #include <w32lib.h>
36 #endif
37
38 #include "folder.h"
39 #include "session.h"
40 #include "inc.h"
41 #include "imap.h"
42 #include "news.h"
43 #include "mh.h"
44 #include "utils.h"
45 #include "xml.h"
46 #include "codeconv.h"
47 #include "prefs_gtk.h"
48 #include "account.h"
49 #include "filtering.h"
50 #include "procheader.h"
51 #include "hooks.h"
52 #include "log.h"
53 #include "folder_item_prefs.h"
54 #include "remotefolder.h"
55 #include "partial_download.h"
56 #include "statusbar.h"
57 #include "gtkutils.h"
58 #include "timing.h"
59 #include "compose.h"
60 #include "main.h"
61
62 /* Dependecies to be removed ?! */
63 #include "prefs_common.h"
64 #include "prefs_account.h"
65
66 /* Define possible missing constants for Windows. */
67 #ifdef G_OS_WIN32
68 # ifndef S_IRGRP
69 # define S_IRGRP 0
70 # define S_IWGRP 0
71 # endif
72 # ifndef S_IROTH
73 # define S_IROTH 0
74 # define S_IWOTH 0
75 # endif
76 #endif
77
78 static GList *folder_list = NULL;
79 static GSList *class_list = NULL;
80 static GSList *folder_unloaded_list = NULL;
81
82 void folder_init                (Folder         *folder,
83                                  const gchar    *name);
84
85 static gchar *folder_item_get_cache_file        (FolderItem     *item);
86 static gchar *folder_item_get_mark_file (FolderItem     *item);
87 static gchar *folder_item_get_tags_file (FolderItem     *item);
88 static gchar *folder_get_list_path      (void);
89 static GNode *folder_get_xml_node       (Folder         *folder);
90 static Folder *folder_get_from_xml      (GNode          *node);
91 static void folder_update_op_count_rec  (GNode          *node);
92
93
94 static void folder_get_persist_prefs_recursive
95                                         (GNode *node, GHashTable *pptable);
96 static gboolean persist_prefs_free      (gpointer key, gpointer val, gpointer data);
97 static void folder_item_read_cache              (FolderItem *item);
98 gint folder_item_scan_full              (FolderItem *item, gboolean filtering);
99 static void folder_item_update_with_msg (FolderItem *item, FolderItemUpdateFlags update_flags,
100                                          MsgInfo *msg);
101 static GHashTable *folder_persist_prefs_new     (Folder *folder);
102 static void folder_persist_prefs_free           (GHashTable *pptable);
103 static void folder_item_restore_persist_prefs   (FolderItem *item, GHashTable *pptable);
104
105 void folder_system_init(void)
106 {
107         folder_register_class(mh_get_class());
108         folder_register_class(imap_get_class());
109         folder_register_class(news_get_class());
110 }
111
112 static GSList *folder_get_class_list(void)
113 {
114         return class_list;
115 }
116
117 void folder_register_class(FolderClass *klass)
118 {
119         GSList *xmllist, *cur;
120
121         debug_print("registering folder class %s\n", klass->idstr);
122
123         class_list = g_slist_append(class_list, klass);
124
125         xmllist = g_slist_copy(folder_unloaded_list);
126         for (cur = xmllist; cur != NULL; cur = g_slist_next(cur)) {
127                 GNode *node = (GNode *) cur->data;
128                 XMLNode *xmlnode = (XMLNode *) node->data;
129                 GList *cur = xmlnode->tag->attr;
130
131                 for (; cur != NULL; cur = g_list_next(cur)) {
132                         XMLAttr *attr = (XMLAttr *) cur->data;
133
134                         if (!attr || !attr->name || !attr->value) continue;
135                         if (!strcmp(attr->name, "type") && !strcmp(attr->value, klass->idstr)) {
136                                 Folder *folder;
137
138                                 folder = folder_get_from_xml(node);
139                                 folder_add(folder);
140                                 folder_unloaded_list = g_slist_remove(folder_unloaded_list, node);
141
142                                 cur = NULL;
143                                 continue;
144                         }
145                 }
146         }
147         g_slist_free(xmllist);
148 }
149
150 void folder_unregister_class(FolderClass *klass)
151 {
152         GList *folderlist, *cur;
153
154         debug_print("unregistering folder class %s\n", klass->idstr);
155
156         class_list = g_slist_remove(class_list, klass);
157
158         folderlist = g_list_copy(folder_get_list());
159         for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
160                 Folder *folder = (Folder *) cur->data;
161
162                 if (folder->klass == klass) {
163                         GNode *xmlnode = folder_get_xml_node(folder);
164                         folder_unloaded_list = g_slist_append(folder_unloaded_list, xmlnode);
165                         folder_destroy(folder);
166                 }
167         }
168         g_list_free(folderlist);
169 }
170
171 Folder *folder_new(FolderClass *klass, const gchar *name, const gchar *path)
172 {
173         Folder *folder = NULL;
174         FolderItem *item;
175
176         g_return_val_if_fail(klass != NULL, NULL);
177
178         name = name ? name : path;
179         folder = klass->new_folder(name, path);
180
181         /* Create root folder item */
182         item = folder_item_new(folder, name, NULL);
183         if (item == NULL) {
184                 return NULL;
185         }
186         item->folder = folder;
187         folder->node = item->node = g_node_new(item);
188         folder->data = NULL;
189
190         return folder;
191 }
192
193 void folder_init(Folder *folder, const gchar *name)
194 {
195         g_return_if_fail(folder != NULL);
196
197         folder_set_name(folder, name);
198
199         /* Init folder data */
200         folder->account = NULL;
201         folder->sort = 0;
202         folder->inbox = NULL;
203         folder->outbox = NULL;
204         folder->draft = NULL;
205         folder->queue = NULL;
206         folder->trash = NULL;
207 }
208
209 static void reset_parent_type(FolderItem *item, gpointer data) {
210         item->parent_stype = -1;
211 }
212
213 void folder_item_change_type(FolderItem *item, SpecialFolderItemType newtype)
214 {
215         Folder *folder = NULL;
216         FolderUpdateData hookdata;
217
218         folder = item->folder;
219         /* unset previous root of newtype */
220         switch(newtype) {
221         case F_INBOX:
222                 folder_item_change_type(folder->inbox, F_NORMAL);
223                 folder->inbox = item;
224                 break;
225         case F_OUTBOX:
226                 folder_item_change_type(folder->outbox, F_NORMAL);
227                 folder->outbox = item;
228                 break;
229         case F_QUEUE:
230                 folder_item_change_type(folder->queue, F_NORMAL);
231                 folder->queue = item;
232                 break;
233         case F_DRAFT:
234                 folder_item_change_type(folder->draft, F_NORMAL);
235                 folder->draft = item;
236                 break;
237         case F_TRASH:
238                 folder_item_change_type(folder->trash, F_NORMAL);
239                 folder->trash = item;
240                 break;
241         case F_NORMAL:
242         default:
243                 break;
244         }
245         /* set new type for current folder and sons */
246         item->stype = newtype;
247         folder_func_to_all_folders(reset_parent_type, NULL);
248         
249         hookdata.folder = folder;
250         hookdata.update_flags = FOLDER_TREE_CHANGED;
251         hookdata.item = NULL;
252         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
253 }
254
255 void folder_destroy(Folder *folder)
256 {
257         g_return_if_fail(folder != NULL);
258         g_return_if_fail(folder->klass->destroy_folder != NULL);
259
260         folder_remove(folder);
261
262         folder_tree_destroy(folder);
263
264         folder->klass->destroy_folder(folder);
265
266         g_free(folder->name);
267         g_free(folder);
268 }
269
270 void folder_set_xml(Folder *folder, XMLTag *tag)
271 {
272         GList *cur;
273         FolderItem *rootitem = NULL;
274
275         if ((folder->node != NULL) && (folder->node->data != NULL))
276                 rootitem = (FolderItem *) folder->node->data;
277
278         for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
279                 XMLAttr *attr = (XMLAttr *) cur->data;
280
281                 if (!attr || !attr->name || !attr->value) continue;
282                 if (!strcmp(attr->name, "name")) {
283                         g_free(folder->name);
284                         folder->name = g_strdup(attr->value);
285                         if (rootitem != NULL) {
286                                 g_free(rootitem->name);
287                                 rootitem->name = g_strdup(attr->value);
288                         }
289                 } else if (!strcmp(attr->name, "account_id")) {
290                         PrefsAccount *account;
291
292                         account = account_find_from_id(atoi(attr->value));
293                         if (!account)
294                                 g_warning("account_id: %s not found\n", attr->value);
295                         else {
296                                 folder->account = account;
297                                 account->folder = folder;
298                         }
299                 } else if (!strcmp(attr->name, "collapsed")) {
300                         if (rootitem != NULL)
301                                 rootitem->collapsed = *attr->value == '1' ? TRUE : FALSE;
302                 } else if (!strcmp(attr->name, "sort")) {
303                         folder->sort = atoi(attr->value);
304                 }
305         }
306 }
307
308 XMLTag *folder_get_xml(Folder *folder)
309 {
310         XMLTag *tag;
311
312         tag = xml_tag_new("folder");
313
314         if (folder->name)
315                 xml_tag_add_attr(tag, xml_attr_new("name", folder->name));
316         if (folder->account)
317                 xml_tag_add_attr(tag, xml_attr_new_int("account_id", folder->account->account_id));
318         if (folder->node && folder->node->data) {
319                 FolderItem *rootitem = (FolderItem *) folder->node->data;
320
321                 xml_tag_add_attr(tag, xml_attr_new("collapsed", rootitem->collapsed ? "1" : "0"));
322         }
323         xml_tag_add_attr(tag, xml_attr_new_int("sort", folder->sort));
324
325         return tag;
326 }
327
328 FolderItem *folder_item_new(Folder *folder, const gchar *name, const gchar *path)
329 {
330         FolderItem *item = NULL;
331         
332         g_return_val_if_fail(folder != NULL, NULL);
333         
334         if (folder->klass->item_new) {
335                 item = folder->klass->item_new(folder);
336         } else {
337                 item = g_new0(FolderItem, 1);
338         }
339
340         g_return_val_if_fail(item != NULL, NULL);
341
342         item->stype = F_NORMAL;
343         item->name = g_strdup(name);
344         item->path = g_strdup(path);
345         item->mtime = 0;
346         item->new_msgs = 0;
347         item->unread_msgs = 0;
348         item->unreadmarked_msgs = 0;
349         item->marked_msgs = 0;
350         item->total_msgs = 0;
351         item->order = 0;
352         item->last_num = -1;
353         item->cache = NULL;
354         item->no_sub = FALSE;
355         item->no_select = FALSE;
356         item->collapsed = FALSE;
357         item->thread_collapsed = FALSE;
358         item->threaded  = TRUE;
359         item->ret_rcpt  = FALSE;
360         item->opened    = FALSE;
361         item->node = g_node_new(item);
362         item->folder = NULL;
363         item->account = NULL;
364         item->apply_sub = FALSE;
365         item->mark_queue = NULL;
366         item->data = NULL;
367         item->parent_stype = -1;
368
369         item->sort_key = SORT_BY_DATE;
370         item->sort_type = SORT_ASCENDING;
371
372         item->prefs = folder_item_prefs_new();
373
374         return item;
375 }
376
377 void folder_item_append(FolderItem *parent, FolderItem *item)
378 {
379         g_return_if_fail(parent != NULL);
380         g_return_if_fail(parent->folder != NULL);
381         g_return_if_fail(parent->node != NULL);
382         g_return_if_fail(item != NULL);
383
384         item->folder = parent->folder;
385         g_node_append(parent->node, item->node);
386 }
387
388 void folder_item_remove(FolderItem *item)
389 {
390         GNode *node, *start_node;
391         FolderUpdateData hookdata;
392
393         g_return_if_fail(item != NULL);
394         g_return_if_fail(item->folder != NULL);
395         g_return_if_fail(item->folder->node != NULL);
396
397         start_node = node = item->node;
398         
399         node = item->folder->node;
400         
401         node = g_node_find(node, G_PRE_ORDER, G_TRAVERSE_ALL, item);
402         node = node->children;
403
404         /* remove my children */
405         while (node != NULL) {
406                 if (node && node->data) {
407                         FolderItem *sub_item = (FolderItem*) node->data;
408                         node = node->next;
409                         folder_item_remove(sub_item);
410                 }
411         }
412         
413         /* remove myself */
414         if (item->cache != NULL) {
415                 msgcache_destroy(item->cache);
416                 item->cache = NULL;
417         }
418
419         hookdata.folder = item->folder;
420         hookdata.update_flags = FOLDER_TREE_CHANGED | FOLDER_REMOVE_FOLDERITEM;
421         hookdata.item = item;
422         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
423
424         node = start_node;
425
426         if (item->folder->node == node)
427                 item->folder->node = NULL;
428
429         folder_item_destroy(item);
430
431         g_node_destroy(node);
432 }
433
434 void folder_item_remove_children(FolderItem *item)
435 {
436         GNode *node, *next;
437
438         g_return_if_fail(item != NULL);
439         g_return_if_fail(item->folder != NULL);
440         g_return_if_fail(item->node != NULL);
441
442         node = item->node->children;
443         while (node != NULL) {
444                 next = node->next;
445                 folder_item_remove(FOLDER_ITEM(node->data));
446                 node = next;
447         }
448 }
449
450 void folder_item_destroy(FolderItem *item)
451 {
452         Folder *folder;
453
454         g_return_if_fail(item != NULL);
455
456         folder = item->folder;
457         if (folder) {
458                 if (folder->inbox == item)
459                         folder->inbox = NULL;
460                 else if (folder->outbox == item)
461                         folder->outbox = NULL;
462                 else if (folder->draft == item)
463                         folder->draft = NULL;
464                 else if (folder->queue == item)
465                         folder->queue = NULL;
466                 else if (folder->trash == item)
467                         folder->trash = NULL;
468         }
469
470         if (item->cache)
471                 folder_item_free_cache(item, TRUE);
472         if (item->prefs)
473                 folder_item_prefs_free(item->prefs);
474         g_free(item->name);
475         g_free(item->path);
476
477         if (item->folder != NULL) {
478                 if(item->folder->klass->item_destroy) {
479                         item->folder->klass->item_destroy(item->folder, item);
480                 } else {
481                         g_free(item);
482                 }
483         }
484 }
485
486 FolderItem *folder_item_parent(FolderItem *item)
487 {
488         g_return_val_if_fail(item != NULL, NULL);
489         g_return_val_if_fail(item->node != NULL, NULL);
490
491         if (item->node->parent == NULL)
492                 return NULL;
493         return (FolderItem *) item->node->parent->data;
494 }
495
496 void folder_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
497 {
498         GList *cur;
499
500         for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
501                 XMLAttr *attr = (XMLAttr *) cur->data;
502
503                 if (!attr || !attr->name || !attr->value) continue;
504                 if (!strcmp(attr->name, "type")) {
505                         if (!g_ascii_strcasecmp(attr->value, "normal"))
506                                 item->stype = F_NORMAL;
507                         else if (!g_ascii_strcasecmp(attr->value, "inbox"))
508                                 item->stype = F_INBOX;
509                         else if (!g_ascii_strcasecmp(attr->value, "outbox"))
510                                 item->stype = F_OUTBOX;
511                         else if (!g_ascii_strcasecmp(attr->value, "draft"))
512                                 item->stype = F_DRAFT;
513                         else if (!g_ascii_strcasecmp(attr->value, "queue"))
514                                 item->stype = F_QUEUE;
515                         else if (!g_ascii_strcasecmp(attr->value, "trash"))
516                                 item->stype = F_TRASH;
517                 } else if (!strcmp(attr->name, "name")) {
518                         g_free(item->name);
519                         item->name = g_strdup(attr->value);
520                 } else if (!strcmp(attr->name, "path")) {
521                         g_free(item->path);
522                         item->path = g_strdup(attr->value);
523                 } else if (!strcmp(attr->name, "mtime"))
524                         item->mtime = strtoul(attr->value, NULL, 10);
525                 else if (!strcmp(attr->name, "new"))
526                         item->new_msgs = atoi(attr->value);
527                 else if (!strcmp(attr->name, "unread"))
528                         item->unread_msgs = atoi(attr->value);
529                 else if (!strcmp(attr->name, "unreadmarked"))
530                         item->unreadmarked_msgs = atoi(attr->value);
531                 else if (!strcmp(attr->name, "marked"))
532                         item->marked_msgs = atoi(attr->value);
533                 else if (!strcmp(attr->name, "order"))
534                         item->order = atoi(attr->value);
535                 else if (!strcmp(attr->name, "total"))
536                         item->total_msgs = atoi(attr->value);
537                 else if (!strcmp(attr->name, "no_sub"))
538                         item->no_sub = *attr->value == '1' ? TRUE : FALSE;
539                 else if (!strcmp(attr->name, "no_select"))
540                         item->no_select = *attr->value == '1' ? TRUE : FALSE;
541                 else if (!strcmp(attr->name, "collapsed"))
542                         item->collapsed = *attr->value == '1' ? TRUE : FALSE;
543                 else if (!strcmp(attr->name, "thread_collapsed"))
544                         item->thread_collapsed =  *attr->value == '1' ? TRUE : FALSE;
545                 else if (!strcmp(attr->name, "threaded"))
546                         item->threaded =  *attr->value == '1' ? TRUE : FALSE;
547                 else if (!strcmp(attr->name, "hidereadmsgs"))
548                         item->hide_read_msgs =  *attr->value == '1' ? TRUE : FALSE;
549                 else if (!strcmp(attr->name, "reqretrcpt"))
550                         item->ret_rcpt =  *attr->value == '1' ? TRUE : FALSE;
551                 else if (!strcmp(attr->name, "sort_key")) {
552                         if (!strcmp(attr->value, "none"))
553                                 item->sort_key = SORT_BY_NONE;
554                         else if (!strcmp(attr->value, "number"))
555                                 item->sort_key = SORT_BY_NUMBER;
556                         else if (!strcmp(attr->value, "size"))
557                                 item->sort_key = SORT_BY_SIZE;
558                         else if (!strcmp(attr->value, "date"))
559                                 item->sort_key = SORT_BY_DATE;
560                         else if (!strcmp(attr->value, "from"))
561                                 item->sort_key = SORT_BY_FROM;
562                         else if (!strcmp(attr->value, "subject"))
563                                 item->sort_key = SORT_BY_SUBJECT;
564                         else if (!strcmp(attr->value, "score"))
565                                 item->sort_key = SORT_BY_SCORE;
566                         else if (!strcmp(attr->value, "label"))
567                                 item->sort_key = SORT_BY_LABEL;
568                         else if (!strcmp(attr->value, "mark"))
569                                 item->sort_key = SORT_BY_MARK;
570                         else if (!strcmp(attr->value, "unread"))
571                                 item->sort_key = SORT_BY_STATUS;
572                         else if (!strcmp(attr->value, "mime"))
573                                 item->sort_key = SORT_BY_MIME;
574                         else if (!strcmp(attr->value, "to"))
575                                 item->sort_key = SORT_BY_TO;
576                         else if (!strcmp(attr->value, "locked"))
577                                 item->sort_key = SORT_BY_LOCKED;
578                         else if (!strcmp(attr->value, "tags"))
579                                 item->sort_key = SORT_BY_TAGS;
580                         else if (!strcmp(attr->value, "thread_date"))
581                                 item->sort_key = SORT_BY_THREAD_DATE;
582                 } else if (!strcmp(attr->name, "sort_type")) {
583                         if (!strcmp(attr->value, "ascending"))
584                                 item->sort_type = SORT_ASCENDING;
585                         else
586                                 item->sort_type = SORT_DESCENDING;
587                 } else if (!strcmp(attr->name, "account_id")) {
588                         PrefsAccount *account;
589
590                         account = account_find_from_id(atoi(attr->value));
591                         if (!account)
592                                 g_warning("account_id: %s not found\n", attr->value);
593                         else
594                                 item->account = account;
595                 } else if (!strcmp(attr->name, "apply_sub")) {
596                         item->apply_sub = *attr->value == '1' ? TRUE : FALSE;
597                 } else if (!strcmp(attr->name, "last_seen")) {
598                         if (!claws_crashed())
599                                 item->last_seen = atoi(attr->value);
600                         else
601                                 item->last_seen = 0;
602                 }
603         }
604 }
605
606 XMLTag *folder_item_get_xml(Folder *folder, FolderItem *item)
607 {
608         static gchar *folder_item_stype_str[] = {"normal", "inbox", "outbox",
609                                                  "draft", "queue", "trash"};
610         static gchar *sort_key_str[] = {"none", "number", "size", "date",
611                                         "from", "subject", "score", "label",
612                                         "mark", "unread", "mime", "to", 
613                                         "locked", "tags", "thread_date" };
614         XMLTag *tag;
615         gchar *value;
616
617         tag = xml_tag_new("folderitem");
618
619         xml_tag_add_attr(tag, xml_attr_new("type", folder_item_stype_str[item->stype]));
620         if (item->name)
621                 xml_tag_add_attr(tag, xml_attr_new("name", item->name));
622         if (item->path)
623                 xml_tag_add_attr(tag, xml_attr_new("path", item->path));
624         if (item->no_sub)
625                 xml_tag_add_attr(tag, xml_attr_new("no_sub", "1"));
626         if (item->no_select)
627                 xml_tag_add_attr(tag, xml_attr_new("no_select", "1"));
628         xml_tag_add_attr(tag, xml_attr_new("collapsed", item->collapsed && item->node->children ? "1" : "0"));
629         xml_tag_add_attr(tag, xml_attr_new("thread_collapsed", item->thread_collapsed ? "1" : "0"));
630         xml_tag_add_attr(tag, xml_attr_new("threaded", item->threaded ? "1" : "0"));
631         xml_tag_add_attr(tag, xml_attr_new("hidereadmsgs", item->hide_read_msgs ? "1" : "0"));
632         if (item->ret_rcpt)
633                 xml_tag_add_attr(tag, xml_attr_new("reqretrcpt", "1"));
634
635         if (item->sort_key != SORT_BY_NONE) {
636                 xml_tag_add_attr(tag, xml_attr_new("sort_key", sort_key_str[item->sort_key]));
637                 xml_tag_add_attr(tag, xml_attr_new("sort_type", item->sort_type == SORT_ASCENDING ? "ascending" : "descending"));
638         }
639
640         value = g_strdup_printf("%ld", (unsigned long int) item->mtime);
641         xml_tag_add_attr(tag, xml_attr_new("mtime", value));
642         g_free(value);
643         xml_tag_add_attr(tag, xml_attr_new_int("new", item->new_msgs));
644         xml_tag_add_attr(tag, xml_attr_new_int("unread", item->unread_msgs));
645         xml_tag_add_attr(tag, xml_attr_new_int("unreadmarked", item->unreadmarked_msgs));
646         xml_tag_add_attr(tag, xml_attr_new_int("marked", item->marked_msgs));
647         xml_tag_add_attr(tag, xml_attr_new_int("total", item->total_msgs));
648         xml_tag_add_attr(tag, xml_attr_new_int("order", item->order));
649
650         if (item->account)
651                 xml_tag_add_attr(tag, xml_attr_new_int("account_id", item->account->account_id));
652         if (item->apply_sub)
653                 xml_tag_add_attr(tag, xml_attr_new("apply_sub", "1"));
654
655         xml_tag_add_attr(tag, xml_attr_new_int("last_seen", item->last_seen));
656
657         return tag;
658 }
659
660 void folder_set_ui_func(Folder *folder, FolderUIFunc func, gpointer data)
661 {
662         g_return_if_fail(folder != NULL);
663
664         folder->ui_func = func;
665         folder->ui_func_data = data;
666 }
667
668 void folder_set_name(Folder *folder, const gchar *name)
669 {
670         g_return_if_fail(folder != NULL);
671
672         g_free(folder->name);
673         folder->name = name ? g_strdup(name) : NULL;
674         if (folder->node && folder->node->data) {
675                 FolderItem *item = (FolderItem *)folder->node->data;
676
677                 g_free(item->name);
678                 item->name = name ? g_strdup(name) : NULL;
679         }
680 }
681
682 void folder_set_sort(Folder *folder, guint sort)
683 {
684         g_return_if_fail(folder != NULL);
685
686         if (folder->sort != sort) {
687                 folder_remove(folder);
688                 folder->sort = sort;
689                 folder_add(folder);
690         }
691 }
692
693 static gboolean folder_tree_destroy_func(GNode *node, gpointer data) {
694         FolderItem *item = (FolderItem *) node->data;
695
696         folder_item_destroy(item);
697         return FALSE;
698 }
699
700 void folder_tree_destroy(Folder *folder)
701 {
702         GNode *node;
703
704         g_return_if_fail(folder != NULL);
705
706         node = folder->node;
707         
708         prefs_filtering_clear_folder(folder);
709
710         if (node != NULL) {
711                 g_node_traverse(node, G_POST_ORDER, G_TRAVERSE_ALL, -1,
712                                 folder_tree_destroy_func, NULL);
713                 g_node_destroy(node);
714                 folder->node = NULL;
715         }
716 }
717
718 void folder_add(Folder *folder)
719 {
720         Folder *cur_folder;
721         GList *cur;
722         gint i;
723         FolderUpdateData hookdata;
724
725         g_return_if_fail(folder != NULL);
726
727         for (i = 0, cur = folder_list; cur != NULL; cur = cur->next, i++) {
728                 cur_folder = FOLDER(cur->data);
729                 if (cur_folder->sort < folder->sort)
730                         break;
731         }
732
733         folder_list = g_list_insert(folder_list, folder, i);
734
735         hookdata.folder = folder;
736         hookdata.update_flags = FOLDER_ADD_FOLDER;
737         hookdata.item = NULL;
738         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
739 }
740
741 void folder_remove(Folder *folder)
742 {
743         FolderUpdateData hookdata;
744
745         g_return_if_fail(folder != NULL);
746
747         folder_list = g_list_remove(folder_list, folder);
748
749         hookdata.folder = folder;
750         hookdata.update_flags = FOLDER_REMOVE_FOLDER;
751         hookdata.item = NULL;
752         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
753 }
754
755 GList *folder_get_list(void)
756 {
757         return folder_list;
758 }
759
760 gint folder_read_list(void)
761 {
762         GNode *node, *cur;
763         XMLNode *xmlnode;
764         gchar *path;
765
766         path = folder_get_list_path();
767         if (!is_file_exist(path)) return -1;
768         node = xml_parse_file(path);
769         if (!node) return -1;
770
771         xmlnode = node->data;
772         if (strcmp2(xmlnode->tag->tag, "folderlist") != 0) {
773                 g_warning("wrong folder list\n");
774                 xml_free_tree(node);
775                 return -1;
776         }
777
778         cur = node->children;
779         while (cur != NULL) {
780                 Folder *folder;
781
782                 folder = folder_get_from_xml(cur);
783                 if (folder != NULL)
784                         folder_add(folder);
785                 else
786                         folder_unloaded_list = g_slist_append(folder_unloaded_list,
787                                 (gpointer) xml_copy_tree(cur));
788                 cur = cur->next;
789         }
790
791         xml_free_tree(node);
792         if (folder_list || folder_unloaded_list)
793                 return 0;
794         else
795                 return -1;
796 }
797
798 void folder_write_list(void)
799 {
800         GList *list;
801         GSList *slist;
802         Folder *folder;
803         gchar *path;
804         PrefFile *pfile;
805         GNode *rootnode;
806         XMLNode *xmlnode;
807         XMLTag *tag;
808
809         path = folder_get_list_path();
810         if ((pfile = prefs_write_open(path)) == NULL) return;
811
812         if (xml_file_put_xml_decl(pfile->fp) < 0) {
813                 prefs_file_close_revert(pfile);
814                 g_warning("failed to start write folder list.\n");
815                 return;         
816         }
817         tag = xml_tag_new("folderlist");
818
819         xmlnode = xml_node_new(tag, NULL);
820
821         rootnode = g_node_new(xmlnode);
822
823         for (list = folder_list; list != NULL; list = list->next) {
824                 GNode *node;
825
826                 folder = list->data;
827                 node = folder_get_xml_node(folder);
828                 if (node != NULL)
829                         g_node_append(rootnode, node);
830         }
831
832         for (slist = folder_unloaded_list; slist != NULL; slist = g_slist_next(slist)) {
833                 GNode *node = (GNode *) slist->data;
834
835                 g_node_append(rootnode, (gpointer) xml_copy_tree(node));
836         }
837
838         if (xml_write_tree(rootnode, pfile->fp) < 0) {
839                 prefs_file_close_revert(pfile);
840                 g_warning("failed to write folder list.\n");
841         } else if (prefs_file_close(pfile) < 0) {
842                 g_warning("failed to write folder list.\n");
843         }
844         xml_free_tree(rootnode);
845 }
846
847 static gboolean folder_scan_tree_func(GNode *node, gpointer data)
848 {
849         GHashTable *pptable = (GHashTable *)data;
850         FolderItem *item = (FolderItem *)node->data;
851         
852         folder_item_restore_persist_prefs(item, pptable);
853         folder_item_scan_full(item, FALSE);
854
855         return FALSE;
856 }
857
858 void folder_scan_tree(Folder *folder, gboolean rebuild)
859 {
860         GHashTable *pptable;
861         FolderUpdateData hookdata;
862         Folder *old_folder = folder;
863
864         if (!folder->klass->scan_tree)
865                 return;
866         
867         pptable = folder_persist_prefs_new(folder);
868
869         if (rebuild)
870                 folder_remove(folder);
871
872         if (folder->klass->scan_tree(folder) < 0) {
873                 if (rebuild)
874                         folder_add(old_folder);
875                 return;
876         } else if (rebuild)
877                 folder_add(folder);
878
879         hookdata.folder = folder;
880         hookdata.update_flags = FOLDER_TREE_CHANGED;
881         hookdata.item = NULL;
882         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
883
884         g_node_traverse(folder->node, G_POST_ORDER, G_TRAVERSE_ALL, -1, folder_scan_tree_func, pptable);
885         folder_persist_prefs_free(pptable);
886
887         prefs_matcher_read_config();
888
889         folder_write_list();
890 }
891
892 static gboolean folder_restore_prefs_func(GNode *node, gpointer data)
893 {
894         GHashTable *pptable = (GHashTable *)data;
895         FolderItem *item = (FolderItem *)node->data;
896         
897         folder_item_restore_persist_prefs(item, pptable);
898
899         return FALSE;
900 }
901
902 void folder_fast_scan_tree(Folder *folder)
903 {
904         GHashTable *pptable;
905         FolderUpdateData hookdata;
906
907         if (!folder->klass->scan_tree)
908                 return;
909         
910         pptable = folder_persist_prefs_new(folder);
911
912         if (folder->klass->scan_tree(folder) < 0) {
913                 return;
914         } 
915
916         hookdata.folder = folder;
917         hookdata.update_flags = FOLDER_TREE_CHANGED;
918         hookdata.item = NULL;
919         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
920
921         g_node_traverse(folder->node, G_POST_ORDER, G_TRAVERSE_ALL, -1, folder_restore_prefs_func, pptable);
922         folder_persist_prefs_free(pptable);
923
924         prefs_matcher_read_config();
925
926         folder_write_list();
927 }
928
929 FolderItem *folder_create_folder(FolderItem *parent, const gchar *name)
930 {
931         FolderItem *new_item;
932
933         new_item = parent->folder->klass->create_folder(parent->folder, parent, name);
934         if (new_item) {
935                 FolderUpdateData hookdata;
936
937                 new_item->cache = msgcache_new();
938
939                 hookdata.folder = new_item->folder;
940                 hookdata.update_flags = FOLDER_TREE_CHANGED | FOLDER_ADD_FOLDERITEM;
941                 hookdata.item = new_item;
942                 hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
943         }
944
945         return new_item;
946 }
947
948 gint folder_item_rename(FolderItem *item, gchar *newname)
949 {
950         gint retval;
951
952         g_return_val_if_fail(item != NULL, -1);
953         g_return_val_if_fail(newname != NULL, -1);
954
955         retval = item->folder->klass->rename_folder(item->folder, item, newname);
956
957         if (retval >= 0) {
958                 FolderItemUpdateData hookdata;
959                 FolderUpdateData hookdata2;
960
961                 hookdata.item = item;
962                 hookdata.update_flags = F_ITEM_UPDATE_NAME;
963                 hookdata.msg = NULL;
964                 hooks_invoke(FOLDER_ITEM_UPDATE_HOOKLIST, &hookdata);
965
966                 hookdata2.folder = item->folder;
967                 hookdata2.item = item;
968                 hookdata2.update_flags = FOLDER_RENAME_FOLDERITEM;
969                 hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata2);
970         }
971
972         return retval;
973 }
974
975 struct TotalMsgCount
976 {
977         guint new_msgs;
978         guint unread_msgs;
979         guint unreadmarked_msgs;
980         guint marked_msgs;
981         guint total_msgs;
982 };
983
984 struct FuncToAllFoldersData
985 {
986         FolderItemFunc  function;
987         gpointer        data;
988 };
989
990 static gboolean folder_func_to_all_folders_func(GNode *node, gpointer data)
991 {
992         FolderItem *item;
993         struct FuncToAllFoldersData *function_data = (struct FuncToAllFoldersData *) data;
994
995         g_return_val_if_fail(node->data != NULL, FALSE);
996
997         item = FOLDER_ITEM(node->data);
998         g_return_val_if_fail(item != NULL, FALSE);
999
1000         function_data->function(item, function_data->data);
1001
1002         return FALSE;
1003 }
1004
1005 void folder_func_to_all_folders(FolderItemFunc function, gpointer data)
1006 {
1007         GList *list;
1008         Folder *folder;
1009         struct FuncToAllFoldersData function_data;
1010         
1011         function_data.function = function;
1012         function_data.data = data;
1013
1014         for (list = folder_list; list != NULL; list = list->next) {
1015                 folder = FOLDER(list->data);
1016                 if (folder->node)
1017                         g_node_traverse(folder->node, G_PRE_ORDER,
1018                                         G_TRAVERSE_ALL, -1,
1019                                         folder_func_to_all_folders_func,
1020                                         &function_data);
1021         }
1022 }
1023
1024 static void folder_count_total_msgs_func(FolderItem *item, gpointer data)
1025 {
1026         struct TotalMsgCount *count = (struct TotalMsgCount *)data;
1027
1028         count->new_msgs += item->new_msgs;
1029         count->unread_msgs += item->unread_msgs;
1030         count->unreadmarked_msgs += item->unreadmarked_msgs;
1031         count->marked_msgs += item->marked_msgs;
1032         count->total_msgs += item->total_msgs;
1033 }
1034
1035 struct TotalMsgStatus
1036 {
1037         guint new;
1038         guint unread;
1039         guint total;
1040         GString *str;
1041 };
1042
1043 static gboolean folder_get_status_full_all_func(GNode *node, gpointer data)
1044 {
1045         FolderItem *item;
1046         struct TotalMsgStatus *status = (struct TotalMsgStatus *)data;
1047         gchar *id;
1048  
1049         g_return_val_if_fail(node->data != NULL, FALSE);
1050  
1051         item = FOLDER_ITEM(node->data);
1052
1053         if (!item->path) return FALSE;
1054
1055         status->new += item->new_msgs;
1056         status->unread += item->unread_msgs;
1057         status->total += item->total_msgs;
1058
1059         if (status->str) {
1060                 id = folder_item_get_identifier(item);
1061                 g_string_append_printf(status->str, "%5d %5d %5d %s\n",
1062                                   item->new_msgs, item->unread_msgs,
1063                                   item->total_msgs, id);
1064                 g_free(id);
1065         }
1066  
1067         return FALSE;
1068  }
1069  
1070 static void folder_get_status_full_all(GString *str, guint *new, guint *unread,
1071                                        guint *total)
1072 {
1073         GList *list;
1074         Folder *folder;
1075         struct TotalMsgStatus status;
1076  
1077         status.new = status.unread = status.total = 0;
1078         status.str = str;
1079  
1080         debug_print("Counting total number of messages...\n");
1081  
1082         for (list = folder_list; list != NULL; list = list->next) {
1083                 folder = FOLDER(list->data);
1084                 if (folder->node)
1085                         g_node_traverse(folder->node, G_PRE_ORDER,
1086                                         G_TRAVERSE_ALL, -1,
1087                                         folder_get_status_full_all_func,
1088                                         &status);
1089         }
1090  
1091         *new = status.new;
1092         *unread = status.unread;
1093         *total = status.total;
1094 }
1095
1096 gchar *folder_get_status(GPtrArray *folders, gboolean full)
1097 {
1098         guint new, unread, total;
1099         GString *str;
1100         gint i;
1101         gchar *ret;
1102
1103         new = unread = total = 0;
1104
1105         str = g_string_new(NULL);
1106
1107         if (folders) {
1108                 for (i = 0; i < folders->len; i++) {
1109                         FolderItem *item;
1110
1111                         item = g_ptr_array_index(folders, i);
1112                         new += item->new_msgs;
1113                         unread += item->unread_msgs;
1114                         total += item->total_msgs;
1115
1116                         if (full) {
1117                                 gchar *id;
1118
1119                                 id = folder_item_get_identifier(item);
1120                                 g_string_append_printf(str, "%5d %5d %5d %s\n",
1121                                                   item->new_msgs, item->unread_msgs,
1122                                                   item->total_msgs, id);
1123                                 g_free(id);
1124                         }
1125                 }
1126         } else {
1127                 folder_get_status_full_all(full ? str : NULL,
1128                                            &new, &unread, &total);
1129         }
1130
1131         if (full)
1132                 g_string_append_printf(str, "%5d %5d %5d\n", new, unread, total);
1133         else
1134                 g_string_append_printf(str, "%d %d %d\n", new, unread, total);
1135
1136         ret = str->str;
1137         g_string_free(str, FALSE);
1138  
1139         return ret;
1140 }
1141
1142 void folder_count_total_msgs(guint *new_msgs, guint *unread_msgs, 
1143                              guint *unreadmarked_msgs, guint *marked_msgs,
1144                              guint *total_msgs)
1145 {
1146         struct TotalMsgCount count;
1147
1148         count.new_msgs = count.unread_msgs = count.unreadmarked_msgs = count.total_msgs = 0;
1149
1150         debug_print("Counting total number of messages...\n");
1151
1152         folder_func_to_all_folders(folder_count_total_msgs_func, &count);
1153
1154         *new_msgs = count.new_msgs;
1155         *unread_msgs = count.unread_msgs;
1156         *unreadmarked_msgs = count.unreadmarked_msgs;
1157         *marked_msgs = count.marked_msgs;
1158         *total_msgs = count.total_msgs;
1159 }
1160
1161 Folder *folder_find_from_path(const gchar *path)
1162 {
1163         GList *list;
1164         Folder *folder;
1165
1166         for (list = folder_list; list != NULL; list = list->next) {
1167                 folder = list->data;
1168                 if ((FOLDER_TYPE(folder) == F_MH || 
1169                      FOLDER_TYPE(folder) == F_MBOX) &&
1170                     !path_cmp(LOCAL_FOLDER(folder)->rootpath, path))
1171                         return folder;
1172         }
1173
1174         return NULL;
1175 }
1176
1177 Folder *folder_find_from_name(const gchar *name, FolderClass *klass)
1178 {
1179         GList *list;
1180         Folder *folder;
1181
1182         for (list = folder_list; list != NULL; list = list->next) {
1183                 folder = list->data;
1184                 if (folder->klass == klass && 
1185                     strcmp2(name, folder->name) == 0)
1186                         return folder;
1187         }
1188
1189         return NULL;
1190 }
1191
1192 static gboolean folder_item_find_func(GNode *node, gpointer data)
1193 {
1194         FolderItem *item = node->data;
1195         gpointer *d = data;
1196         const gchar *path = d[0];
1197
1198         if (path_cmp(path, item->path) != 0)
1199                 return FALSE;
1200
1201         d[1] = item;
1202
1203         return TRUE;
1204 }
1205
1206 FolderItem *folder_find_item_from_path(const gchar *path)
1207 {
1208         Folder *folder;
1209         gpointer d[2];
1210         GList *list = folder_get_list();
1211         
1212         folder = list ? list->data:NULL;
1213         
1214         g_return_val_if_fail(folder != NULL, NULL);
1215
1216         d[0] = (gpointer)path;
1217         d[1] = NULL;
1218         while (d[1] == NULL && list) {
1219                 folder = FOLDER(list->data);
1220                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1221                         folder_item_find_func, d);
1222                 list = list->next;
1223         }
1224         return d[1];
1225 }
1226
1227 FolderItem *folder_find_child_item_by_name(FolderItem *item, const gchar *name)
1228 {
1229         GNode *node;
1230         FolderItem *child;
1231
1232         for (node = item->node->children; node != NULL; node = node->next) {
1233                 gchar *base;
1234                 child = FOLDER_ITEM(node->data);
1235                 base = g_path_get_basename(child->path);
1236                 if (strcmp2(base, name) == 0) {
1237                         g_free(base);
1238                         return child;
1239                 }
1240                 g_free(base);
1241         }
1242
1243         return NULL;
1244 }
1245
1246 FolderClass *folder_get_class_from_string(const gchar *str)
1247 {
1248         GSList *classlist;
1249
1250         classlist = folder_get_class_list();
1251         for (; classlist != NULL; classlist = g_slist_next(classlist)) {
1252                 FolderClass *class = (FolderClass *) classlist->data;
1253                 if (g_ascii_strcasecmp(class->idstr, str) == 0)
1254                         return class;
1255         }
1256
1257         return NULL;
1258 }
1259
1260 static gchar *folder_get_identifier(Folder *folder)
1261 {
1262         gchar *type_str;
1263
1264         g_return_val_if_fail(folder != NULL, NULL);
1265
1266         type_str = folder->klass->idstr;
1267         return g_strconcat("#", type_str, "/", folder->name, NULL);
1268 }
1269
1270 gchar *folder_item_get_identifier(FolderItem *item)
1271 {
1272         gchar *id = NULL;
1273         gchar *folder_id = NULL;
1274
1275         g_return_val_if_fail(item != NULL, NULL);
1276
1277         if (item->path == NULL)
1278                 return NULL;
1279
1280         folder_id = folder_get_identifier(item->folder);
1281         id = g_strconcat(folder_id, "/", item->path, NULL);
1282         g_free(folder_id);
1283
1284         return id;
1285 }
1286
1287 FolderItem *folder_find_item_from_identifier(const gchar *identifier)
1288 {
1289         Folder *folder;
1290         gpointer d[2];
1291         gchar *str;
1292         gchar *p;
1293         gchar *name;
1294         gchar *path;
1295         FolderClass *class;
1296
1297         g_return_val_if_fail(identifier != NULL, NULL);
1298
1299         if (*identifier != '#')
1300                 return folder_find_item_from_path(identifier);
1301
1302         Xstrdup_a(str, identifier, return NULL);
1303
1304         p = strchr(str, '/');
1305         if (!p)
1306                 return folder_find_item_from_path(identifier);
1307         *p = '\0';
1308         p++;
1309         class = folder_get_class_from_string(&str[1]);
1310         if (class == NULL)
1311                 return folder_find_item_from_path(identifier);
1312
1313         name = p;
1314         p = strchr(p, '/');
1315         if (!p)
1316                 return folder_find_item_from_path(identifier);
1317         *p = '\0';
1318         p++;
1319
1320         folder = folder_find_from_name(name, class);
1321         if (!folder)
1322                 return folder_find_item_from_path(identifier);
1323
1324         path = p;
1325
1326         d[0] = (gpointer)path;
1327         d[1] = NULL;
1328         g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1329                         folder_item_find_func, d);
1330         return d[1];
1331 }
1332
1333 /**
1334  * Get a displayable name for a FolderItem
1335  *
1336  * \param item FolderItem for that a name should be created
1337  * \return Displayable name for item, returned string has to
1338  *         be freed
1339  */
1340 gchar *folder_item_get_name(FolderItem *item)
1341 {
1342         gchar *name = NULL;
1343
1344         g_return_val_if_fail(item != NULL, g_strdup(""));
1345
1346         switch (item->stype) {
1347         case F_INBOX:
1348                 name = g_strdup(!strcmp2(item->name, INBOX_DIR) ? _("Inbox") :
1349                                 item->name);
1350                 break;
1351         case F_OUTBOX:
1352                 name = g_strdup(!strcmp2(item->name, OUTBOX_DIR) ? _("Sent") :
1353                                 item->name);
1354                 break;
1355         case F_QUEUE:
1356                 name = g_strdup(!strcmp2(item->name, QUEUE_DIR) ? _("Queue") :
1357                                 item->name);
1358                 break;
1359         case F_TRASH:
1360                 name = g_strdup(!strcmp2(item->name, TRASH_DIR) ? _("Trash") :
1361                                 item->name);
1362                 break;
1363         case F_DRAFT:
1364                 name = g_strdup(!strcmp2(item->name, DRAFT_DIR) ? _("Drafts") :
1365                                 item->name);
1366                 break;
1367         default:
1368                 break;
1369         }
1370
1371         if (name == NULL) {
1372                 /*
1373                  * should probably be done by a virtual function,
1374                  * the folder knows the ui string and how to abbrev
1375                 */
1376                 if (folder_item_parent(item) == NULL) {
1377                         name = g_strconcat(item->name, " (", item->folder->klass->uistr, ")", NULL);
1378                 } else {
1379                         if (FOLDER_CLASS(item->folder) == news_get_class() &&
1380                             item->path && !strcmp2(item->name, item->path))
1381                                 name = get_abbrev_newsgroup_name
1382                                         (item->path,
1383                                          prefs_common.ng_abbrev_len);
1384                         else
1385                                 name = g_strdup(item->name);
1386                 }
1387         }
1388
1389         if (name == NULL)
1390                 name = g_strdup("");
1391
1392         return name;
1393 }
1394
1395 gboolean folder_have_mailbox (void)
1396 {
1397         GList *cur;
1398         for (cur = folder_list; cur != NULL; cur = g_list_next(cur)) {
1399                 Folder *folder = FOLDER(cur->data);
1400                 if (folder->inbox && folder->outbox)
1401                         return TRUE;
1402         }
1403         return FALSE;
1404 }
1405
1406 FolderItem *folder_get_default_inbox(void)
1407 {
1408         GList *flist;
1409
1410         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1411                 Folder * folder = FOLDER(flist->data);
1412
1413                 if (folder == NULL)
1414                         continue;
1415                 if (folder->inbox == NULL)
1416                         continue;
1417                 if (folder->klass->type == F_UNKNOWN)
1418                         continue;
1419
1420                 return folder->inbox;
1421         }
1422
1423         return NULL;
1424 }
1425
1426 FolderItem *folder_get_default_inbox_for_class(FolderType type)
1427 {
1428         GList *flist;
1429
1430         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1431                 Folder * folder = FOLDER(flist->data);
1432
1433                 if (folder == NULL)
1434                         continue;
1435                 if (folder->inbox == NULL)
1436                         continue;
1437                 if (folder->klass->type != type)
1438                         continue;
1439
1440                 return folder->inbox;
1441         }
1442
1443         return NULL;
1444 }
1445
1446 FolderItem *folder_get_default_outbox(void)
1447 {
1448         GList *flist;
1449
1450         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1451                 Folder * folder = FOLDER(flist->data);
1452
1453                 if (folder == NULL)
1454                         continue;
1455                 if (folder->outbox == NULL)
1456                         continue;
1457                 if (folder->klass->type == F_UNKNOWN)
1458                         continue;
1459
1460                 return folder->outbox;
1461         }
1462
1463         return NULL;
1464 }
1465
1466 FolderItem *folder_get_default_draft(void)
1467 {
1468         GList *flist;
1469
1470         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1471                 Folder * folder = FOLDER(flist->data);
1472
1473                 if (folder == NULL)
1474                         continue;
1475                 if (folder->draft == NULL)
1476                         continue;
1477                 if (folder->klass->type == F_UNKNOWN)
1478                         continue;
1479
1480                 return folder->draft;
1481         }
1482
1483         return NULL;
1484 }
1485
1486 FolderItem *folder_get_default_queue(void)
1487 {
1488         GList *flist;
1489
1490         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1491                 Folder * folder = FOLDER(flist->data);
1492
1493                 if (folder == NULL)
1494                         continue;
1495                 if (folder->queue == NULL)
1496                         continue;
1497                 if (folder->klass->type == F_UNKNOWN)
1498                         continue;
1499
1500                 return folder->queue;
1501         }
1502
1503         return NULL;
1504 }
1505
1506 FolderItem *folder_get_default_trash(void)
1507 {
1508         GList *flist;
1509
1510         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1511                 Folder * folder = FOLDER(flist->data);
1512
1513                 if (folder == NULL)
1514                         continue;
1515                 if (folder->trash == NULL)
1516                         continue;
1517                 if (folder->klass->type == F_UNKNOWN)
1518                         continue;
1519
1520                 return folder->trash;
1521         }
1522
1523         return NULL;
1524 }
1525
1526 #define CREATE_FOLDER_IF_NOT_EXIST(member, dir, type)           \
1527 {                                                               \
1528         if (!folder->member) {                                  \
1529                 item = folder_item_new(folder, dir, dir);       \
1530                 item->stype = type;                             \
1531                 folder_item_append(rootitem, item);             \
1532                 folder->member = item;                          \
1533         }                                                       \
1534 }
1535
1536 void folder_set_missing_folders(void)
1537 {
1538         Folder *folder;
1539         FolderItem *rootitem;
1540         FolderItem *item;
1541         GList *list;
1542
1543         for (list = folder_list; list != NULL; list = list->next) {
1544                 folder = list->data;
1545                 if (FOLDER_TYPE(folder) != F_MH) continue;
1546                 rootitem = FOLDER_ITEM(folder->node->data);
1547                 g_return_if_fail(rootitem != NULL);
1548
1549                 if (folder->inbox && folder->outbox && folder->draft &&
1550                     folder->queue && folder->trash)
1551                         continue;
1552
1553                 if (folder->klass->create_tree(folder) < 0) {
1554                         g_warning("%s: can't create the folder tree.\n",
1555                                   LOCAL_FOLDER(folder)->rootpath);
1556                         continue;
1557                 }
1558
1559                 CREATE_FOLDER_IF_NOT_EXIST(inbox,  INBOX_DIR,  F_INBOX);
1560                 CREATE_FOLDER_IF_NOT_EXIST(outbox, OUTBOX_DIR, F_OUTBOX);
1561                 CREATE_FOLDER_IF_NOT_EXIST(draft,  DRAFT_DIR,  F_DRAFT);
1562                 CREATE_FOLDER_IF_NOT_EXIST(queue,  QUEUE_DIR,  F_QUEUE);
1563                 CREATE_FOLDER_IF_NOT_EXIST(trash,  TRASH_DIR,  F_TRASH);
1564         }
1565 }
1566
1567 static gboolean folder_unref_account_func(GNode *node, gpointer data)
1568 {
1569         FolderItem *item = node->data;
1570         PrefsAccount *account = data;
1571
1572         if (item->account == account)
1573                 item->account = NULL;
1574
1575         return FALSE;
1576 }
1577
1578 void folder_unref_account_all(PrefsAccount *account)
1579 {
1580         Folder *folder;
1581         GList *list;
1582
1583         if (!account) return;
1584
1585         for (list = folder_list; list != NULL; list = list->next) {
1586                 folder = list->data;
1587                 if (folder->account == account)
1588                         folder->account = NULL;
1589                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1590                                 folder_unref_account_func, account);
1591         }
1592 }
1593
1594 #undef CREATE_FOLDER_IF_NOT_EXIST
1595
1596 gchar *folder_item_get_path(FolderItem *item)
1597 {
1598         Folder *folder;
1599
1600         g_return_val_if_fail(item != NULL, NULL);
1601         folder = item->folder;
1602         g_return_val_if_fail(folder != NULL, NULL);
1603
1604         return folder->klass->item_get_path(folder, item);
1605 }
1606
1607 void folder_item_set_default_flags(FolderItem *dest, MsgFlags *flags)
1608 {
1609         if (!(folder_has_parent_of_type(dest, F_OUTBOX) ||
1610               folder_has_parent_of_type(dest, F_QUEUE)  ||
1611               folder_has_parent_of_type(dest, F_DRAFT) ||
1612               folder_has_parent_of_type(dest, F_TRASH))) {
1613                 flags->perm_flags = MSG_NEW|MSG_UNREAD;
1614         } else {
1615                 flags->perm_flags = 0;
1616         }
1617         if (FOLDER_TYPE(dest->folder) == F_MH) {
1618                 if (folder_has_parent_of_type(dest, F_QUEUE)) {
1619                         MSG_SET_TMP_FLAGS(*flags, MSG_QUEUED);
1620                 } else if (folder_has_parent_of_type(dest, F_DRAFT)) {
1621                         MSG_SET_TMP_FLAGS(*flags, MSG_DRAFT);
1622                 }
1623         }
1624 }
1625
1626 static gint folder_sort_cache_list_by_msgnum(gconstpointer a, gconstpointer b)
1627 {
1628         MsgInfo *msginfo_a = (MsgInfo *) a;
1629         MsgInfo *msginfo_b = (MsgInfo *) b;
1630
1631         return (msginfo_a->msgnum - msginfo_b->msgnum);
1632 }
1633
1634 static gint folder_sort_folder_list(gconstpointer a, gconstpointer b)
1635 {
1636         guint gint_a = GPOINTER_TO_INT(a);
1637         guint gint_b = GPOINTER_TO_INT(b);
1638         
1639         return (gint_a - gint_b);
1640 }
1641
1642 void folder_item_process_open (FolderItem *item,
1643                                  void (*before_proc_func)(gpointer data),
1644                                  void (*after_proc_func)(gpointer data),
1645                                  gpointer data)
1646 {
1647         gchar *buf;
1648         if (item == NULL)
1649                 return;
1650         if((item->folder->klass->scan_required != NULL) &&
1651            (item->folder->klass->scan_required(item->folder, item))) {
1652                 folder_item_scan_full(item, TRUE);
1653         } else {
1654                 folder_item_syncronize_flags(item);
1655         }
1656         
1657         /* Processing */
1658         buf = g_strdup_printf(_("Processing (%s)...\n"), 
1659                               item->path ? item->path : item->name);
1660         g_free(buf);
1661
1662         if (before_proc_func)
1663                 before_proc_func(data);
1664
1665         folder_item_apply_processing(item);
1666
1667         if (after_proc_func)
1668                 after_proc_func(data);
1669
1670         item->processing_pending = FALSE;
1671         return; 
1672 }
1673
1674 gint folder_item_open(FolderItem *item)
1675 {
1676         START_TIMING(""); 
1677         if (item->no_select)
1678                 return -1;
1679
1680         if (item->scanning) {
1681                 debug_print("%s is scanning... \n", item->path ? item->path : item->name);
1682                 return -2;
1683         }
1684
1685         item->processing_pending = TRUE;
1686         folder_item_process_open (item, NULL, NULL, NULL);
1687         
1688         item->opened = TRUE;
1689         END_TIMING();
1690         return 0;
1691 }
1692
1693 gint folder_item_close(FolderItem *item)
1694 {
1695         GSList *mlist, *cur;
1696         Folder *folder;
1697         
1698         g_return_val_if_fail(item != NULL, -1);
1699
1700         if (item->no_select)
1701                 return -1;
1702
1703         if (item->new_msgs) {
1704                 folder_item_update_freeze();
1705                 mlist = folder_item_get_msg_list(item);
1706                 for (cur = mlist ; cur != NULL ; cur = cur->next) {
1707                         MsgInfo * msginfo;
1708
1709                         msginfo = (MsgInfo *) cur->data;
1710                         if (MSG_IS_NEW(msginfo->flags))
1711                                 procmsg_msginfo_unset_flags(msginfo, MSG_NEW, 0);
1712                         procmsg_msginfo_free(msginfo);
1713                 }
1714                 g_slist_free(mlist);
1715                 folder_item_update_thaw();
1716         }               
1717
1718         folder_item_write_cache(item);
1719         
1720         folder_item_update(item, F_ITEM_UPDATE_MSGCNT);
1721
1722         item->opened = FALSE;
1723         folder = item->folder;
1724
1725         if (folder->klass->close == NULL)
1726                 return 0;
1727
1728         return folder->klass->close(folder, item);
1729 }
1730
1731 static MsgInfoList *get_msginfos(FolderItem *item, MsgNumberList *numlist)
1732 {
1733         MsgInfoList *msglist = NULL;
1734         Folder *folder = item->folder;
1735         if (item->no_select)
1736                 return NULL;
1737         
1738         if (folder->klass->get_msginfos != NULL)
1739                 msglist = folder->klass->get_msginfos(folder, item, numlist);
1740         else {
1741                 MsgNumberList *elem;
1742
1743                 for (elem = numlist; elem != NULL; elem = g_slist_next(elem)) {
1744                         MsgInfo *msginfo;
1745                         guint num;
1746
1747                         num = GPOINTER_TO_INT(elem->data);
1748                         msginfo = folder->klass->get_msginfo(folder, item, num);
1749                         if (msginfo != NULL)
1750                                 msglist = g_slist_prepend(msglist, msginfo);
1751                 }               
1752         }
1753
1754         return msglist;
1755 }
1756
1757 static MsgInfo *get_msginfo(FolderItem *item, guint num)
1758 {
1759         MsgNumberList numlist;
1760         MsgInfoList *msglist;
1761         MsgInfo *msginfo = NULL;
1762
1763         numlist.data = GINT_TO_POINTER(num);
1764         numlist.next = NULL;
1765         msglist = get_msginfos(item, &numlist);
1766         if (msglist != NULL)
1767                 msginfo = procmsg_msginfo_new_ref(msglist->data);
1768         procmsg_msg_list_free(msglist);
1769
1770         return msginfo;
1771 }
1772
1773 static gint syncronize_flags(FolderItem *item, MsgInfoList *msglist)
1774 {
1775         GRelation *relation;
1776         gint ret = 0;
1777         GSList *cur;
1778
1779         if(msglist == NULL)
1780                 return 0;
1781         if(item->folder->klass->get_flags == NULL)
1782                 return 0;
1783         if (item->no_select)
1784                 return 0;
1785
1786         relation = g_relation_new(2);
1787         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
1788         folder_item_set_batch(item, TRUE);
1789         if ((ret = item->folder->klass->get_flags(
1790             item->folder, item, msglist, relation)) == 0) {
1791                 GTuples *tuples;
1792                 MsgInfo *msginfo;
1793                 MsgPermFlags permflags = 0;
1794                 gboolean skip;
1795
1796                 folder_item_update_freeze();
1797                 for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1798                         msginfo = (MsgInfo *) cur->data;
1799                 
1800                         tuples = g_relation_select(relation, msginfo, 0);
1801                         skip = tuples->len < 1;
1802                         if (!skip)
1803                                 permflags = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
1804                         g_tuples_destroy(tuples);
1805                         if (skip)
1806                                 continue;
1807                         
1808                         if (msginfo->flags.perm_flags != permflags) {
1809                                 procmsg_msginfo_change_flags(msginfo,
1810                                         permflags & ~msginfo->flags.perm_flags, 0,
1811                                         ~permflags & msginfo->flags.perm_flags, 0);
1812                         }
1813                 }
1814                 folder_item_update_thaw();
1815         }
1816         folder_item_set_batch(item, FALSE);
1817         g_relation_destroy(relation);   
1818
1819         return ret;
1820 }
1821
1822 gint folder_item_scan_full(FolderItem *item, gboolean filtering)
1823 {
1824         Folder *folder;
1825         GSList *folder_list = NULL, *cache_list = NULL;
1826         GSList *folder_list_cur, *cache_list_cur, *new_list = NULL;
1827         GSList *exists_list = NULL, *elem;
1828         GSList *newmsg_list = NULL;
1829         guint newcnt = 0, unreadcnt = 0, totalcnt = 0;
1830         guint markedcnt = 0, unreadmarkedcnt = 0;
1831         guint cache_max_num, folder_max_num, cache_cur_num, folder_cur_num;
1832         gboolean update_flags = 0, old_uids_valid = FALSE;
1833         GHashTable *subject_table = NULL;
1834         
1835         g_return_val_if_fail(item != NULL, -1);
1836         if (item->path == NULL) return -1;
1837
1838         folder = item->folder;
1839
1840         g_return_val_if_fail(folder != NULL, -1);
1841         g_return_val_if_fail(folder->klass->get_num_list != NULL, -1);
1842
1843         item->scanning = TRUE;
1844
1845         debug_print("Scanning folder %s for cache changes.\n", item->path ? item->path : "(null)");
1846         
1847         /* Get list of messages for folder and cache */
1848         if (folder->klass->get_num_list(item->folder, item, &folder_list, &old_uids_valid) < 0) {
1849                 debug_print("Error fetching list of message numbers\n");
1850                 item->scanning = FALSE;
1851                 return(-1);
1852         }
1853
1854         if(prefs_common.thread_by_subject) {
1855                 subject_table = g_hash_table_new(g_str_hash, g_str_equal);
1856         }
1857         
1858         if (old_uids_valid) {
1859                 if (!item->cache)
1860                         folder_item_read_cache(item);
1861                 cache_list = msgcache_get_msg_list(item->cache);
1862         } else {
1863                 if (item->cache)
1864                         msgcache_destroy(item->cache);
1865                 item->cache = msgcache_new();
1866                 cache_list = NULL;
1867         }
1868
1869         /* Sort both lists */
1870         cache_list = g_slist_sort(cache_list, folder_sort_cache_list_by_msgnum);
1871         folder_list = g_slist_sort(folder_list, folder_sort_folder_list);
1872
1873         cache_list_cur = cache_list;
1874         folder_list_cur = folder_list;
1875
1876         if (cache_list_cur != NULL) {
1877                 GSList *cache_list_last;
1878         
1879                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
1880                 cache_list_last = g_slist_last(cache_list);
1881                 cache_max_num = ((MsgInfo *)cache_list_last->data)->msgnum;
1882         } else {
1883                 cache_cur_num = G_MAXINT;
1884                 cache_max_num = 0;
1885         }
1886
1887         if (folder_list_cur != NULL) {
1888                 GSList *folder_list_last;
1889         
1890                 folder_cur_num = GPOINTER_TO_INT(folder_list_cur->data);
1891                 folder_list_last = g_slist_last(folder_list);
1892                 folder_max_num = GPOINTER_TO_INT(folder_list_last->data);
1893         } else {
1894                 folder_cur_num = G_MAXINT;
1895                 folder_max_num = 0;
1896         }
1897
1898         while ((cache_cur_num != G_MAXINT) || (folder_cur_num != G_MAXINT)) {
1899                 /*
1900                  *  Message only exists in the folder
1901                  *  Remember message for fetching
1902                  */
1903                 if (folder_cur_num < cache_cur_num) {
1904                         gboolean add = FALSE;
1905
1906                         switch(FOLDER_TYPE(folder)) {
1907                                 case F_NEWS:
1908                                         if (folder_cur_num < cache_max_num)
1909                                                 break;
1910                                         
1911                                         if (folder->account->max_articles == 0) {
1912                                                 add = TRUE;
1913                                         }
1914
1915                                         if (folder_max_num <= folder->account->max_articles) {
1916                                                 add = TRUE;
1917                                         } else if (folder_cur_num > (folder_max_num - folder->account->max_articles)) {
1918                                                 add = TRUE;
1919                                         }
1920                                         break;
1921                                 default:
1922                                         add = TRUE;
1923                                         break;
1924                         }
1925                         
1926                         if (add) {
1927                                 new_list = g_slist_prepend(new_list, GINT_TO_POINTER(folder_cur_num));
1928                                 debug_print("Remembered message %d for fetching\n", folder_cur_num);
1929                         }
1930
1931                         /* Move to next folder number */
1932                         folder_list_cur = folder_list_cur->next;
1933
1934                         if (folder_list_cur != NULL)
1935                                 folder_cur_num = GPOINTER_TO_INT(folder_list_cur->data);
1936                         else
1937                                 folder_cur_num = G_MAXINT;
1938
1939                         continue;
1940                 }
1941
1942                 /*
1943                  *  Message only exists in the cache
1944                  *  Remove the message from the cache
1945                  */
1946                 if (cache_cur_num < folder_cur_num) {
1947                         msgcache_remove_msg(item->cache, cache_cur_num);
1948                         debug_print("Removed message %d from cache.\n", cache_cur_num);
1949
1950                         /* Move to next cache number */
1951                         cache_list_cur = cache_list_cur->next;
1952
1953                         if (cache_list_cur != NULL)
1954                                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
1955                         else
1956                                 cache_cur_num = G_MAXINT;
1957
1958                         update_flags |= F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT;
1959
1960                         continue;
1961                 }
1962
1963                 /*
1964                  *  Message number exists in folder and cache!
1965                  *  Check if the message has been modified
1966                  */
1967                 if (cache_cur_num == folder_cur_num) {
1968                         MsgInfo *msginfo;
1969
1970                         msginfo = msgcache_get_msg(item->cache, folder_cur_num);
1971                         if (folder->klass->is_msg_changed && folder->klass->is_msg_changed(folder, item, msginfo)) {
1972                                 msgcache_remove_msg(item->cache, msginfo->msgnum);
1973                                 new_list = g_slist_prepend(new_list, GINT_TO_POINTER(msginfo->msgnum));
1974                                 procmsg_msginfo_free(msginfo);
1975
1976                                 debug_print("Remembering message %d to update...\n", folder_cur_num);
1977                         } else {
1978                                 exists_list = g_slist_prepend(exists_list, msginfo);
1979
1980                                 if(prefs_common.thread_by_subject &&
1981                                         MSG_IS_IGNORE_THREAD(msginfo->flags) &&
1982                                         !subject_table_lookup(subject_table, msginfo->subject)) {
1983                                         subject_table_insert(subject_table, msginfo->subject, msginfo);
1984                                 }
1985                         }
1986                         
1987                         /* Move to next folder and cache number */
1988                         cache_list_cur = cache_list_cur->next;
1989                         folder_list_cur = folder_list_cur->next;
1990
1991                         if (cache_list_cur != NULL)
1992                                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
1993                         else
1994                                 cache_cur_num = G_MAXINT;
1995
1996                         if (folder_list_cur != NULL)
1997                                 folder_cur_num = GPOINTER_TO_INT(folder_list_cur->data);
1998                         else
1999                                 folder_cur_num = G_MAXINT;
2000
2001                         continue;
2002                 }
2003         }
2004         
2005         for(cache_list_cur = cache_list; cache_list_cur != NULL; cache_list_cur = g_slist_next(cache_list_cur))
2006                 procmsg_msginfo_free((MsgInfo *) cache_list_cur->data);
2007
2008         g_slist_free(cache_list);
2009         g_slist_free(folder_list);
2010
2011         if (new_list != NULL) {
2012                 GSList *tmp_list = NULL;
2013                 newmsg_list = get_msginfos(item, new_list);
2014                 g_slist_free(new_list);
2015                 tmp_list = g_slist_concat(g_slist_copy(exists_list), g_slist_copy(newmsg_list));
2016                 syncronize_flags(item, tmp_list);
2017                 g_slist_free(tmp_list);
2018         } else {
2019                 syncronize_flags(item, exists_list);
2020         }
2021
2022         folder_item_update_freeze();
2023         if (newmsg_list != NULL) {
2024                 GSList *elem, *to_filter = NULL;
2025                 gboolean do_filter = (filtering == TRUE) &&
2026                                         (item->stype == F_INBOX) &&
2027                                         (item->folder->account != NULL) && 
2028                                         (item->folder->account->filter_on_recv);
2029                 
2030                 for (elem = newmsg_list; elem != NULL; elem = g_slist_next(elem)) {
2031                         MsgInfo *msginfo = (MsgInfo *) elem->data;
2032
2033                         msgcache_add_msg(item->cache, msginfo);
2034                         if (!do_filter) {
2035                                 exists_list = g_slist_prepend(exists_list, msginfo);
2036
2037                                 if(prefs_common.thread_by_subject &&
2038                                         MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2039                                         !subject_table_lookup(subject_table, msginfo->subject)) {
2040                                         subject_table_insert(subject_table, msginfo->subject, msginfo);
2041                                 }                       
2042                         }
2043                 }
2044
2045                 if (do_filter) {
2046                         GSList *unfiltered;
2047                         procmsg_msglist_filter(newmsg_list, item->folder->account, 
2048                                         &to_filter, &unfiltered, 
2049                                         TRUE);
2050                         
2051                         filtering_move_and_copy_msgs(newmsg_list);
2052                         if (to_filter != NULL) {
2053                                 for (elem = to_filter; elem; elem = g_slist_next(elem)) {
2054                                         MsgInfo *msginfo = (MsgInfo *)elem->data;
2055                                         procmsg_msginfo_free(msginfo);
2056                                 }
2057                                 g_slist_free(to_filter);
2058                         }
2059                         if (unfiltered != NULL) {
2060                                 for (elem = unfiltered; elem; elem = g_slist_next(elem)) {
2061                                         MsgInfo *msginfo = (MsgInfo *)elem->data;
2062                                         exists_list = g_slist_prepend(exists_list, msginfo);
2063
2064                                         if(prefs_common.thread_by_subject &&
2065                                                 MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2066                                                 !subject_table_lookup(subject_table, msginfo->subject)) {
2067                                                 subject_table_insert(subject_table, msginfo->subject, msginfo);
2068                                         }
2069                                 }
2070                                 g_slist_free(unfiltered);
2071                         }
2072                         if (prefs_common.real_time_sync)
2073                                 folder_item_synchronise(item);
2074                 } else {
2075                         if (prefs_common.real_time_sync)
2076                                 folder_item_synchronise(item);
2077                 }
2078
2079                 g_slist_free(newmsg_list);
2080
2081                 update_flags |= F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT;
2082         }
2083
2084         folder_item_set_batch(item, TRUE);
2085         for (elem = exists_list; elem != NULL; elem = g_slist_next(elem)) {
2086                 MsgInfo *msginfo, *parent_msginfo;
2087
2088                 msginfo = elem->data;
2089                 if (MSG_IS_IGNORE_THREAD(msginfo->flags) && (MSG_IS_NEW(msginfo->flags) || MSG_IS_UNREAD(msginfo->flags)))
2090                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
2091                 if (!MSG_IS_IGNORE_THREAD(msginfo->flags) && procmsg_msg_has_flagged_parent(msginfo, MSG_IGNORE_THREAD)) {
2092                         procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0, MSG_NEW | MSG_UNREAD, 0);
2093                 }
2094                 if(prefs_common.thread_by_subject && !msginfo->inreplyto &&
2095                         !msginfo->references && !MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2096                         (parent_msginfo = subject_table_lookup(subject_table, msginfo->subject)))
2097                 {
2098                         if(MSG_IS_IGNORE_THREAD(parent_msginfo->flags)) {
2099                                 procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0,
2100                                                 MSG_NEW | MSG_UNREAD, 0);
2101                         }
2102                 }
2103                 if ((folder_has_parent_of_type(item, F_OUTBOX) ||
2104                      folder_has_parent_of_type(item, F_QUEUE)  ||
2105                      folder_has_parent_of_type(item, F_DRAFT)  ||
2106                      folder_has_parent_of_type(item, F_TRASH)) &&
2107                     (MSG_IS_NEW(msginfo->flags) || MSG_IS_UNREAD(msginfo->flags)))
2108                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
2109                 if (MSG_IS_NEW(msginfo->flags))
2110                         newcnt++;
2111                 if (MSG_IS_UNREAD(msginfo->flags))
2112                         unreadcnt++;
2113                 if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2114                         unreadmarkedcnt++;
2115                 if (MSG_IS_MARKED(msginfo->flags))
2116                         markedcnt++;
2117
2118                 totalcnt++;
2119
2120                 procmsg_msginfo_free(msginfo);
2121         }
2122         folder_item_set_batch(item, FALSE);
2123         g_slist_free(exists_list);
2124         
2125         if(prefs_common.thread_by_subject) {
2126                 g_hash_table_destroy(subject_table);
2127         }
2128         
2129         if (item->new_msgs != newcnt || item->unread_msgs != unreadcnt
2130         ||  item->total_msgs != totalcnt || item->marked_msgs != markedcnt
2131         ||  item->unreadmarked_msgs != unreadmarkedcnt) {
2132                 update_flags |= F_ITEM_UPDATE_CONTENT;
2133         }
2134
2135         item->new_msgs = newcnt;
2136         item->unread_msgs = unreadcnt;
2137         item->total_msgs = totalcnt;
2138         item->unreadmarked_msgs = unreadmarkedcnt;
2139         item->marked_msgs = markedcnt;
2140
2141         update_flags |= F_ITEM_UPDATE_MSGCNT;
2142
2143         folder_item_update(item, update_flags);
2144         folder_item_update_thaw();
2145         
2146         item->scanning = FALSE;
2147
2148         return 0;
2149 }
2150
2151 gint folder_item_scan(FolderItem *item)
2152 {
2153         return folder_item_scan_full(item, TRUE);
2154 }
2155
2156 static void folder_item_scan_foreach_func(gpointer key, gpointer val,
2157                                           gpointer data)
2158 {
2159         folder_item_scan(FOLDER_ITEM(key));
2160 }
2161
2162 void folder_item_scan_foreach(GHashTable *table)
2163 {
2164         g_hash_table_foreach(table, folder_item_scan_foreach_func, NULL);
2165 }
2166
2167 static void folder_count_total_cache_memusage(FolderItem *item, gpointer data)
2168 {
2169         gint *memusage = (gint *)data;
2170
2171         if (item->cache == NULL)
2172                 return;
2173         
2174         *memusage += msgcache_get_memory_usage(item->cache);
2175 }
2176
2177 gint folder_item_syncronize_flags(FolderItem *item)
2178 {
2179         MsgInfoList *msglist = NULL;
2180         GSList *cur;
2181         gint ret = 0;
2182         
2183         g_return_val_if_fail(item != NULL, -1);
2184         g_return_val_if_fail(item->folder != NULL, -1);
2185         g_return_val_if_fail(item->folder->klass != NULL, -1);
2186         if (item->no_select)
2187                 return -1;
2188
2189         item->scanning = TRUE;
2190
2191         if (item->cache == NULL)
2192                 folder_item_read_cache(item);
2193         
2194         msglist = msgcache_get_msg_list(item->cache);
2195         
2196         ret = syncronize_flags(item, msglist);
2197
2198         for (cur = msglist; cur != NULL; cur = g_slist_next(cur))
2199                 procmsg_msginfo_free((MsgInfo *) cur->data);
2200         
2201         g_slist_free(msglist);
2202
2203         item->scanning = FALSE;
2204
2205         return ret;
2206 }
2207
2208 static gint folder_cache_time_compare_func(gconstpointer a, gconstpointer b)
2209 {
2210         FolderItem *fa = (FolderItem *)a;
2211         FolderItem *fb = (FolderItem *)b;
2212         
2213         return (gint) (msgcache_get_last_access_time(fa->cache) - msgcache_get_last_access_time(fb->cache));
2214 }
2215
2216 static void folder_find_expired_caches(FolderItem *item, gpointer data)
2217 {
2218         GSList **folder_item_list = (GSList **)data;
2219         gint difftime, expiretime;
2220         
2221         if (item->cache == NULL)
2222                 return;
2223
2224         if (item->opened > 0)
2225                 return;
2226
2227         difftime = (gint) (time(NULL) - msgcache_get_last_access_time(item->cache));
2228         expiretime = prefs_common.cache_min_keep_time * 60;
2229         debug_print("Cache unused time: %d (Expire time: %d)\n", difftime, expiretime);
2230
2231         if (difftime > expiretime && !item->opened && !item->processing_pending) {
2232                 *folder_item_list = g_slist_insert_sorted(*folder_item_list, item, folder_cache_time_compare_func);
2233         }
2234 }
2235
2236 gboolean folder_item_free_cache(FolderItem *item, gboolean force)
2237 {
2238         g_return_val_if_fail(item != NULL, TRUE);
2239         
2240         if (item->cache == NULL)
2241                 return TRUE;
2242         
2243         if (item->opened > 0 && !force)
2244                 return FALSE;
2245
2246         folder_item_write_cache(item);
2247         msgcache_destroy(item->cache);
2248         item->cache = NULL;
2249         return TRUE;
2250 }
2251
2252 void folder_clean_cache_memory_force(void)
2253 {
2254         int old_cache_max_mem_usage = prefs_common.cache_max_mem_usage;
2255         int old_cache_min_keep_time = prefs_common.cache_min_keep_time;
2256
2257         prefs_common.cache_max_mem_usage = 0;
2258         prefs_common.cache_min_keep_time = 0;
2259
2260         folder_clean_cache_memory(NULL);
2261
2262         prefs_common.cache_max_mem_usage = old_cache_max_mem_usage;
2263         prefs_common.cache_min_keep_time = old_cache_min_keep_time;
2264 }
2265
2266 void folder_clean_cache_memory(FolderItem *protected_item)
2267 {
2268         gint memusage = 0;
2269
2270         folder_func_to_all_folders(folder_count_total_cache_memusage, &memusage);       
2271         debug_print("Total cache memory usage: %d\n", memusage);
2272         
2273         if (memusage > (prefs_common.cache_max_mem_usage * 1024)) {
2274                 GSList *folder_item_list = NULL, *listitem;
2275                 
2276                 debug_print("Trying to free cache memory\n");
2277
2278                 folder_func_to_all_folders(folder_find_expired_caches, &folder_item_list);      
2279                 listitem = folder_item_list;
2280                 while((listitem != NULL) && (memusage > (prefs_common.cache_max_mem_usage * 1024))) {
2281                         FolderItem *item = (FolderItem *)(listitem->data);
2282                         gint cache_size = 0;
2283                         if (item == protected_item) {
2284                                 listitem = listitem->next;
2285                                 continue;
2286                         }
2287                         debug_print("Freeing cache memory for %s\n", item->path ? item->path : item->name);
2288                         cache_size = msgcache_get_memory_usage(item->cache);
2289                         if (folder_item_free_cache(item, FALSE))
2290                                 memusage -= cache_size;
2291
2292                         listitem = listitem->next;
2293                 }
2294                 g_slist_free(folder_item_list);
2295         }
2296 }
2297
2298 static void folder_item_read_cache(FolderItem *item)
2299 {
2300         gchar *cache_file, *mark_file, *tags_file;
2301         START_TIMING("");
2302         g_return_if_fail(item != NULL);
2303
2304         if (item->path != NULL) {
2305                 cache_file = folder_item_get_cache_file(item);
2306                 mark_file = folder_item_get_mark_file(item);
2307                 tags_file = folder_item_get_tags_file(item);
2308                 item->cache = msgcache_read_cache(item, cache_file);
2309                 if (!item->cache) {
2310                         MsgInfoList *list, *cur;
2311                         guint newcnt = 0, unreadcnt = 0;
2312                         guint markedcnt = 0, unreadmarkedcnt = 0;
2313                         MsgInfo *msginfo;
2314
2315                         item->cache = msgcache_new();
2316                         folder_item_scan_full(item, TRUE);
2317
2318                         msgcache_read_mark(item->cache, mark_file);
2319
2320                         list = msgcache_get_msg_list(item->cache);
2321                         for (cur = list; cur != NULL; cur = g_slist_next(cur)) {
2322                                 msginfo = cur->data;
2323
2324                                 if (MSG_IS_NEW(msginfo->flags))
2325                                         newcnt++;
2326                                 if (MSG_IS_UNREAD(msginfo->flags))
2327                                         unreadcnt++;
2328                                 if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2329                                         unreadmarkedcnt++;
2330                                 if (MSG_IS_MARKED(msginfo->flags))
2331                                         markedcnt++;
2332                         }
2333                         item->new_msgs = newcnt;
2334                         item->unread_msgs = unreadcnt;
2335                         item->unreadmarked_msgs = unreadmarkedcnt;
2336                         item->marked_msgs = markedcnt;
2337                         procmsg_msg_list_free(list);
2338                 } else
2339                         msgcache_read_mark(item->cache, mark_file);
2340
2341                 msgcache_read_tags(item->cache, tags_file);
2342
2343                 g_free(cache_file);
2344                 g_free(mark_file);
2345                 g_free(tags_file);
2346         } else {
2347                 item->cache = msgcache_new();
2348         }
2349         END_TIMING();
2350         folder_clean_cache_memory(item);
2351 }
2352
2353 void folder_item_write_cache(FolderItem *item)
2354 {
2355         gchar *cache_file, *mark_file, *tags_file;
2356         FolderItemPrefs *prefs;
2357         gint filemode = 0;
2358         gchar *id;
2359         time_t last_mtime = (time_t)0;
2360         gboolean need_scan = FALSE;
2361         
2362         if (!item || !item->path || !item->cache)
2363                 return;
2364
2365         if (FOLDER_TYPE(item->folder) == F_MH) {
2366                 last_mtime = item->mtime;
2367                 need_scan = item->folder->klass->scan_required(item->folder, item);
2368         }
2369
2370         id = folder_item_get_identifier(item);
2371         debug_print("Save cache for folder %s\n", id);
2372         g_free(id);
2373
2374         cache_file = folder_item_get_cache_file(item);
2375         mark_file = folder_item_get_mark_file(item);
2376         tags_file = folder_item_get_tags_file(item);
2377         if (msgcache_write(cache_file, mark_file, tags_file, item->cache) < 0) {
2378                 prefs = item->prefs;
2379                 if (prefs && prefs->enable_folder_chmod && prefs->folder_chmod) {
2380                         /* for cache file */
2381                         filemode = prefs->folder_chmod;
2382                         if (filemode & S_IRGRP) filemode |= S_IWGRP;
2383                         if (filemode & S_IROTH) filemode |= S_IWOTH;
2384                         chmod(cache_file, filemode);
2385                 }
2386         }
2387
2388         if (!need_scan && FOLDER_TYPE(item->folder) == F_MH) {
2389                 if (item->mtime == last_mtime) {
2390                         mh_set_mtime(item);
2391                 }
2392         }
2393
2394         g_free(cache_file);
2395         g_free(mark_file);
2396         g_free(tags_file);
2397 }
2398
2399 MsgInfo *folder_item_get_msginfo(FolderItem *item, gint num)
2400 {
2401         Folder *folder;
2402         MsgInfo *msginfo = NULL;
2403         
2404         g_return_val_if_fail(item != NULL, NULL);
2405         if (item->no_select)
2406                 return NULL;
2407         folder = item->folder;
2408         if (!item->cache)
2409                 folder_item_read_cache(item);
2410         
2411         if ((msginfo = msgcache_get_msg(item->cache, num)) != NULL)
2412                 return msginfo;
2413         
2414         msginfo = get_msginfo(item, num);
2415         if (msginfo != NULL) {
2416                 msgcache_add_msg(item->cache, msginfo);
2417                 return msginfo;
2418         }
2419         
2420         return NULL;
2421 }
2422
2423 MsgInfo *folder_item_get_msginfo_by_msgid(FolderItem *item, const gchar *msgid)
2424 {
2425         Folder *folder;
2426         MsgInfo *msginfo;
2427         
2428         g_return_val_if_fail(item != NULL, NULL);
2429         g_return_val_if_fail(msgid != NULL, NULL);
2430         if (item->no_select)
2431                 return FALSE;
2432         
2433         folder = item->folder;
2434         if (!item->cache)
2435                 folder_item_read_cache(item);
2436         
2437         if ((msginfo = msgcache_get_msg_by_id(item->cache, msgid)) != NULL)
2438                 return msginfo;
2439
2440         return NULL;
2441 }
2442
2443 GSList *folder_item_get_msg_list(FolderItem *item)
2444 {
2445         g_return_val_if_fail(item != NULL, NULL);
2446         if (item->no_select)
2447                 return FALSE;
2448         
2449         if (item->cache == 0)
2450                 folder_item_read_cache(item);
2451
2452         g_return_val_if_fail(item->cache != NULL, NULL);
2453         
2454         return msgcache_get_msg_list(item->cache);
2455 }
2456
2457 static void msginfo_set_mime_flags(GNode *node, gpointer data)
2458 {
2459         MsgInfo *msginfo = data;
2460         MimeInfo *mimeinfo = node->data;
2461         
2462         if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT
2463          && (!mimeinfo->subtype ||  strcmp(mimeinfo->subtype, "pgp-signature"))) {
2464                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2465         } else if (mimeinfo->disposition == DISPOSITIONTYPE_UNKNOWN && 
2466                  mimeinfo->type != MIMETYPE_TEXT &&
2467                  mimeinfo->type != MIMETYPE_MULTIPART) {
2468                 if (!mimeinfo->subtype 
2469                 ||  strcmp(mimeinfo->subtype, "pgp-signature"))
2470                         procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2471         } else if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE &&
2472                 strcmp(mimeinfo->subtype, "pgp-signature") && 
2473                 (procmime_mimeinfo_get_parameter(mimeinfo, "name") != NULL ||
2474                  procmime_mimeinfo_get_parameter(mimeinfo, "filename") != NULL)) {
2475                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2476         } 
2477
2478         /* don't descend below top level message for signed and encrypted info */
2479         if (mimeinfo->type == MIMETYPE_MESSAGE)
2480                 return;
2481
2482         if (privacy_mimeinfo_is_signed(mimeinfo)) {
2483                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
2484         }
2485
2486         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
2487                 procmsg_msginfo_set_flags(msginfo, 0, MSG_ENCRYPTED);
2488         } else {
2489                 /* searching inside encrypted parts doesn't really make sense */
2490                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2491         }
2492 }
2493
2494 gchar *folder_item_fetch_msg(FolderItem *item, gint num)
2495 {
2496         Folder *folder;
2497         gchar *msgfile;
2498         MsgInfo *msginfo;
2499
2500         g_return_val_if_fail(item != NULL, NULL);
2501
2502         folder = item->folder;
2503
2504         g_return_val_if_fail(folder->klass->fetch_msg != NULL, NULL);
2505         if (item->no_select)
2506                 return NULL;
2507
2508         msgfile = folder->klass->fetch_msg(folder, item, num);
2509
2510         if (msgfile != NULL) {
2511                 msginfo = folder_item_get_msginfo(item, num);
2512                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2513                         MimeInfo *mimeinfo;
2514
2515                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) && 
2516                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2517                                 mimeinfo = procmime_scan_file(msgfile);
2518                         else
2519                                 mimeinfo = procmime_scan_queue_file(msgfile);
2520                         /* check for attachments */
2521                         if (mimeinfo != NULL) { 
2522                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2523                                 procmime_mimeinfo_free_all(mimeinfo);
2524
2525                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2526                         }
2527                 }
2528                 procmsg_msginfo_free(msginfo);
2529         }
2530
2531         return msgfile;
2532 }
2533
2534 gchar *folder_item_fetch_msg_full(FolderItem *item, gint num, gboolean headers,
2535                                   gboolean body)
2536 {
2537         Folder *folder;
2538         gchar *msgfile;
2539         MsgInfo *msginfo;
2540
2541         g_return_val_if_fail(item != NULL, NULL);
2542         if (item->no_select)
2543                 return NULL;
2544         
2545         folder = item->folder;
2546
2547         if (folder->klass->fetch_msg_full == NULL)
2548                 return folder_item_fetch_msg(item, num);
2549
2550         if (item->prefs->offlinesync && prefs_common.real_time_sync)
2551                 msgfile = folder->klass->fetch_msg_full(folder, item, num, 
2552                                                 TRUE, TRUE);
2553         else
2554                 msgfile = folder->klass->fetch_msg_full(folder, item, num, 
2555                                                 headers, body);
2556
2557         if (msgfile != NULL) {
2558                 msginfo = folder_item_get_msginfo(item, num);
2559                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2560                         MimeInfo *mimeinfo;
2561
2562                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
2563                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2564                                 mimeinfo = procmime_scan_file(msgfile);
2565                         else
2566                                 mimeinfo = procmime_scan_queue_file(msgfile);
2567                         /* check for attachments */
2568                         if (mimeinfo != NULL) { 
2569                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2570                                 procmime_mimeinfo_free_all(mimeinfo);
2571
2572                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2573                         }
2574                 }
2575                 procmsg_msginfo_free(msginfo);
2576         }
2577
2578         return msgfile;
2579 }
2580
2581
2582 gint folder_item_fetch_all_msg(FolderItem *item)
2583 {
2584         Folder *folder;
2585         GSList *mlist;
2586         GSList *cur;
2587         gint num = 0;
2588         gint ret = 0;
2589         gint total = 0;
2590
2591         g_return_val_if_fail(item != NULL, -1);
2592         if (item->no_select)
2593                 return -1;
2594
2595         debug_print("fetching all messages in %s ...\n", item->path ? item->path : "(null)");
2596         statusbar_print_all(_("Fetching all messages in %s ...\n"), item->path ? item->path : "(null)");
2597
2598         folder = item->folder;
2599
2600         if (folder->ui_func)
2601                 folder->ui_func(folder, item, folder->ui_func_data ?
2602                                 folder->ui_func_data : GINT_TO_POINTER(num));
2603
2604         mlist = folder_item_get_msg_list(item);
2605
2606         total = g_slist_length(mlist);
2607
2608         for (cur = mlist; cur != NULL; cur = cur->next) {
2609                 MsgInfo *msginfo = (MsgInfo *)cur->data;
2610                 gchar *msg;
2611
2612                 statusbar_progress_all(num++,total, 10);
2613
2614                 if (folder->ui_func)
2615                         folder->ui_func(folder, item,
2616                                         folder->ui_func_data ?
2617                                         folder->ui_func_data :
2618                                         GINT_TO_POINTER(num));
2619                 if (num % 50 == 0)
2620                         GTK_EVENTS_FLUSH();
2621
2622                 msg = folder_item_fetch_msg(item, msginfo->msgnum);
2623                 if (!msg) {
2624                         g_warning("Can't fetch message %d. Aborting.\n",
2625                                   msginfo->msgnum);
2626                         ret = -1;
2627                         break;
2628                 }
2629                 g_free(msg);
2630         }
2631         
2632         statusbar_progress_all(0,0,0);
2633         statusbar_pop_all();
2634         procmsg_msg_list_free(mlist);
2635
2636         return ret;
2637 }
2638
2639 static gint folder_item_get_msg_num_by_file(FolderItem *dest, const gchar *file)
2640 {
2641         static HeaderEntry hentry[] = {{"Message-ID:",  NULL, TRUE},
2642                                        {NULL,           NULL, FALSE}};
2643         FILE *fp;
2644         MsgInfo *msginfo;
2645         gint msgnum = 0;
2646         gchar buf[BUFFSIZE];
2647
2648         if ((fp = g_fopen(file, "rb")) == NULL)
2649                 return 0;
2650
2651         if ((folder_has_parent_of_type(dest, F_QUEUE)) || 
2652             (folder_has_parent_of_type(dest, F_DRAFT)))
2653                 while (fgets(buf, sizeof(buf), fp) != NULL)
2654                         if (buf[0] == '\r' || buf[0] == '\n') break;
2655
2656         procheader_get_header_fields(fp, hentry);
2657         if (hentry[0].body) {
2658                 extract_parenthesis(hentry[0].body, '<', '>');
2659                 remove_space(hentry[0].body);
2660                 if ((msginfo = msgcache_get_msg_by_id(dest->cache, hentry[0].body)) != NULL) {
2661                         msgnum = msginfo->msgnum;
2662                         procmsg_msginfo_free(msginfo);
2663
2664                         debug_print("found message as uid %d\n", msgnum);
2665                 }
2666         }
2667         
2668         g_free(hentry[0].body);
2669         hentry[0].body = NULL;
2670         fclose(fp);
2671
2672         return msgnum;
2673 }
2674
2675 static void copy_msginfo_flags(MsgInfo *source, MsgInfo *dest)
2676 {
2677         MsgPermFlags perm_flags = 0;
2678         MsgTmpFlags tmp_flags = 0;
2679
2680         /* create new flags */
2681         if (source != NULL) {
2682                 /* copy original flags */
2683                 perm_flags = source->flags.perm_flags;
2684                 tmp_flags = source->flags.tmp_flags;
2685         } else {
2686                 perm_flags = dest->flags.perm_flags;
2687                 tmp_flags = dest->flags.tmp_flags;
2688         }
2689
2690         /* remove new, unread and deleted in special folders */
2691         if (folder_has_parent_of_type(dest->folder, F_OUTBOX) || 
2692             folder_has_parent_of_type(dest->folder, F_QUEUE) || 
2693             folder_has_parent_of_type(dest->folder, F_DRAFT) || 
2694             folder_has_parent_of_type(dest->folder, F_TRASH))
2695                 perm_flags &= ~(MSG_NEW | MSG_UNREAD | MSG_DELETED);
2696
2697         /* set ignore flag of ignored parent exists */
2698         if (procmsg_msg_has_flagged_parent(dest, MSG_IGNORE_THREAD))
2699                 perm_flags |= MSG_IGNORE_THREAD;
2700
2701         /* Unset tmp flags that should not be copied */
2702         tmp_flags &= ~(MSG_MOVE | MSG_COPY | MSG_MOVE_DONE);
2703
2704         /* unset flags that are set but should not */
2705         /* and set new flags */
2706         procmsg_msginfo_change_flags(dest,
2707                                   ~dest->flags.perm_flags & perm_flags,
2708                                   ~dest->flags.tmp_flags  & tmp_flags,
2709                                    dest->flags.perm_flags & ~perm_flags,
2710                                    dest->flags.tmp_flags  & ~tmp_flags);
2711         
2712         if (source && source->tags) {
2713                 g_slist_free(dest->tags);
2714                 dest->tags = g_slist_copy(source->tags);
2715         }
2716 }
2717
2718 static void add_msginfo_to_cache(FolderItem *item, MsgInfo *newmsginfo, MsgInfo *flagsource)
2719 {
2720         /* update folder stats */
2721         if (MSG_IS_NEW(newmsginfo->flags))
2722                 item->new_msgs++;
2723         if (MSG_IS_UNREAD(newmsginfo->flags))
2724                 item->unread_msgs++;
2725         if (MSG_IS_UNREAD(newmsginfo->flags) && procmsg_msg_has_marked_parent(newmsginfo))
2726                 item->unreadmarked_msgs++;
2727         if (MSG_IS_MARKED(newmsginfo->flags))
2728                 item->marked_msgs++;
2729         item->total_msgs++;
2730
2731         folder_item_update_freeze();
2732
2733         if (!item->cache)
2734                 folder_item_read_cache(item);
2735
2736         msgcache_add_msg(item->cache, newmsginfo);
2737         copy_msginfo_flags(flagsource, newmsginfo);
2738         folder_item_update_with_msg(item,  F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_ADDMSG, newmsginfo);
2739         folder_item_update_thaw();
2740 }
2741
2742 static void remove_msginfo_from_cache(FolderItem *item, MsgInfo *msginfo)
2743 {
2744         MsgInfoUpdate msginfo_update;
2745
2746         if (!item->cache)
2747                 folder_item_read_cache(item);
2748
2749         if (MSG_IS_NEW(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
2750                 msginfo->folder->new_msgs--;
2751         if (MSG_IS_UNREAD(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
2752                 msginfo->folder->unread_msgs--;
2753         if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2754                 msginfo->folder->unreadmarked_msgs--;
2755         if (MSG_IS_MARKED(msginfo->flags))
2756                 item->marked_msgs--;
2757
2758         msginfo->folder->total_msgs--;
2759
2760         msginfo_update.msginfo = msginfo;
2761         msginfo_update.flags = MSGINFO_UPDATE_DELETED;
2762         hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
2763
2764         msgcache_remove_msg(item->cache, msginfo->msgnum);
2765         folder_item_update_with_msg(msginfo->folder, F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_REMOVEMSG, msginfo);
2766 }
2767
2768 gint folder_item_add_msg(FolderItem *dest, const gchar *file,
2769                          MsgFlags *flags, gboolean remove_source)
2770 {
2771         GSList file_list;
2772         MsgFileInfo fileinfo;
2773
2774         g_return_val_if_fail(dest != NULL, -1);
2775         g_return_val_if_fail(file != NULL, -1);
2776  
2777         fileinfo.msginfo = NULL;
2778         fileinfo.file = (gchar *)file;
2779         fileinfo.flags = flags;
2780         file_list.data = &fileinfo;
2781         file_list.next = NULL;
2782
2783         return folder_item_add_msgs(dest, &file_list, remove_source);
2784 }
2785
2786 gint folder_item_add_msgs(FolderItem *dest, GSList *file_list,
2787                           gboolean remove_source)
2788 {
2789         Folder *folder;
2790         gint ret, num, lastnum = -1;
2791         GSList *file_cur;
2792         GRelation *relation;
2793         MsgFileInfo *fileinfo = NULL;
2794         gboolean folderscan = FALSE;
2795
2796         g_return_val_if_fail(dest != NULL, -1);
2797         g_return_val_if_fail(file_list != NULL, -1);
2798         g_return_val_if_fail(dest->folder != NULL, -1);
2799         if (dest->no_select)
2800                 return -1;
2801
2802         folder = dest->folder;
2803
2804         relation = g_relation_new(2);
2805         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
2806
2807         if (folder->klass->add_msgs != NULL) {
2808                 ret = folder->klass->add_msgs(folder, dest, file_list, relation);
2809                 if (ret < 0) {
2810                         g_relation_destroy(relation);
2811                         return ret;
2812                 }
2813         } else {
2814                 for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
2815                         fileinfo = (MsgFileInfo *) file_cur->data;
2816
2817                         ret = folder->klass->add_msg(folder, dest, fileinfo->file, fileinfo->flags);
2818                         if (ret < 0) {
2819                                 g_relation_destroy(relation);
2820                                 return ret;
2821                         }
2822                         g_relation_insert(relation, fileinfo, GINT_TO_POINTER(ret));
2823                 }
2824         }
2825
2826         for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
2827                 GTuples *tuples;
2828
2829                 fileinfo = (MsgFileInfo *) file_cur->data;
2830                 tuples = g_relation_select(relation, fileinfo, 0);
2831                 num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
2832                 g_tuples_destroy(tuples);
2833
2834                 if (num >= 0) {
2835                         MsgInfo *newmsginfo;
2836
2837                         if (num == 0) {
2838                                 if (!folderscan) {
2839                                         folder_item_scan_full(dest, FALSE);
2840                                         folderscan = TRUE;
2841                                 }
2842                                 num = folder_item_get_msg_num_by_file(dest, fileinfo->file);
2843                         }
2844
2845                         if (num > lastnum)
2846                                 lastnum = num;
2847
2848                         if (num >= 0 && remove_source) {
2849                                 if (g_unlink(fileinfo->file) < 0)
2850                                         FILE_OP_ERROR(fileinfo->file, "unlink");
2851                         }
2852
2853                         if (num == 0)
2854                                 continue;
2855
2856                         if (!folderscan && 
2857                             ((newmsginfo = get_msginfo(dest, num)) != NULL)) {
2858                                 add_msginfo_to_cache(dest, newmsginfo, NULL);
2859                                 procmsg_msginfo_free(newmsginfo);
2860                         } else if ((newmsginfo = msgcache_get_msg(dest->cache, num)) != NULL) {
2861                                 /* TODO: set default flags */
2862                                 procmsg_msginfo_free(newmsginfo);
2863                         }
2864                 }
2865         }
2866
2867         g_relation_destroy(relation);
2868
2869         return lastnum;
2870 }
2871
2872 static FolderItem *folder_item_move_recursive(FolderItem *src, FolderItem *dest, gboolean copy) 
2873 {
2874         GSList *mlist;
2875         FolderItem *new_item;
2876         FolderItem *next_item;
2877         GNode *srcnode;
2878         gchar *old_id, *new_id;
2879
2880         /* move messages */
2881         debug_print("%s %s to %s\n", copy?"Copying":"Moving", src->path, dest->path);
2882         new_item = folder_create_folder(dest, src->name);
2883         if (new_item == NULL) {
2884                 printf("Can't create folder\n");
2885                 return NULL;
2886         }
2887         
2888         if (new_item->folder == NULL)
2889                 new_item->folder = dest->folder;
2890
2891         /* move messages */
2892         log_message(LOG_PROTOCOL, copy ?_("Copying %s to %s...\n"):_("Moving %s to %s...\n"), 
2893                         src->name, new_item->path);
2894
2895         mlist = folder_item_get_msg_list(src);
2896         
2897         if (mlist != NULL) {
2898                 if (copy)
2899                         folder_item_copy_msgs(new_item, mlist);
2900                 else
2901                         folder_item_move_msgs(new_item, mlist);
2902                 procmsg_msg_list_free(mlist);
2903         }
2904         
2905         /*copy prefs*/
2906         folder_item_prefs_copy_prefs(src, new_item);
2907         
2908         /* copy internal data */
2909         if (src->folder->klass == new_item->folder->klass &&
2910             src->folder->klass->copy_private_data != NULL)
2911                 src->folder->klass->copy_private_data(src->folder,
2912                                         src, new_item);
2913         new_item->collapsed = src->collapsed;
2914         new_item->thread_collapsed = src->thread_collapsed;
2915         new_item->threaded  = src->threaded;
2916         new_item->ret_rcpt  = src->ret_rcpt;
2917         new_item->hide_read_msgs = src->hide_read_msgs;
2918         new_item->sort_key  = src->sort_key;
2919         new_item->sort_type = src->sort_type;
2920
2921         prefs_matcher_write_config();
2922         
2923         /* recurse */
2924         srcnode = src->folder->node;    
2925         srcnode = g_node_find(srcnode, G_PRE_ORDER, G_TRAVERSE_ALL, src);
2926         srcnode = srcnode->children;
2927         while (srcnode != NULL) {
2928                 if (srcnode && srcnode->data) {
2929                         next_item = (FolderItem*) srcnode->data;
2930                         srcnode = srcnode->next;
2931                         if (folder_item_move_recursive(next_item, new_item, copy) == NULL) {
2932                                 return NULL;
2933                         }
2934                 }
2935         }
2936         old_id = folder_item_get_identifier(src);
2937         new_id = folder_item_get_identifier(new_item);
2938
2939         /* if src supports removing, otherwise only copy folder */
2940         if (src->folder->klass->remove_folder != NULL && !copy) 
2941                 src->folder->klass->remove_folder(src->folder, src);
2942         folder_write_list();
2943
2944         if (!copy) {
2945                 debug_print("updating rules : %s => %s\n", old_id, new_id);
2946                 if (old_id != NULL && new_id != NULL) {
2947                         prefs_filtering_rename_path(old_id, new_id);
2948                         account_rename_path(old_id, new_id);
2949                 }
2950         }
2951         g_free(old_id);
2952         g_free(new_id);
2953         
2954         return new_item;
2955 }
2956
2957 gint folder_item_move_to(FolderItem *src, FolderItem *dest, FolderItem **new_item, gboolean copy)
2958 {
2959         FolderItem *tmp = folder_item_parent(dest);
2960         gchar * src_identifier, * dst_identifier;
2961         gchar * phys_srcpath, * phys_dstpath, *tmppath;
2962
2963         while (tmp) {
2964                 if (tmp == src) {
2965                         return F_MOVE_FAILED_DEST_IS_CHILD;
2966                 }
2967                 tmp = folder_item_parent(tmp);
2968         }
2969         
2970         tmp = folder_item_parent(src);
2971         
2972         src_identifier = folder_item_get_identifier(src);
2973         dst_identifier = folder_item_get_identifier(dest);
2974         
2975         if(dst_identifier == NULL && dest->folder && folder_item_parent(dest) == NULL) {
2976                 /* dest can be a root folder */
2977                 dst_identifier = folder_get_identifier(dest->folder);
2978         }
2979         if (src_identifier == NULL || dst_identifier == NULL) {
2980                 debug_print("Can't get identifiers\n");
2981                 return F_MOVE_FAILED;
2982         }
2983
2984         if (src->folder != dest->folder && !copy) {
2985                 return F_MOVE_FAILED_DEST_OUTSIDE_MAILBOX;
2986         }
2987
2988         phys_srcpath = folder_item_get_path(src);
2989         tmppath = folder_item_get_path(dest);
2990         phys_dstpath = g_strconcat(tmppath,
2991                        G_DIR_SEPARATOR_S,
2992                        g_path_get_basename(phys_srcpath),
2993                        NULL);
2994         g_free(tmppath);
2995
2996         if (folder_item_parent(src) == dest || src == dest) {
2997                 g_free(src_identifier);
2998                 g_free(dst_identifier);
2999                 g_free(phys_srcpath);
3000                 g_free(phys_dstpath);
3001                 return F_MOVE_FAILED_DEST_IS_PARENT;
3002         }
3003         debug_print("moving \"%s\" to \"%s\"\n", phys_srcpath, phys_dstpath);
3004         if ((tmp = folder_item_move_recursive(src, dest, copy)) == NULL) {
3005                 return F_MOVE_FAILED;
3006         }
3007         
3008         g_free(src_identifier);
3009         g_free(dst_identifier);
3010         g_free(phys_srcpath);
3011         g_free(phys_dstpath);
3012
3013         *new_item = tmp;
3014
3015         return F_MOVE_OK;
3016 }
3017
3018 /**
3019  * Copy a list of message to a new folder and remove
3020  * source messages if wanted
3021  */
3022 static gint do_copy_msgs(FolderItem *dest, GSList *msglist, gboolean remove_source)
3023 {
3024         Folder *folder;
3025         GSList *l;
3026         gint num, lastnum = -1;
3027         gboolean folderscan = FALSE;
3028         GRelation *relation;
3029         GSList *not_moved = NULL;
3030         gint total = 0, curmsg = 0;
3031         MsgInfo *msginfo = NULL;
3032
3033         g_return_val_if_fail(dest != NULL, -1);
3034         g_return_val_if_fail(msglist != NULL, -1);
3035
3036         folder = dest->folder;
3037
3038         g_return_val_if_fail(folder->klass->copy_msg != NULL, -1);
3039         if (dest->no_select)
3040                 return -1;
3041
3042         msginfo = (MsgInfo *)msglist->data;
3043         
3044         if (!msginfo)
3045                 return -1;
3046         
3047         if (!MSG_IS_QUEUED(msginfo->flags) && 
3048             MSG_IS_DRAFT(msginfo->flags) && 
3049             folder_has_parent_of_type(dest, F_QUEUE)) {
3050                 GSList *cur = msglist;
3051                 gboolean queue_err = FALSE;
3052                 for (; cur; cur = cur->next) {
3053                         Compose *compose = NULL;
3054                         FolderItem *queue = dest;
3055                         int val = 0;
3056                         
3057                         msginfo = (MsgInfo *)cur->data;
3058                         compose = compose_reedit(msginfo, TRUE);
3059                         if (compose == NULL) {
3060                                 queue_err = TRUE;
3061                                 continue;
3062                         }
3063                         val = compose_queue(compose, NULL, &queue, NULL,
3064                                         FALSE);
3065                         if (val < 0) {
3066                                 queue_err = TRUE;
3067                         } else if (remove_source) {
3068                                 folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
3069                         }
3070                         if (val == 0)
3071                                 compose_close(compose);
3072                 }
3073                 return queue_err ? -1:0;
3074         }
3075
3076         relation = g_relation_new(2);
3077         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
3078         g_relation_index(relation, 1, g_direct_hash, g_direct_equal);
3079
3080         for (l = msglist ; l != NULL ; l = g_slist_next(l)) {
3081                 MsgInfo * msginfo = (MsgInfo *) l->data;
3082
3083                 if (msginfo->planned_download != 0) {
3084                         int old_planned = msginfo->planned_download;
3085                         partial_unmark(msginfo);
3086                         /* little hack to reenable after */
3087                         msginfo->planned_download = old_planned;
3088                 }
3089         }
3090
3091         /* 
3092          * Copy messages to destination folder and 
3093          * store new message numbers in newmsgnums
3094          */
3095         if (folder->klass->copy_msgs != NULL) {
3096                 if (folder->klass->copy_msgs(folder, dest, msglist, relation) < 0) {
3097                         g_relation_destroy(relation);
3098                         return -1;
3099                 }
3100         } else {
3101                 MsgInfo * msginfo;
3102                 l = msglist;
3103
3104                 /* immediately stop if src and dest folders are identical */
3105                 if (l != NULL) {
3106                         msginfo = (MsgInfo *) l->data;
3107                         if (msginfo != NULL && msginfo->folder == dest) {
3108                                 g_relation_destroy(relation);
3109                                 return -1;
3110                         }
3111                 }
3112
3113                 for (; l != NULL ; l = g_slist_next(l)) {
3114                         msginfo = (MsgInfo *) l->data;
3115
3116                         num = folder->klass->copy_msg(folder, dest, msginfo);
3117                         if (num > 0)
3118                                 g_relation_insert(relation, msginfo, GINT_TO_POINTER(num));
3119                         else
3120                                 not_moved = g_slist_prepend(not_moved, msginfo);
3121                 }
3122         }
3123
3124         if (remove_source) {
3125                 MsgInfo *msginfo = (MsgInfo *) msglist->data;
3126                 FolderItem *item = msginfo->folder;
3127                 /*
3128                  * Remove source messages from their folders if
3129                  * copying was successfull and update folder
3130                  * message counts
3131                  */
3132                 if (not_moved == NULL && item->folder->klass->remove_msgs) {
3133                         item->folder->klass->remove_msgs(item->folder,
3134                                                                 msginfo->folder,
3135                                                                 msglist,
3136                                                                 relation);
3137                 }
3138                 for (l = msglist; l != NULL; l = g_slist_next(l)) {
3139                         GTuples *tuples;
3140                         msginfo = (MsgInfo *) l->data;
3141                         item = msginfo->folder;
3142
3143                         tuples = g_relation_select(relation, msginfo, 0);
3144                         if (tuples) {
3145                                 if (tuples->len)
3146                                         num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
3147                                 else
3148                                         num = 0;
3149                                 g_tuples_destroy(tuples);
3150                         } else {
3151                                 num = -1;
3152                         }
3153
3154                         if (g_slist_find(not_moved, msginfo))
3155                                 continue;
3156
3157                         if ((num >= 0) && (item->folder->klass->remove_msg != NULL)) {
3158                                 if (!item->folder->klass->remove_msgs)
3159                                         item->folder->klass->remove_msg(item->folder,
3160                                                                 msginfo->folder,
3161                                                                 msginfo->msgnum);
3162                                 remove_msginfo_from_cache(item, msginfo);
3163                         }
3164                 }
3165         }
3166
3167         /* Read cache for dest folder */
3168         if (!dest->cache) folder_item_read_cache(dest);
3169
3170         /* 
3171          * Fetch new MsgInfos for new messages in dest folder,
3172          * add them to the msgcache and update folder message counts
3173          */
3174         if (g_relation_count(relation, GINT_TO_POINTER(0), 1) > 0) {
3175                 folder_item_scan_full(dest, FALSE);
3176                 folderscan = TRUE;
3177         }
3178
3179         statusbar_print_all(_("Updating cache for %s..."), dest->path ? dest->path : "(null)");
3180         total = g_slist_length(msglist);
3181         for (l = msglist; l != NULL; l = g_slist_next(l)) {
3182                 MsgInfo *msginfo = (MsgInfo *) l->data;
3183                 GTuples *tuples;
3184
3185                 tuples = g_relation_select(relation, msginfo, 0);
3186                 if (tuples->len > 0) {
3187                         num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
3188                         g_tuples_destroy(tuples);
3189                 } else {
3190                         num = 0;
3191                         if (tuples)
3192                                 g_tuples_destroy(tuples);
3193                 }
3194                 statusbar_progress_all(curmsg++,total, 100);
3195                 if (curmsg % 100 == 0)
3196                         GTK_EVENTS_FLUSH();
3197
3198                 if (num >= 0) {
3199                         MsgInfo *newmsginfo = NULL;
3200
3201                         if (!folderscan && num > 0) {
3202                                 newmsginfo = get_msginfo(dest, num);
3203                                 if (newmsginfo != NULL) {
3204                                         add_msginfo_to_cache(dest, newmsginfo, msginfo);
3205                                 }
3206                         }
3207                         if (newmsginfo == NULL) {
3208                                 if (!folderscan) {
3209                                         folder_item_scan_full(dest, FALSE);
3210                                         folderscan = TRUE;
3211                                 }
3212                                 if (msginfo->msgid != NULL) {
3213                                         newmsginfo = folder_item_get_msginfo_by_msgid(dest, msginfo->msgid);
3214                                         if (newmsginfo != NULL) {
3215                                                 copy_msginfo_flags(msginfo, newmsginfo);
3216                                                 num = newmsginfo->msgnum;
3217                                         }
3218                                 }
3219                         }
3220
3221                         if (msginfo->planned_download 
3222                             == POP3_PARTIAL_DLOAD_DELE) {
3223                                 partial_mark_for_delete(newmsginfo);
3224                         }
3225                         if (msginfo->planned_download 
3226                             == POP3_PARTIAL_DLOAD_DLOAD) {
3227                                 partial_mark_for_download(newmsginfo);
3228                         }
3229                         if (!MSG_IS_POSTFILTERED (msginfo->flags)) {
3230                             procmsg_msginfo_set_flags (   msginfo, MSG_POSTFILTERED, 0);
3231                             procmsg_msginfo_set_flags (newmsginfo, MSG_POSTFILTERED, 0);
3232                             hooks_invoke (MAIL_POSTFILTERING_HOOKLIST, newmsginfo);
3233                         }
3234                         procmsg_msginfo_free(newmsginfo);
3235
3236
3237                         if (num > lastnum)
3238                                 lastnum = num;
3239                 }
3240         }
3241         statusbar_progress_all(0,0,0);
3242         statusbar_pop_all();
3243
3244         g_relation_destroy(relation);
3245         if (not_moved != NULL) {
3246                 g_slist_free(not_moved);
3247                 return -1;
3248         } else
3249                 return lastnum;
3250 }
3251
3252 /**
3253  * Move a message to a new folder.
3254  *
3255  * \param dest Destination folder
3256  * \param msginfo The message
3257  */
3258 gint folder_item_move_msg(FolderItem *dest, MsgInfo *msginfo)
3259 {
3260         GSList list;
3261
3262         g_return_val_if_fail(dest != NULL, -1);
3263         g_return_val_if_fail(msginfo != NULL, -1);
3264
3265         list.data = msginfo;
3266         list.next = NULL;
3267
3268         return do_copy_msgs(dest, &list, TRUE);
3269 }
3270
3271 /**
3272  * Move a list of messages to a new folder.
3273  *
3274  * \param dest Destination folder
3275  * \param msglist List of messages
3276  */
3277 gint folder_item_move_msgs(FolderItem *dest, GSList *msglist)
3278 {
3279         gint result = -1;
3280         g_return_val_if_fail(dest != NULL, -1);
3281         g_return_val_if_fail(msglist != NULL, -1);
3282         inc_lock();
3283         result = do_copy_msgs(dest, msglist, TRUE);
3284         inc_unlock();
3285         return result;
3286 }
3287
3288 /**
3289  * Copy a message to a new folder.
3290  *
3291  * \param dest Destination folder
3292  * \param msginfo The message
3293  */
3294 gint folder_item_copy_msg(FolderItem *dest, MsgInfo *msginfo)
3295 {
3296         GSList list;
3297
3298         g_return_val_if_fail(dest != NULL, -1);
3299         g_return_val_if_fail(msginfo != NULL, -1);
3300     
3301         list.data = msginfo;
3302         list.next = NULL;
3303
3304         return do_copy_msgs(dest, &list, FALSE);
3305 }
3306
3307 /**
3308  * Copy a list of messages to a new folder.
3309  *
3310  * \param dest Destination folder
3311  * \param msglist List of messages
3312  */
3313 gint folder_item_copy_msgs(FolderItem *dest, GSList *msglist)
3314 {
3315         gint result;
3316         g_return_val_if_fail(dest != NULL, -1);
3317         g_return_val_if_fail(msglist != NULL, -1);
3318
3319         inc_lock();
3320         result = do_copy_msgs(dest, msglist, FALSE);
3321         inc_unlock();
3322         
3323         return result;
3324 }
3325
3326 gint folder_item_remove_msg(FolderItem *item, gint num)
3327 {
3328         Folder *folder;
3329         gint ret;
3330         MsgInfo *msginfo;
3331
3332         g_return_val_if_fail(item != NULL, -1);
3333         folder = item->folder;
3334         g_return_val_if_fail(folder->klass->remove_msg != NULL, -1);
3335         if (item->no_select)
3336                 return -1;
3337
3338         if (!item->cache) folder_item_read_cache(item);
3339
3340         ret = folder->klass->remove_msg(folder, item, num);
3341
3342         msginfo = msgcache_get_msg(item->cache, num);
3343         if (msginfo != NULL) {
3344                 remove_msginfo_from_cache(item, msginfo);
3345                 procmsg_msginfo_free(msginfo);
3346         }
3347
3348         return ret;
3349 }
3350
3351 gint folder_item_remove_msgs(FolderItem *item, GSList *msglist)
3352 {
3353         Folder *folder;
3354         gint ret = 0;
3355
3356         g_return_val_if_fail(item != NULL, -1);
3357         folder = item->folder;
3358         g_return_val_if_fail(folder != NULL, -1);
3359         if (item->no_select)
3360                 return -1;
3361         inc_lock();
3362         if (!item->cache) folder_item_read_cache(item);
3363
3364         folder_item_update_freeze();
3365         if (item->folder->klass->remove_msgs) {
3366                 ret = item->folder->klass->remove_msgs(item->folder,
3367                                                         item,
3368                                                         msglist,
3369                                                         NULL);
3370         }
3371         while (ret == 0 && msglist != NULL) {
3372                 MsgInfo *msginfo = (MsgInfo *)msglist->data;
3373                 if (MSG_IS_LOCKED(msginfo->flags)) {
3374                         msglist = msglist->next;
3375                         continue;
3376                 }
3377                 if (!item->folder->klass->remove_msgs)
3378                         ret = folder_item_remove_msg(item, msginfo->msgnum);
3379                 if (ret != 0) break;
3380                 msgcache_remove_msg(item->cache, msginfo->msgnum);
3381                 msglist = msglist->next;
3382         }
3383         folder_item_scan_full(item, FALSE);
3384         folder_item_update_thaw();
3385         inc_unlock();
3386         return ret;
3387 }
3388
3389 gint folder_item_remove_all_msg(FolderItem *item)
3390 {
3391         Folder *folder;
3392         gint result;
3393
3394         g_return_val_if_fail(item != NULL, -1);
3395         if (item->no_select)
3396                 return -1;
3397
3398         folder = item->folder;
3399
3400         inc_lock();
3401         if (folder->klass->remove_all_msg != NULL) {
3402                 result = folder->klass->remove_all_msg(folder, item);
3403
3404                 if (result == 0) {
3405                         folder_item_free_cache(item, TRUE);
3406                         item->cache = msgcache_new();
3407                 }
3408         } else {
3409                 MsgInfoList *msglist;
3410
3411                 msglist = folder_item_get_msg_list(item);
3412                 result = folder_item_remove_msgs(item, msglist);
3413                 procmsg_msg_list_free(msglist);
3414         }
3415
3416         if (result == 0) {
3417                 item->new_msgs = 0;
3418                 item->unread_msgs = 0;
3419                 item->unreadmarked_msgs = 0;
3420                 item->marked_msgs = 0;
3421                 item->total_msgs = 0;
3422                 folder_item_update(item, F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT);
3423         }
3424
3425         inc_unlock();
3426         return result;
3427 }
3428
3429 void folder_item_change_msg_flags(FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
3430 {
3431         g_return_if_fail(item != NULL);
3432         g_return_if_fail(msginfo != NULL);
3433         if (item->no_select)
3434                 return;
3435         
3436         if (item->folder->klass->change_flags != NULL) {
3437                 item->folder->klass->change_flags(item->folder, item, msginfo, newflags);
3438         } else {
3439                 msginfo->flags.perm_flags = newflags;
3440         }
3441 }
3442
3443 gboolean folder_item_is_msg_changed(FolderItem *item, MsgInfo *msginfo)
3444 {
3445         Folder *folder;
3446
3447         g_return_val_if_fail(item != NULL, FALSE);
3448         if (item->no_select)
3449                 return FALSE;
3450
3451         folder = item->folder;
3452
3453         g_return_val_if_fail(folder->klass->is_msg_changed != NULL, -1);
3454
3455         return folder->klass->is_msg_changed(folder, item, msginfo);
3456 }
3457
3458 static gchar *folder_item_get_cache_file(FolderItem *item)
3459 {
3460         gchar *path;
3461         gchar *file;
3462         gchar *old_file;
3463
3464         g_return_val_if_fail(item != NULL, NULL);
3465         g_return_val_if_fail(item->path != NULL, NULL);
3466
3467         path = folder_item_get_path(item);
3468         g_return_val_if_fail(path != NULL, NULL);
3469         if (!is_dir_exist(path))
3470                 make_dir_hier(path);
3471         file = g_strconcat(path, G_DIR_SEPARATOR_S, CACHE_FILE, NULL);
3472         old_file = g_strconcat(path, G_DIR_SEPARATOR_S, OLD_CACHE_FILE, NULL);
3473
3474         if (!is_file_exist(file) && is_file_exist(old_file))
3475                 move_file(old_file, file, FALSE);
3476         g_free(old_file);
3477         g_free(path);
3478
3479         return file;
3480 }
3481
3482 static gchar *folder_item_get_mark_file(FolderItem *item)
3483 {
3484         gchar *path;
3485         gchar *file;
3486         gchar *old_file;
3487
3488         g_return_val_if_fail(item != NULL, NULL);
3489         g_return_val_if_fail(item->path != NULL, NULL);
3490
3491         path = folder_item_get_path(item);
3492         g_return_val_if_fail(path != NULL, NULL);
3493         if (!is_dir_exist(path))
3494                 make_dir_hier(path);
3495         file = g_strconcat(path, G_DIR_SEPARATOR_S, MARK_FILE, NULL);
3496         old_file = g_strconcat(path, G_DIR_SEPARATOR_S, OLD_MARK_FILE, NULL);
3497
3498         if (!is_file_exist(file) && is_file_exist(old_file))
3499                 move_file(old_file, file, FALSE);
3500         g_free(old_file);
3501         g_free(path);
3502
3503         return file;
3504 }
3505
3506 static gchar *folder_item_get_tags_file(FolderItem *item)
3507 {
3508         gchar *path;
3509         gchar *identifier;
3510         gchar *file;
3511
3512         /* we save tags files in rc_dir, because tagsrc is there too,
3513          * and storing tags directly in the mailboxes would give strange
3514          * result when using another Claws mailbox from another install
3515          * with different tags. */
3516
3517         g_return_val_if_fail(item != NULL, NULL);
3518
3519         identifier = folder_item_get_identifier(item);
3520         g_return_val_if_fail(identifier != NULL, NULL);
3521         
3522         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
3523                            "tagsdb", G_DIR_SEPARATOR_S,
3524                            identifier, NULL);
3525         
3526         g_free(identifier);
3527                            
3528         if (!is_dir_exist(path))
3529                 make_dir_hier(path);
3530
3531