55b83899b2a678f06c00266f53f422d4043649f7
[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 3 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, see <http://www.gnu.org/licenses/>.
17  * 
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         if (item == NULL)
219                 return;
220
221         folder = item->folder;
222         /* unset previous root of newtype */
223         switch(newtype) {
224         case F_INBOX:
225                 folder_item_change_type(folder->inbox, F_NORMAL);
226                 folder->inbox = item;
227                 break;
228         case F_OUTBOX:
229                 folder_item_change_type(folder->outbox, F_NORMAL);
230                 folder->outbox = item;
231                 break;
232         case F_QUEUE:
233                 folder_item_change_type(folder->queue, F_NORMAL);
234                 folder->queue = item;
235                 break;
236         case F_DRAFT:
237                 folder_item_change_type(folder->draft, F_NORMAL);
238                 folder->draft = item;
239                 break;
240         case F_TRASH:
241                 folder_item_change_type(folder->trash, F_NORMAL);
242                 folder->trash = item;
243                 break;
244         case F_NORMAL:
245         default:
246                 break;
247         }
248         /* set new type for current folder and sons */
249         item->stype = newtype;
250         folder_func_to_all_folders(reset_parent_type, NULL);
251         
252         hookdata.folder = folder;
253         hookdata.update_flags = FOLDER_TREE_CHANGED;
254         hookdata.item = NULL;
255         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
256 }
257
258 void folder_destroy(Folder *folder)
259 {
260         g_return_if_fail(folder != NULL);
261         g_return_if_fail(folder->klass->destroy_folder != NULL);
262
263         folder_remove(folder);
264
265         folder_tree_destroy(folder);
266
267         folder->klass->destroy_folder(folder);
268
269         g_free(folder->name);
270         g_free(folder);
271 }
272
273 void folder_set_xml(Folder *folder, XMLTag *tag)
274 {
275         GList *cur;
276         FolderItem *rootitem = NULL;
277
278         if ((folder->node != NULL) && (folder->node->data != NULL))
279                 rootitem = (FolderItem *) folder->node->data;
280
281         for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
282                 XMLAttr *attr = (XMLAttr *) cur->data;
283
284                 if (!attr || !attr->name || !attr->value) continue;
285                 if (!strcmp(attr->name, "name")) {
286                         g_free(folder->name);
287                         folder->name = g_strdup(attr->value);
288                         if (rootitem != NULL) {
289                                 g_free(rootitem->name);
290                                 rootitem->name = g_strdup(attr->value);
291                         }
292                 } else if (!strcmp(attr->name, "account_id")) {
293                         PrefsAccount *account;
294
295                         account = account_find_from_id(atoi(attr->value));
296                         if (!account)
297                                 g_warning("account_id: %s not found\n", attr->value);
298                         else {
299                                 folder->account = account;
300                                 account->folder = folder;
301                         }
302                 } else if (!strcmp(attr->name, "collapsed")) {
303                         if (rootitem != NULL)
304                                 rootitem->collapsed = *attr->value == '1' ? TRUE : FALSE;
305                 } else if (!strcmp(attr->name, "sort")) {
306                         folder->sort = atoi(attr->value);
307                 }
308         }
309 }
310
311 XMLTag *folder_get_xml(Folder *folder)
312 {
313         XMLTag *tag;
314
315         tag = xml_tag_new("folder");
316
317         if (folder->name)
318                 xml_tag_add_attr(tag, xml_attr_new("name", folder->name));
319         if (folder->account)
320                 xml_tag_add_attr(tag, xml_attr_new_int("account_id", folder->account->account_id));
321         if (folder->node && folder->node->data) {
322                 FolderItem *rootitem = (FolderItem *) folder->node->data;
323
324                 xml_tag_add_attr(tag, xml_attr_new("collapsed", rootitem->collapsed ? "1" : "0"));
325         }
326         xml_tag_add_attr(tag, xml_attr_new_int("sort", folder->sort));
327
328         return tag;
329 }
330
331 FolderItem *folder_item_new(Folder *folder, const gchar *name, const gchar *path)
332 {
333         FolderItem *item = NULL;
334         
335         g_return_val_if_fail(folder != NULL, NULL);
336         
337         if (folder->klass->item_new) {
338                 item = folder->klass->item_new(folder);
339         } else {
340                 item = g_new0(FolderItem, 1);
341         }
342
343         g_return_val_if_fail(item != NULL, NULL);
344
345         item->stype = F_NORMAL;
346         item->name = g_strdup(name);
347         item->path = g_strdup(path);
348         item->mtime = 0;
349         item->new_msgs = 0;
350         item->unread_msgs = 0;
351         item->unreadmarked_msgs = 0;
352         item->marked_msgs = 0;
353         item->total_msgs = 0;
354         item->order = 0;
355         item->last_num = -1;
356         item->cache = NULL;
357         item->no_sub = FALSE;
358         item->no_select = FALSE;
359         item->collapsed = FALSE;
360         item->thread_collapsed = FALSE;
361         item->threaded  = TRUE;
362         item->ret_rcpt  = FALSE;
363         item->opened    = FALSE;
364         item->node = g_node_new(item);
365         item->folder = NULL;
366         item->account = NULL;
367         item->apply_sub = FALSE;
368         item->mark_queue = NULL;
369         item->data = NULL;
370         item->parent_stype = -1;
371
372         item->sort_key = SORT_BY_DATE;
373         item->sort_type = SORT_ASCENDING;
374
375         item->prefs = folder_item_prefs_new();
376
377         return item;
378 }
379
380 void folder_item_append(FolderItem *parent, FolderItem *item)
381 {
382         g_return_if_fail(parent != NULL);
383         g_return_if_fail(parent->folder != NULL);
384         g_return_if_fail(parent->node != NULL);
385         g_return_if_fail(item != NULL);
386
387         item->folder = parent->folder;
388         g_node_append(parent->node, item->node);
389 }
390
391 void folder_item_remove(FolderItem *item)
392 {
393         GNode *node, *start_node;
394         FolderUpdateData hookdata;
395
396         g_return_if_fail(item != NULL);
397         g_return_if_fail(item->folder != NULL);
398         g_return_if_fail(item->folder->node != NULL);
399
400         start_node = node = item->node;
401         
402         node = item->folder->node;
403         
404         node = g_node_find(node, G_PRE_ORDER, G_TRAVERSE_ALL, item);
405         node = node->children;
406
407         /* remove my children */
408         while (node != NULL) {
409                 if (node && node->data) {
410                         FolderItem *sub_item = (FolderItem*) node->data;
411                         node = node->next;
412                         folder_item_remove(sub_item);
413                 }
414         }
415         
416         /* remove myself */
417         if (item->cache != NULL) {
418                 msgcache_destroy(item->cache);
419                 item->cache = NULL;
420         }
421
422         hookdata.folder = item->folder;
423         hookdata.update_flags = FOLDER_TREE_CHANGED | FOLDER_REMOVE_FOLDERITEM;
424         hookdata.item = item;
425         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
426
427         node = start_node;
428
429         if (item->folder->node == node)
430                 item->folder->node = NULL;
431
432         folder_item_destroy(item);
433
434         g_node_destroy(node);
435 }
436
437 void folder_item_remove_children(FolderItem *item)
438 {
439         GNode *node, *next;
440
441         g_return_if_fail(item != NULL);
442         g_return_if_fail(item->folder != NULL);
443         g_return_if_fail(item->node != NULL);
444
445         node = item->node->children;
446         while (node != NULL) {
447                 next = node->next;
448                 folder_item_remove(FOLDER_ITEM(node->data));
449                 node = next;
450         }
451 }
452
453 void folder_item_destroy(FolderItem *item)
454 {
455         Folder *folder;
456
457         g_return_if_fail(item != NULL);
458
459         folder = item->folder;
460         if (folder) {
461                 if (folder->inbox == item)
462                         folder->inbox = NULL;
463                 else if (folder->outbox == item)
464                         folder->outbox = NULL;
465                 else if (folder->draft == item)
466                         folder->draft = NULL;
467                 else if (folder->queue == item)
468                         folder->queue = NULL;
469                 else if (folder->trash == item)
470                         folder->trash = NULL;
471         }
472
473         if (item->cache)
474                 folder_item_free_cache(item, TRUE);
475         if (item->prefs)
476                 folder_item_prefs_free(item->prefs);
477         g_free(item->name);
478         g_free(item->path);
479
480         if (item->folder != NULL) {
481                 if(item->folder->klass->item_destroy) {
482                         item->folder->klass->item_destroy(item->folder, item);
483                 } else {
484                         g_free(item);
485                 }
486         }
487 }
488
489 FolderItem *folder_item_parent(FolderItem *item)
490 {
491         g_return_val_if_fail(item != NULL, NULL);
492         g_return_val_if_fail(item->node != NULL, NULL);
493
494         if (item->node->parent == NULL)
495                 return NULL;
496         return (FolderItem *) item->node->parent->data;
497 }
498
499 void folder_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
500 {
501         GList *cur;
502
503         for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
504                 XMLAttr *attr = (XMLAttr *) cur->data;
505
506                 if (!attr || !attr->name || !attr->value) continue;
507                 if (!strcmp(attr->name, "type")) {
508                         if (!g_ascii_strcasecmp(attr->value, "normal"))
509                                 item->stype = F_NORMAL;
510                         else if (!g_ascii_strcasecmp(attr->value, "inbox"))
511                                 item->stype = F_INBOX;
512                         else if (!g_ascii_strcasecmp(attr->value, "outbox"))
513                                 item->stype = F_OUTBOX;
514                         else if (!g_ascii_strcasecmp(attr->value, "draft"))
515                                 item->stype = F_DRAFT;
516                         else if (!g_ascii_strcasecmp(attr->value, "queue"))
517                                 item->stype = F_QUEUE;
518                         else if (!g_ascii_strcasecmp(attr->value, "trash"))
519                                 item->stype = F_TRASH;
520                 } else if (!strcmp(attr->name, "name")) {
521                         g_free(item->name);
522                         item->name = g_strdup(attr->value);
523                 } else if (!strcmp(attr->name, "path")) {
524                         g_free(item->path);
525                         item->path = g_strdup(attr->value);
526                 } else if (!strcmp(attr->name, "mtime"))
527                         item->mtime = strtoul(attr->value, NULL, 10);
528                 else if (!strcmp(attr->name, "new"))
529                         item->new_msgs = atoi(attr->value);
530                 else if (!strcmp(attr->name, "unread"))
531                         item->unread_msgs = atoi(attr->value);
532                 else if (!strcmp(attr->name, "unreadmarked"))
533                         item->unreadmarked_msgs = atoi(attr->value);
534                 else if (!strcmp(attr->name, "marked"))
535                         item->marked_msgs = atoi(attr->value);
536                 else if (!strcmp(attr->name, "order"))
537                         item->order = atoi(attr->value);
538                 else if (!strcmp(attr->name, "total"))
539                         item->total_msgs = atoi(attr->value);
540                 else if (!strcmp(attr->name, "no_sub"))
541                         item->no_sub = *attr->value == '1' ? TRUE : FALSE;
542                 else if (!strcmp(attr->name, "no_select"))
543                         item->no_select = *attr->value == '1' ? TRUE : FALSE;
544                 else if (!strcmp(attr->name, "collapsed"))
545                         item->collapsed = *attr->value == '1' ? TRUE : FALSE;
546                 else if (!strcmp(attr->name, "thread_collapsed"))
547                         item->thread_collapsed =  *attr->value == '1' ? TRUE : FALSE;
548                 else if (!strcmp(attr->name, "threaded"))
549                         item->threaded =  *attr->value == '1' ? TRUE : FALSE;
550                 else if (!strcmp(attr->name, "hidereadmsgs"))
551                         item->hide_read_msgs =  *attr->value == '1' ? TRUE : FALSE;
552                 else if (!strcmp(attr->name, "reqretrcpt"))
553                         item->ret_rcpt =  *attr->value == '1' ? TRUE : FALSE;
554                 else if (!strcmp(attr->name, "sort_key")) {
555                         if (!strcmp(attr->value, "none"))
556                                 item->sort_key = SORT_BY_NONE;
557                         else if (!strcmp(attr->value, "number"))
558                                 item->sort_key = SORT_BY_NUMBER;
559                         else if (!strcmp(attr->value, "size"))
560                                 item->sort_key = SORT_BY_SIZE;
561                         else if (!strcmp(attr->value, "date"))
562                                 item->sort_key = SORT_BY_DATE;
563                         else if (!strcmp(attr->value, "from"))
564                                 item->sort_key = SORT_BY_FROM;
565                         else if (!strcmp(attr->value, "subject"))
566                                 item->sort_key = SORT_BY_SUBJECT;
567                         else if (!strcmp(attr->value, "score"))
568                                 item->sort_key = SORT_BY_SCORE;
569                         else if (!strcmp(attr->value, "label"))
570                                 item->sort_key = SORT_BY_LABEL;
571                         else if (!strcmp(attr->value, "mark"))
572                                 item->sort_key = SORT_BY_MARK;
573                         else if (!strcmp(attr->value, "unread"))
574                                 item->sort_key = SORT_BY_STATUS;
575                         else if (!strcmp(attr->value, "mime"))
576                                 item->sort_key = SORT_BY_MIME;
577                         else if (!strcmp(attr->value, "to"))
578                                 item->sort_key = SORT_BY_TO;
579                         else if (!strcmp(attr->value, "locked"))
580                                 item->sort_key = SORT_BY_LOCKED;
581                         else if (!strcmp(attr->value, "tags"))
582                                 item->sort_key = SORT_BY_TAGS;
583                         else if (!strcmp(attr->value, "thread_date"))
584                                 item->sort_key = SORT_BY_THREAD_DATE;
585                 } else if (!strcmp(attr->name, "sort_type")) {
586                         if (!strcmp(attr->value, "ascending"))
587                                 item->sort_type = SORT_ASCENDING;
588                         else
589                                 item->sort_type = SORT_DESCENDING;
590                 } else if (!strcmp(attr->name, "account_id")) {
591                         PrefsAccount *account;
592
593                         account = account_find_from_id(atoi(attr->value));
594                         if (!account)
595                                 g_warning("account_id: %s not found\n", attr->value);
596                         else
597                                 item->account = account;
598                 } else if (!strcmp(attr->name, "apply_sub")) {
599                         item->apply_sub = *attr->value == '1' ? TRUE : FALSE;
600                 } else if (!strcmp(attr->name, "last_seen")) {
601                         if (!claws_crashed())
602                                 item->last_seen = atoi(attr->value);
603                         else
604                                 item->last_seen = 0;
605                 }
606         }
607 }
608
609 XMLTag *folder_item_get_xml(Folder *folder, FolderItem *item)
610 {
611         static gchar *folder_item_stype_str[] = {"normal", "inbox", "outbox",
612                                                  "draft", "queue", "trash"};
613         static gchar *sort_key_str[] = {"none", "number", "size", "date",
614                                         "from", "subject", "score", "label",
615                                         "mark", "unread", "mime", "to", 
616                                         "locked", "tags", "thread_date" };
617         XMLTag *tag;
618         gchar *value;
619
620         tag = xml_tag_new("folderitem");
621
622         xml_tag_add_attr(tag, xml_attr_new("type", folder_item_stype_str[item->stype]));
623         if (item->name)
624                 xml_tag_add_attr(tag, xml_attr_new("name", item->name));
625         if (item->path)
626                 xml_tag_add_attr(tag, xml_attr_new("path", item->path));
627         if (item->no_sub)
628                 xml_tag_add_attr(tag, xml_attr_new("no_sub", "1"));
629         if (item->no_select)
630                 xml_tag_add_attr(tag, xml_attr_new("no_select", "1"));
631         xml_tag_add_attr(tag, xml_attr_new("collapsed", item->collapsed && item->node->children ? "1" : "0"));
632         xml_tag_add_attr(tag, xml_attr_new("thread_collapsed", item->thread_collapsed ? "1" : "0"));
633         xml_tag_add_attr(tag, xml_attr_new("threaded", item->threaded ? "1" : "0"));
634         xml_tag_add_attr(tag, xml_attr_new("hidereadmsgs", item->hide_read_msgs ? "1" : "0"));
635         if (item->ret_rcpt)
636                 xml_tag_add_attr(tag, xml_attr_new("reqretrcpt", "1"));
637
638         if (item->sort_key != SORT_BY_NONE) {
639                 xml_tag_add_attr(tag, xml_attr_new("sort_key", sort_key_str[item->sort_key]));
640                 xml_tag_add_attr(tag, xml_attr_new("sort_type", item->sort_type == SORT_ASCENDING ? "ascending" : "descending"));
641         }
642
643         value = g_strdup_printf("%ld", (unsigned long int) item->mtime);
644         xml_tag_add_attr(tag, xml_attr_new("mtime", value));
645         g_free(value);
646         xml_tag_add_attr(tag, xml_attr_new_int("new", item->new_msgs));
647         xml_tag_add_attr(tag, xml_attr_new_int("unread", item->unread_msgs));
648         xml_tag_add_attr(tag, xml_attr_new_int("unreadmarked", item->unreadmarked_msgs));
649         xml_tag_add_attr(tag, xml_attr_new_int("marked", item->marked_msgs));
650         xml_tag_add_attr(tag, xml_attr_new_int("total", item->total_msgs));
651         xml_tag_add_attr(tag, xml_attr_new_int("order", item->order));
652
653         if (item->account)
654                 xml_tag_add_attr(tag, xml_attr_new_int("account_id", item->account->account_id));
655         if (item->apply_sub)
656                 xml_tag_add_attr(tag, xml_attr_new("apply_sub", "1"));
657
658         xml_tag_add_attr(tag, xml_attr_new_int("last_seen", item->last_seen));
659
660         return tag;
661 }
662
663 void folder_set_ui_func(Folder *folder, FolderUIFunc func, gpointer data)
664 {
665         g_return_if_fail(folder != NULL);
666
667         folder->ui_func = func;
668         folder->ui_func_data = data;
669 }
670
671 void folder_set_name(Folder *folder, const gchar *name)
672 {
673         g_return_if_fail(folder != NULL);
674
675         g_free(folder->name);
676         folder->name = name ? g_strdup(name) : NULL;
677         if (folder->node && folder->node->data) {
678                 FolderItem *item = (FolderItem *)folder->node->data;
679
680                 g_free(item->name);
681                 item->name = name ? g_strdup(name) : NULL;
682         }
683 }
684
685 void folder_set_sort(Folder *folder, guint sort)
686 {
687         g_return_if_fail(folder != NULL);
688
689         if (folder->sort != sort) {
690                 folder_remove(folder);
691                 folder->sort = sort;
692                 folder_add(folder);
693         }
694 }
695
696 static gboolean folder_tree_destroy_func(GNode *node, gpointer data) {
697         FolderItem *item = (FolderItem *) node->data;
698
699         folder_item_destroy(item);
700         return FALSE;
701 }
702
703 void folder_tree_destroy(Folder *folder)
704 {
705         GNode *node;
706
707         g_return_if_fail(folder != NULL);
708
709         node = folder->node;
710         
711         prefs_filtering_clear_folder(folder);
712
713         if (node != NULL) {
714                 g_node_traverse(node, G_POST_ORDER, G_TRAVERSE_ALL, -1,
715                                 folder_tree_destroy_func, NULL);
716                 g_node_destroy(node);
717                 folder->node = NULL;
718         }
719 }
720
721 void folder_add(Folder *folder)
722 {
723         Folder *cur_folder;
724         GList *cur;
725         gint i;
726         FolderUpdateData hookdata;
727
728         g_return_if_fail(folder != NULL);
729
730         for (i = 0, cur = folder_list; cur != NULL; cur = cur->next, i++) {
731                 cur_folder = FOLDER(cur->data);
732                 if (cur_folder->sort < folder->sort)
733                         break;
734         }
735
736         folder_list = g_list_insert(folder_list, folder, i);
737
738         hookdata.folder = folder;
739         hookdata.update_flags = FOLDER_ADD_FOLDER;
740         hookdata.item = NULL;
741         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
742 }
743
744 void folder_remove(Folder *folder)
745 {
746         FolderUpdateData hookdata;
747
748         g_return_if_fail(folder != NULL);
749
750         folder_list = g_list_remove(folder_list, folder);
751
752         hookdata.folder = folder;
753         hookdata.update_flags = FOLDER_REMOVE_FOLDER;
754         hookdata.item = NULL;
755         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
756 }
757
758 GList *folder_get_list(void)
759 {
760         return folder_list;
761 }
762
763 gint folder_read_list(void)
764 {
765         GNode *node, *cur;
766         XMLNode *xmlnode;
767         gchar *path;
768
769         path = folder_get_list_path();
770         if (!is_file_exist(path)) return -1;
771         node = xml_parse_file(path);
772         if (!node) return -1;
773
774         xmlnode = node->data;
775         if (strcmp2(xmlnode->tag->tag, "folderlist") != 0) {
776                 g_warning("wrong folder list\n");
777                 xml_free_tree(node);
778                 return -1;
779         }
780
781         cur = node->children;
782         while (cur != NULL) {
783                 Folder *folder;
784
785                 folder = folder_get_from_xml(cur);
786                 if (folder != NULL)
787                         folder_add(folder);
788                 else
789                         folder_unloaded_list = g_slist_append(folder_unloaded_list,
790                                 (gpointer) xml_copy_tree(cur));
791                 cur = cur->next;
792         }
793
794         xml_free_tree(node);
795         if (folder_list || folder_unloaded_list)
796                 return 0;
797         else
798                 return -1;
799 }
800
801 void folder_write_list(void)
802 {
803         GList *list;
804         GSList *slist;
805         Folder *folder;
806         gchar *path;
807         PrefFile *pfile;
808         GNode *rootnode;
809         XMLNode *xmlnode;
810         XMLTag *tag;
811
812         path = folder_get_list_path();
813         if ((pfile = prefs_write_open(path)) == NULL) return;
814
815         if (xml_file_put_xml_decl(pfile->fp) < 0) {
816                 prefs_file_close_revert(pfile);
817                 g_warning("failed to start write folder list.\n");
818                 return;         
819         }
820         tag = xml_tag_new("folderlist");
821
822         xmlnode = xml_node_new(tag, NULL);
823
824         rootnode = g_node_new(xmlnode);
825
826         for (list = folder_list; list != NULL; list = list->next) {
827                 GNode *node;
828
829                 folder = list->data;
830                 node = folder_get_xml_node(folder);
831                 if (node != NULL)
832                         g_node_append(rootnode, node);
833         }
834
835         for (slist = folder_unloaded_list; slist != NULL; slist = g_slist_next(slist)) {
836                 GNode *node = (GNode *) slist->data;
837
838                 g_node_append(rootnode, (gpointer) xml_copy_tree(node));
839         }
840
841         if (xml_write_tree(rootnode, pfile->fp) < 0) {
842                 prefs_file_close_revert(pfile);
843                 g_warning("failed to write folder list.\n");
844         } else if (prefs_file_close(pfile) < 0) {
845                 g_warning("failed to write folder list.\n");
846         }
847         xml_free_tree(rootnode);
848 }
849
850 static gboolean folder_scan_tree_func(GNode *node, gpointer data)
851 {
852         GHashTable *pptable = (GHashTable *)data;
853         FolderItem *item = (FolderItem *)node->data;
854         
855         folder_item_restore_persist_prefs(item, pptable);
856         folder_item_scan_full(item, FALSE);
857
858         return FALSE;
859 }
860
861 void folder_scan_tree(Folder *folder, gboolean rebuild)
862 {
863         GHashTable *pptable;
864         FolderUpdateData hookdata;
865         Folder *old_folder = folder;
866
867         if (!folder->klass->scan_tree)
868                 return;
869         
870         pptable = folder_persist_prefs_new(folder);
871
872         if (rebuild)
873                 folder_remove(folder);
874
875         if (folder->klass->scan_tree(folder) < 0) {
876                 if (rebuild)
877                         folder_add(old_folder);
878                 return;
879         } else if (rebuild)
880                 folder_add(folder);
881
882         hookdata.folder = folder;
883         hookdata.update_flags = FOLDER_TREE_CHANGED;
884         hookdata.item = NULL;
885         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
886
887         g_node_traverse(folder->node, G_POST_ORDER, G_TRAVERSE_ALL, -1, folder_scan_tree_func, pptable);
888         folder_persist_prefs_free(pptable);
889
890         prefs_matcher_read_config();
891
892         folder_write_list();
893 }
894
895 static gboolean folder_restore_prefs_func(GNode *node, gpointer data)
896 {
897         GHashTable *pptable = (GHashTable *)data;
898         FolderItem *item = (FolderItem *)node->data;
899         
900         folder_item_restore_persist_prefs(item, pptable);
901
902         return FALSE;
903 }
904
905 void folder_fast_scan_tree(Folder *folder)
906 {
907         GHashTable *pptable;
908         FolderUpdateData hookdata;
909
910         if (!folder->klass->scan_tree)
911                 return;
912         
913         pptable = folder_persist_prefs_new(folder);
914
915         if (folder->klass->scan_tree(folder) < 0) {
916                 return;
917         } 
918
919         hookdata.folder = folder;
920         hookdata.update_flags = FOLDER_TREE_CHANGED;
921         hookdata.item = NULL;
922         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
923
924         g_node_traverse(folder->node, G_POST_ORDER, G_TRAVERSE_ALL, -1, folder_restore_prefs_func, pptable);
925         folder_persist_prefs_free(pptable);
926
927         prefs_matcher_read_config();
928
929         folder_write_list();
930 }
931
932 FolderItem *folder_create_folder(FolderItem *parent, const gchar *name)
933 {
934         FolderItem *new_item;
935
936         new_item = parent->folder->klass->create_folder(parent->folder, parent, name);
937         if (new_item) {
938                 FolderUpdateData hookdata;
939
940                 new_item->cache = msgcache_new();
941
942                 hookdata.folder = new_item->folder;
943                 hookdata.update_flags = FOLDER_TREE_CHANGED | FOLDER_ADD_FOLDERITEM;
944                 hookdata.item = new_item;
945                 hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
946         }
947
948         return new_item;
949 }
950
951 gint folder_item_rename(FolderItem *item, gchar *newname)
952 {
953         gint retval;
954
955         g_return_val_if_fail(item != NULL, -1);
956         g_return_val_if_fail(newname != NULL, -1);
957
958         retval = item->folder->klass->rename_folder(item->folder, item, newname);
959
960         if (retval >= 0) {
961                 FolderItemUpdateData hookdata;
962                 FolderUpdateData hookdata2;
963
964                 hookdata.item = item;
965                 hookdata.update_flags = F_ITEM_UPDATE_NAME;
966                 hookdata.msg = NULL;
967                 hooks_invoke(FOLDER_ITEM_UPDATE_HOOKLIST, &hookdata);
968
969                 hookdata2.folder = item->folder;
970                 hookdata2.item = item;
971                 hookdata2.update_flags = FOLDER_RENAME_FOLDERITEM;
972                 hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata2);
973         }
974
975         return retval;
976 }
977
978 struct TotalMsgCount
979 {
980         guint new_msgs;
981         guint unread_msgs;
982         guint unreadmarked_msgs;
983         guint marked_msgs;
984         guint total_msgs;
985 };
986
987 struct FuncToAllFoldersData
988 {
989         FolderItemFunc  function;
990         gpointer        data;
991 };
992
993 static gboolean folder_func_to_all_folders_func(GNode *node, gpointer data)
994 {
995         FolderItem *item;
996         struct FuncToAllFoldersData *function_data = (struct FuncToAllFoldersData *) data;
997
998         g_return_val_if_fail(node->data != NULL, FALSE);
999
1000         item = FOLDER_ITEM(node->data);
1001         g_return_val_if_fail(item != NULL, FALSE);
1002
1003         function_data->function(item, function_data->data);
1004
1005         return FALSE;
1006 }
1007
1008 void folder_func_to_all_folders(FolderItemFunc function, gpointer data)
1009 {
1010         GList *list;
1011         Folder *folder;
1012         struct FuncToAllFoldersData function_data;
1013         
1014         function_data.function = function;
1015         function_data.data = data;
1016
1017         for (list = folder_list; list != NULL; list = list->next) {
1018                 folder = FOLDER(list->data);
1019                 if (folder->node)
1020                         g_node_traverse(folder->node, G_PRE_ORDER,
1021                                         G_TRAVERSE_ALL, -1,
1022                                         folder_func_to_all_folders_func,
1023                                         &function_data);
1024         }
1025 }
1026
1027 static void folder_count_total_msgs_func(FolderItem *item, gpointer data)
1028 {
1029         struct TotalMsgCount *count = (struct TotalMsgCount *)data;
1030
1031         count->new_msgs += item->new_msgs;
1032         count->unread_msgs += item->unread_msgs;
1033         count->unreadmarked_msgs += item->unreadmarked_msgs;
1034         count->marked_msgs += item->marked_msgs;
1035         count->total_msgs += item->total_msgs;
1036 }
1037
1038 struct TotalMsgStatus
1039 {
1040         guint new;
1041         guint unread;
1042         guint total;
1043         GString *str;
1044 };
1045
1046 static gboolean folder_get_status_full_all_func(GNode *node, gpointer data)
1047 {
1048         FolderItem *item;
1049         struct TotalMsgStatus *status = (struct TotalMsgStatus *)data;
1050         gchar *id;
1051  
1052         g_return_val_if_fail(node->data != NULL, FALSE);
1053  
1054         item = FOLDER_ITEM(node->data);
1055
1056         if (!item->path) return FALSE;
1057
1058         status->new += item->new_msgs;
1059         status->unread += item->unread_msgs;
1060         status->total += item->total_msgs;
1061
1062         if (status->str) {
1063                 id = folder_item_get_identifier(item);
1064                 g_string_append_printf(status->str, "%5d %5d %5d %s\n",
1065                                   item->new_msgs, item->unread_msgs,
1066                                   item->total_msgs, id);
1067                 g_free(id);
1068         }
1069  
1070         return FALSE;
1071  }
1072  
1073 static void folder_get_status_full_all(GString *str, guint *new, guint *unread,
1074                                        guint *total)
1075 {
1076         GList *list;
1077         Folder *folder;
1078         struct TotalMsgStatus status;
1079  
1080         status.new = status.unread = status.total = 0;
1081         status.str = str;
1082  
1083         debug_print("Counting total number of messages...\n");
1084  
1085         for (list = folder_list; list != NULL; list = list->next) {
1086                 folder = FOLDER(list->data);
1087                 if (folder->node)
1088                         g_node_traverse(folder->node, G_PRE_ORDER,
1089                                         G_TRAVERSE_ALL, -1,
1090                                         folder_get_status_full_all_func,
1091                                         &status);
1092         }
1093  
1094         *new = status.new;
1095         *unread = status.unread;
1096         *total = status.total;
1097 }
1098
1099 gchar *folder_get_status(GPtrArray *folders, gboolean full)
1100 {
1101         guint new, unread, total;
1102         GString *str;
1103         gint i;
1104         gchar *ret;
1105
1106         new = unread = total = 0;
1107
1108         str = g_string_new(NULL);
1109
1110         if (folders) {
1111                 for (i = 0; i < folders->len; i++) {
1112                         FolderItem *item;
1113
1114                         item = g_ptr_array_index(folders, i);
1115                         new += item->new_msgs;
1116                         unread += item->unread_msgs;
1117                         total += item->total_msgs;
1118
1119                         if (full) {
1120                                 gchar *id;
1121
1122                                 id = folder_item_get_identifier(item);
1123                                 g_string_append_printf(str, "%5d %5d %5d %s\n",
1124                                                   item->new_msgs, item->unread_msgs,
1125                                                   item->total_msgs, id);
1126                                 g_free(id);
1127                         }
1128                 }
1129         } else {
1130                 folder_get_status_full_all(full ? str : NULL,
1131                                            &new, &unread, &total);
1132         }
1133
1134         if (full)
1135                 g_string_append_printf(str, "%5d %5d %5d\n", new, unread, total);
1136         else
1137                 g_string_append_printf(str, "%d %d %d\n", new, unread, total);
1138
1139         ret = str->str;
1140         g_string_free(str, FALSE);
1141  
1142         return ret;
1143 }
1144
1145 void folder_count_total_msgs(guint *new_msgs, guint *unread_msgs, 
1146                              guint *unreadmarked_msgs, guint *marked_msgs,
1147                              guint *total_msgs)
1148 {
1149         struct TotalMsgCount count;
1150
1151         count.new_msgs = count.unread_msgs = count.unreadmarked_msgs = count.total_msgs = 0;
1152
1153         debug_print("Counting total number of messages...\n");
1154
1155         folder_func_to_all_folders(folder_count_total_msgs_func, &count);
1156
1157         *new_msgs = count.new_msgs;
1158         *unread_msgs = count.unread_msgs;
1159         *unreadmarked_msgs = count.unreadmarked_msgs;
1160         *marked_msgs = count.marked_msgs;
1161         *total_msgs = count.total_msgs;
1162 }
1163
1164 Folder *folder_find_from_path(const gchar *path)
1165 {
1166         GList *list;
1167         Folder *folder;
1168
1169         for (list = folder_list; list != NULL; list = list->next) {
1170                 folder = list->data;
1171                 if ((FOLDER_TYPE(folder) == F_MH || 
1172                      FOLDER_TYPE(folder) == F_MBOX) &&
1173                     !path_cmp(LOCAL_FOLDER(folder)->rootpath, path))
1174                         return folder;
1175         }
1176
1177         return NULL;
1178 }
1179
1180 Folder *folder_find_from_name(const gchar *name, FolderClass *klass)
1181 {
1182         GList *list;
1183         Folder *folder;
1184
1185         for (list = folder_list; list != NULL; list = list->next) {
1186                 folder = list->data;
1187                 if (folder->klass == klass && 
1188                     strcmp2(name, folder->name) == 0)
1189                         return folder;
1190         }
1191
1192         return NULL;
1193 }
1194
1195 static gboolean folder_item_find_func(GNode *node, gpointer data)
1196 {
1197         FolderItem *item = node->data;
1198         gpointer *d = data;
1199         const gchar *path = d[0];
1200
1201         if (path_cmp(path, item->path) != 0)
1202                 return FALSE;
1203
1204         d[1] = item;
1205
1206         return TRUE;
1207 }
1208
1209 FolderItem *folder_find_item_from_path(const gchar *path)
1210 {
1211         Folder *folder;
1212         gpointer d[2];
1213         GList *list = folder_get_list();
1214         
1215         folder = list ? list->data:NULL;
1216         
1217         g_return_val_if_fail(folder != NULL, NULL);
1218
1219         d[0] = (gpointer)path;
1220         d[1] = NULL;
1221         while (d[1] == NULL && list) {
1222                 folder = FOLDER(list->data);
1223                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1224                         folder_item_find_func, d);
1225                 list = list->next;
1226         }
1227         return d[1];
1228 }
1229
1230 FolderItem *folder_find_child_item_by_name(FolderItem *item, const gchar *name)
1231 {
1232         GNode *node;
1233         FolderItem *child;
1234
1235         for (node = item->node->children; node != NULL; node = node->next) {
1236                 gchar *base;
1237                 child = FOLDER_ITEM(node->data);
1238                 base = g_path_get_basename(child->path);
1239                 if (strcmp2(base, name) == 0) {
1240                         g_free(base);
1241                         return child;
1242                 }
1243                 g_free(base);
1244         }
1245
1246         return NULL;
1247 }
1248
1249 FolderClass *folder_get_class_from_string(const gchar *str)
1250 {
1251         GSList *classlist;
1252
1253         classlist = folder_get_class_list();
1254         for (; classlist != NULL; classlist = g_slist_next(classlist)) {
1255                 FolderClass *class = (FolderClass *) classlist->data;
1256                 if (g_ascii_strcasecmp(class->idstr, str) == 0)
1257                         return class;
1258         }
1259
1260         return NULL;
1261 }
1262
1263 static gchar *folder_get_identifier(Folder *folder)
1264 {
1265         gchar *type_str;
1266
1267         g_return_val_if_fail(folder != NULL, NULL);
1268
1269         type_str = folder->klass->idstr;
1270         return g_strconcat("#", type_str, "/", folder->name, NULL);
1271 }
1272
1273 gchar *folder_item_get_identifier(FolderItem *item)
1274 {
1275         gchar *id = NULL;
1276         gchar *folder_id = NULL;
1277
1278         g_return_val_if_fail(item != NULL, NULL);
1279
1280         if (item->path == NULL)
1281                 return NULL;
1282
1283         folder_id = folder_get_identifier(item->folder);
1284         id = g_strconcat(folder_id, "/", item->path, NULL);
1285         g_free(folder_id);
1286
1287         return id;
1288 }
1289
1290 FolderItem *folder_find_item_from_identifier(const gchar *identifier)
1291 {
1292         Folder *folder;
1293         gpointer d[2];
1294         gchar *str;
1295         gchar *p;
1296         gchar *name;
1297         gchar *path;
1298         FolderClass *class;
1299
1300         g_return_val_if_fail(identifier != NULL, NULL);
1301
1302         if (*identifier != '#')
1303                 return folder_find_item_from_path(identifier);
1304
1305         Xstrdup_a(str, identifier, return NULL);
1306
1307         p = strchr(str, '/');
1308         if (!p)
1309                 return folder_find_item_from_path(identifier);
1310         *p = '\0';
1311         p++;
1312         class = folder_get_class_from_string(&str[1]);
1313         if (class == NULL)
1314                 return folder_find_item_from_path(identifier);
1315
1316         name = p;
1317         p = strchr(p, '/');
1318         if (!p)
1319                 return folder_find_item_from_path(identifier);
1320         *p = '\0';
1321         p++;
1322
1323         folder = folder_find_from_name(name, class);
1324         if (!folder)
1325                 return folder_find_item_from_path(identifier);
1326
1327         path = p;
1328
1329         d[0] = (gpointer)path;
1330         d[1] = NULL;
1331         g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1332                         folder_item_find_func, d);
1333         return d[1];
1334 }
1335
1336 /**
1337  * Get a displayable name for a FolderItem
1338  *
1339  * \param item FolderItem for that a name should be created
1340  * \return Displayable name for item, returned string has to
1341  *         be freed
1342  */
1343 gchar *folder_item_get_name(FolderItem *item)
1344 {
1345         gchar *name = NULL;
1346
1347         g_return_val_if_fail(item != NULL, g_strdup(""));
1348
1349         switch (item->stype) {
1350         case F_INBOX:
1351                 name = g_strdup(!strcmp2(item->name, INBOX_DIR) ? _("Inbox") :
1352                                 item->name);
1353                 break;
1354         case F_OUTBOX:
1355                 name = g_strdup(!strcmp2(item->name, OUTBOX_DIR) ? _("Sent") :
1356                                 item->name);
1357                 break;
1358         case F_QUEUE:
1359                 name = g_strdup(!strcmp2(item->name, QUEUE_DIR) ? _("Queue") :
1360                                 item->name);
1361                 break;
1362         case F_TRASH:
1363                 name = g_strdup(!strcmp2(item->name, TRASH_DIR) ? _("Trash") :
1364                                 item->name);
1365                 break;
1366         case F_DRAFT:
1367                 name = g_strdup(!strcmp2(item->name, DRAFT_DIR) ? _("Drafts") :
1368                                 item->name);
1369                 break;
1370         default:
1371                 break;
1372         }
1373
1374         if (name == NULL) {
1375                 /*
1376                  * should probably be done by a virtual function,
1377                  * the folder knows the ui string and how to abbrev
1378                 */
1379                 if (folder_item_parent(item) == NULL) {
1380                         name = g_strconcat(item->name, " (", item->folder->klass->uistr, ")", NULL);
1381                 } else {
1382                         if (FOLDER_CLASS(item->folder) == news_get_class() &&
1383                             item->path && !strcmp2(item->name, item->path))
1384                                 name = get_abbrev_newsgroup_name
1385                                         (item->path,
1386                                          prefs_common.ng_abbrev_len);
1387                         else
1388                                 name = g_strdup(item->name);
1389                 }
1390         }
1391
1392         if (name == NULL)
1393                 name = g_strdup("");
1394
1395         return name;
1396 }
1397
1398 gboolean folder_have_mailbox (void)
1399 {
1400         GList *cur;
1401         for (cur = folder_list; cur != NULL; cur = g_list_next(cur)) {
1402                 Folder *folder = FOLDER(cur->data);
1403                 if (folder->inbox && folder->outbox)
1404                         return TRUE;
1405         }
1406         return FALSE;
1407 }
1408
1409 FolderItem *folder_get_default_inbox(void)
1410 {
1411         GList *flist;
1412
1413         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1414                 Folder * folder = FOLDER(flist->data);
1415
1416                 if (folder == NULL)
1417                         continue;
1418                 if (folder->inbox == NULL)
1419                         continue;
1420                 if (folder->klass->type == F_UNKNOWN)
1421                         continue;
1422
1423                 return folder->inbox;
1424         }
1425
1426         return NULL;
1427 }
1428
1429 FolderItem *folder_get_default_inbox_for_class(FolderType type)
1430 {
1431         GList *flist;
1432
1433         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1434                 Folder * folder = FOLDER(flist->data);
1435
1436                 if (folder == NULL)
1437                         continue;
1438                 if (folder->inbox == NULL)
1439                         continue;
1440                 if (folder->klass->type != type)
1441                         continue;
1442
1443                 return folder->inbox;
1444         }
1445
1446         return NULL;
1447 }
1448
1449 FolderItem *folder_get_default_outbox(void)
1450 {
1451         GList *flist;
1452
1453         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1454                 Folder * folder = FOLDER(flist->data);
1455
1456                 if (folder == NULL)
1457                         continue;
1458                 if (folder->outbox == NULL)
1459                         continue;
1460                 if (folder->klass->type == F_UNKNOWN)
1461                         continue;
1462
1463                 return folder->outbox;
1464         }
1465
1466         return NULL;
1467 }
1468
1469 FolderItem *folder_get_default_outbox_for_class(FolderType type)
1470 {
1471         GList *flist;
1472
1473         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1474                 Folder * folder = FOLDER(flist->data);
1475
1476                 if (folder == NULL)
1477                         continue;
1478                 if (folder->outbox == NULL)
1479                         continue;
1480                 if (folder->klass->type != type)
1481                         continue;
1482
1483                 return folder->outbox;
1484         }
1485
1486         return NULL;
1487 }
1488
1489 FolderItem *folder_get_default_draft(void)
1490 {
1491         GList *flist;
1492
1493         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1494                 Folder * folder = FOLDER(flist->data);
1495
1496                 if (folder == NULL)
1497                         continue;
1498                 if (folder->draft == NULL)
1499                         continue;
1500                 if (folder->klass->type == F_UNKNOWN)
1501                         continue;
1502
1503                 return folder->draft;
1504         }
1505
1506         return NULL;
1507 }
1508
1509 FolderItem *folder_get_default_draft_for_class(FolderType type)
1510 {
1511         GList *flist;
1512
1513         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1514                 Folder * folder = FOLDER(flist->data);
1515
1516                 if (folder == NULL)
1517                         continue;
1518                 if (folder->draft == NULL)
1519                         continue;
1520                 if (folder->klass->type != type)
1521                         continue;
1522
1523                 return folder->draft;
1524         }
1525
1526         return NULL;
1527 }
1528
1529 FolderItem *folder_get_default_queue(void)
1530 {
1531         GList *flist;
1532
1533         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1534                 Folder * folder = FOLDER(flist->data);
1535
1536                 if (folder == NULL)
1537                         continue;
1538                 if (folder->queue == NULL)
1539                         continue;
1540                 if (folder->klass->type == F_UNKNOWN)
1541                         continue;
1542
1543                 return folder->queue;
1544         }
1545
1546         return NULL;
1547 }
1548
1549 FolderItem *folder_get_default_queue_for_class(FolderType type)
1550 {
1551         GList *flist;
1552
1553         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1554                 Folder * folder = FOLDER(flist->data);
1555
1556                 if (folder == NULL)
1557                         continue;
1558                 if (folder->queue == NULL)
1559                         continue;
1560                 if (folder->klass->type != type)
1561                         continue;
1562
1563                 return folder->queue;
1564         }
1565
1566         return NULL;
1567 }
1568
1569 FolderItem *folder_get_default_trash(void)
1570 {
1571         GList *flist;
1572
1573         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1574                 Folder * folder = FOLDER(flist->data);
1575
1576                 if (folder == NULL)
1577                         continue;
1578                 if (folder->trash == NULL)
1579                         continue;
1580                 if (folder->klass->type == F_UNKNOWN)
1581                         continue;
1582
1583                 return folder->trash;
1584         }
1585
1586         return NULL;
1587 }
1588
1589 FolderItem *folder_get_default_trash_for_class(FolderType type)
1590 {
1591         GList *flist;
1592
1593         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1594                 Folder * folder = FOLDER(flist->data);
1595
1596                 if (folder == NULL)
1597                         continue;
1598                 if (folder->trash == NULL)
1599                         continue;
1600                 if (folder->klass->type != type)
1601                         continue;
1602
1603                 return folder->trash;
1604         }
1605
1606         return NULL;
1607 }
1608
1609 #define CREATE_FOLDER_IF_NOT_EXIST(member, dir, type)           \
1610 {                                                               \
1611         if (!folder->member) {                                  \
1612                 item = folder_item_new(folder, dir, dir);       \
1613                 item->stype = type;                             \
1614                 folder_item_append(rootitem, item);             \
1615                 folder->member = item;                          \
1616         }                                                       \
1617 }
1618
1619 void folder_set_missing_folders(void)
1620 {
1621         Folder *folder;
1622         FolderItem *rootitem;
1623         FolderItem *item;
1624         GList *list;
1625
1626         for (list = folder_list; list != NULL; list = list->next) {
1627                 folder = list->data;
1628                 if (FOLDER_TYPE(folder) != F_MH) continue;
1629                 rootitem = FOLDER_ITEM(folder->node->data);
1630                 g_return_if_fail(rootitem != NULL);
1631
1632                 if (folder->inbox && folder->outbox && folder->draft &&
1633                     folder->queue && folder->trash)
1634                         continue;
1635
1636                 if (folder->klass->create_tree(folder) < 0) {
1637                         g_warning("%s: can't create the folder tree.\n",
1638                                   LOCAL_FOLDER(folder)->rootpath);
1639                         continue;
1640                 }
1641
1642                 CREATE_FOLDER_IF_NOT_EXIST(inbox,  INBOX_DIR,  F_INBOX);
1643                 CREATE_FOLDER_IF_NOT_EXIST(outbox, OUTBOX_DIR, F_OUTBOX);
1644                 CREATE_FOLDER_IF_NOT_EXIST(draft,  DRAFT_DIR,  F_DRAFT);
1645                 CREATE_FOLDER_IF_NOT_EXIST(queue,  QUEUE_DIR,  F_QUEUE);
1646                 CREATE_FOLDER_IF_NOT_EXIST(trash,  TRASH_DIR,  F_TRASH);
1647         }
1648 }
1649
1650 static gboolean folder_unref_account_func(GNode *node, gpointer data)
1651 {
1652         FolderItem *item = node->data;
1653         PrefsAccount *account = data;
1654
1655         if (item->account == account)
1656                 item->account = NULL;
1657
1658         return FALSE;
1659 }
1660
1661 void folder_unref_account_all(PrefsAccount *account)
1662 {
1663         Folder *folder;
1664         GList *list;
1665
1666         if (!account) return;
1667
1668         for (list = folder_list; list != NULL; list = list->next) {
1669                 folder = list->data;
1670                 if (folder->account == account)
1671                         folder->account = NULL;
1672                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1673                                 folder_unref_account_func, account);
1674         }
1675 }
1676
1677 #undef CREATE_FOLDER_IF_NOT_EXIST
1678
1679 gchar *folder_item_get_path(FolderItem *item)
1680 {
1681         Folder *folder;
1682
1683         g_return_val_if_fail(item != NULL, NULL);
1684         folder = item->folder;
1685         g_return_val_if_fail(folder != NULL, NULL);
1686
1687         return folder->klass->item_get_path(folder, item);
1688 }
1689
1690 static gint folder_sort_cache_list_by_msgnum(gconstpointer a, gconstpointer b)
1691 {
1692         MsgInfo *msginfo_a = (MsgInfo *) a;
1693         MsgInfo *msginfo_b = (MsgInfo *) b;
1694
1695         return (msginfo_a->msgnum - msginfo_b->msgnum);
1696 }
1697
1698 static gint folder_sort_folder_list(gconstpointer a, gconstpointer b)
1699 {
1700         guint gint_a = GPOINTER_TO_INT(a);
1701         guint gint_b = GPOINTER_TO_INT(b);
1702         
1703         return (gint_a - gint_b);
1704 }
1705
1706 static gint syncronize_flags(FolderItem *item, MsgInfoList *msglist)
1707 {
1708         GRelation *relation;
1709         gint ret = 0;
1710         GSList *cur;
1711
1712         if(msglist == NULL)
1713                 return 0;
1714         if(item->folder->klass->get_flags == NULL)
1715                 return 0;
1716         if (item->no_select)
1717                 return 0;
1718
1719         relation = g_relation_new(2);
1720         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
1721         if ((ret = item->folder->klass->get_flags(
1722             item->folder, item, msglist, relation)) == 0) {
1723                 GTuples *tuples;
1724                 MsgInfo *msginfo;
1725                 MsgPermFlags permflags = 0;
1726                 gboolean skip;
1727
1728                 folder_item_update_freeze();
1729                 folder_item_set_batch(item, TRUE);
1730                 for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1731                         msginfo = (MsgInfo *) cur->data;
1732                 
1733                         tuples = g_relation_select(relation, msginfo, 0);
1734                         skip = tuples->len < 1;
1735                         if (!skip)
1736                                 permflags = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
1737                         g_tuples_destroy(tuples);
1738                         if (skip)
1739                                 continue;
1740                         
1741                         if (msginfo->flags.perm_flags != permflags) {
1742                                 procmsg_msginfo_change_flags(msginfo,
1743                                         permflags & ~msginfo->flags.perm_flags, 0,
1744                                         ~permflags & msginfo->flags.perm_flags, 0);
1745                         }
1746                 }
1747                 folder_item_set_batch(item, FALSE);
1748                 folder_item_update_thaw();
1749         }
1750         g_relation_destroy(relation);   
1751
1752         return ret;
1753 }
1754
1755 static gint folder_item_syncronize_flags(FolderItem *item)
1756 {
1757         MsgInfoList *msglist = NULL;
1758         GSList *cur;
1759         gint ret = 0;
1760         
1761         g_return_val_if_fail(item != NULL, -1);
1762         g_return_val_if_fail(item->folder != NULL, -1);
1763         g_return_val_if_fail(item->folder->klass != NULL, -1);
1764         if (item->no_select)
1765                 return -1;
1766
1767         item->scanning = TRUE;
1768
1769         if (item->cache == NULL)
1770                 folder_item_read_cache(item);
1771         
1772         msglist = msgcache_get_msg_list(item->cache);
1773         
1774         ret = syncronize_flags(item, msglist);
1775
1776         for (cur = msglist; cur != NULL; cur = g_slist_next(cur))
1777                 procmsg_msginfo_free((MsgInfo *) cur->data);
1778         
1779         g_slist_free(msglist);
1780
1781         item->scanning = FALSE;
1782
1783         return ret;
1784 }
1785
1786 static void folder_item_process_open (FolderItem *item,
1787                                  void (*before_proc_func)(gpointer data),
1788                                  void (*after_proc_func)(gpointer data),
1789                                  gpointer data)
1790 {
1791         gchar *buf;
1792         if (item == NULL)
1793                 return;
1794         if((item->folder->klass->scan_required != NULL) &&
1795            (item->folder->klass->scan_required(item->folder, item))) {
1796                 folder_item_scan_full(item, TRUE);
1797         } else {
1798                 folder_item_syncronize_flags(item);
1799         }
1800         
1801         /* Processing */
1802         buf = g_strdup_printf(_("Processing (%s)...\n"), 
1803                               item->path ? item->path : item->name);
1804         g_free(buf);
1805
1806         if (before_proc_func)
1807                 before_proc_func(data);
1808
1809         folder_item_apply_processing(item);
1810
1811         if (after_proc_func)
1812                 after_proc_func(data);
1813
1814         item->processing_pending = FALSE;
1815         return; 
1816 }
1817
1818 gint folder_item_open(FolderItem *item)
1819 {
1820         START_TIMING(""); 
1821         if (item->no_select)
1822                 return -1;
1823
1824         if (item->scanning) {
1825                 debug_print("%s is scanning... \n", item->path ? item->path : item->name);
1826                 return -2;
1827         }
1828
1829         item->processing_pending = TRUE;
1830         folder_item_process_open (item, NULL, NULL, NULL);
1831         
1832         item->opened = TRUE;
1833         END_TIMING();
1834         return 0;
1835 }
1836
1837 gint folder_item_close(FolderItem *item)
1838 {
1839         GSList *mlist, *cur;
1840         Folder *folder;
1841         
1842         g_return_val_if_fail(item != NULL, -1);
1843
1844         if (item->no_select)
1845                 return -1;
1846
1847         if (item->new_msgs) {
1848                 folder_item_update_freeze();
1849                 mlist = folder_item_get_msg_list(item);
1850                 for (cur = mlist ; cur != NULL ; cur = cur->next) {
1851                         MsgInfo * msginfo;
1852
1853                         msginfo = (MsgInfo *) cur->data;
1854                         if (MSG_IS_NEW(msginfo->flags))
1855                                 procmsg_msginfo_unset_flags(msginfo, MSG_NEW, 0);
1856                         procmsg_msginfo_free(msginfo);
1857                 }
1858                 g_slist_free(mlist);
1859                 folder_item_update_thaw();
1860         }               
1861
1862         folder_item_write_cache(item);
1863         
1864         folder_item_update(item, F_ITEM_UPDATE_MSGCNT);
1865
1866         item->opened = FALSE;
1867         folder = item->folder;
1868
1869         if (folder->klass->close == NULL)
1870                 return 0;
1871
1872         return folder->klass->close(folder, item);
1873 }
1874
1875 static MsgInfoList *get_msginfos(FolderItem *item, MsgNumberList *numlist)
1876 {
1877         MsgInfoList *msglist = NULL;
1878         Folder *folder = item->folder;
1879         if (item->no_select)
1880                 return NULL;
1881         
1882         if (folder->klass->get_msginfos != NULL)
1883                 msglist = folder->klass->get_msginfos(folder, item, numlist);
1884         else {
1885                 MsgNumberList *elem;
1886
1887                 for (elem = numlist; elem != NULL; elem = g_slist_next(elem)) {
1888                         MsgInfo *msginfo;
1889                         guint num;
1890
1891                         num = GPOINTER_TO_INT(elem->data);
1892                         msginfo = folder->klass->get_msginfo(folder, item, num);
1893                         if (msginfo != NULL)
1894                                 msglist = g_slist_prepend(msglist, msginfo);
1895                 }               
1896         }
1897
1898         return msglist;
1899 }
1900
1901 static MsgInfo *get_msginfo(FolderItem *item, guint num)
1902 {
1903         MsgNumberList numlist;
1904         MsgInfoList *msglist;
1905         MsgInfo *msginfo = NULL;
1906
1907         numlist.data = GINT_TO_POINTER(num);
1908         numlist.next = NULL;
1909         msglist = get_msginfos(item, &numlist);
1910         if (msglist != NULL)
1911                 msginfo = procmsg_msginfo_new_ref(msglist->data);
1912         procmsg_msg_list_free(msglist);
1913
1914         return msginfo;
1915 }
1916
1917 gint folder_item_scan_full(FolderItem *item, gboolean filtering)
1918 {
1919         Folder *folder;
1920         GSList *folder_list = NULL, *cache_list = NULL;
1921         GSList *folder_list_cur, *cache_list_cur, *new_list = NULL;
1922         GSList *exists_list = NULL, *elem;
1923         GSList *newmsg_list = NULL;
1924         guint newcnt = 0, unreadcnt = 0, totalcnt = 0;
1925         guint markedcnt = 0, unreadmarkedcnt = 0;
1926         guint cache_max_num, folder_max_num, cache_cur_num, folder_cur_num;
1927         gboolean update_flags = 0, old_uids_valid = FALSE;
1928         GHashTable *subject_table = NULL;
1929         
1930         g_return_val_if_fail(item != NULL, -1);
1931         if (item->path == NULL) return -1;
1932
1933         folder = item->folder;
1934
1935         g_return_val_if_fail(folder != NULL, -1);
1936         g_return_val_if_fail(folder->klass->get_num_list != NULL, -1);
1937
1938         item->scanning = TRUE;
1939
1940         debug_print("Scanning folder %s for cache changes.\n", item->path ? item->path : "(null)");
1941         
1942         /* Get list of messages for folder and cache */
1943         if (folder->klass->get_num_list(item->folder, item, &folder_list, &old_uids_valid) < 0) {
1944                 debug_print("Error fetching list of message numbers\n");
1945                 item->scanning = FALSE;
1946                 return(-1);
1947         }
1948
1949         if(prefs_common.thread_by_subject) {
1950                 subject_table = g_hash_table_new(g_str_hash, g_str_equal);
1951         }
1952         
1953         if (old_uids_valid) {
1954                 if (!item->cache)
1955                         folder_item_read_cache(item);
1956                 cache_list = msgcache_get_msg_list(item->cache);
1957         } else {
1958                 if (item->cache)
1959                         msgcache_destroy(item->cache);
1960                 item->cache = msgcache_new();
1961                 cache_list = NULL;
1962         }
1963
1964         /* Sort both lists */
1965         cache_list = g_slist_sort(cache_list, folder_sort_cache_list_by_msgnum);
1966         folder_list = g_slist_sort(folder_list, folder_sort_folder_list);
1967
1968         cache_list_cur = cache_list;
1969         folder_list_cur = folder_list;
1970
1971         if (cache_list_cur != NULL) {
1972                 GSList *cache_list_last;
1973         
1974                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
1975                 cache_list_last = g_slist_last(cache_list);
1976                 cache_max_num = ((MsgInfo *)cache_list_last->data)->msgnum;
1977         } else {
1978                 cache_cur_num = G_MAXINT;
1979                 cache_max_num = 0;
1980         }
1981
1982         if (folder_list_cur != NULL) {
1983                 GSList *folder_list_last;
1984         
1985                 folder_cur_num = GPOINTER_TO_INT(folder_list_cur->data);
1986                 folder_list_last = g_slist_last(folder_list);
1987                 folder_max_num = GPOINTER_TO_INT(folder_list_last->data);
1988         } else {
1989                 folder_cur_num = G_MAXINT;
1990                 folder_max_num = 0;
1991         }
1992
1993         while ((cache_cur_num != G_MAXINT) || (folder_cur_num != G_MAXINT)) {
1994                 /*
1995                  *  Message only exists in the folder
1996                  *  Remember message for fetching
1997                  */
1998                 if (folder_cur_num < cache_cur_num) {
1999                         gboolean add = FALSE;
2000
2001                         switch(FOLDER_TYPE(folder)) {
2002                                 case F_NEWS:
2003                                         if (folder_cur_num < cache_max_num)
2004                                                 break;
2005                                         
2006                                         if (folder->account->max_articles == 0) {
2007                                                 add = TRUE;
2008                                         }
2009
2010                                         if (folder_max_num <= folder->account->max_articles) {
2011                                                 add = TRUE;
2012                                         } else if (folder_cur_num > (folder_max_num - folder->account->max_articles)) {
2013                                                 add = TRUE;
2014                                         }
2015                                         break;
2016                                 default:
2017                                         add = TRUE;
2018                                         break;
2019                         }
2020                         
2021                         if (add) {
2022                                 new_list = g_slist_prepend(new_list, GINT_TO_POINTER(folder_cur_num));
2023                                 debug_print("Remembered message %d for fetching\n", folder_cur_num);
2024                         }
2025
2026                         /* Move to next folder number */
2027                         folder_list_cur = folder_list_cur->next;
2028
2029                         if (folder_list_cur != NULL)
2030                                 folder_cur_num = GPOINTER_TO_INT(folder_list_cur->data);
2031                         else
2032                                 folder_cur_num = G_MAXINT;
2033
2034                         continue;
2035                 }
2036
2037                 /*
2038                  *  Message only exists in the cache
2039                  *  Remove the message from the cache
2040                  */
2041                 if (cache_cur_num < folder_cur_num) {
2042                         msgcache_remove_msg(item->cache, cache_cur_num);
2043                         debug_print("Removed message %d from cache.\n", cache_cur_num);
2044
2045                         /* Move to next cache number */
2046                         cache_list_cur = cache_list_cur->next;
2047
2048                         if (cache_list_cur != NULL)
2049                                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
2050                         else
2051                                 cache_cur_num = G_MAXINT;
2052
2053                         update_flags |= F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT;
2054
2055                         continue;
2056                 }
2057
2058                 /*
2059                  *  Message number exists in folder and cache!
2060                  *  Check if the message has been modified
2061                  */
2062                 if (cache_cur_num == folder_cur_num) {
2063                         MsgInfo *msginfo;
2064
2065                         msginfo = msgcache_get_msg(item->cache, folder_cur_num);
2066                         if (folder->klass->is_msg_changed && folder->klass->is_msg_changed(folder, item, msginfo)) {
2067                                 msgcache_remove_msg(item->cache, msginfo->msgnum);
2068                                 new_list = g_slist_prepend(new_list, GINT_TO_POINTER(msginfo->msgnum));
2069                                 procmsg_msginfo_free(msginfo);
2070
2071                                 debug_print("Remembering message %d to update...\n", folder_cur_num);
2072                         } else {
2073                                 exists_list = g_slist_prepend(exists_list, msginfo);
2074
2075                                 if(prefs_common.thread_by_subject &&
2076                                         MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2077                                         !subject_table_lookup(subject_table, msginfo->subject)) {
2078                                         subject_table_insert(subject_table, msginfo->subject, msginfo);
2079                                 }
2080                         }
2081                         
2082                         /* Move to next folder and cache number */
2083                         cache_list_cur = cache_list_cur->next;
2084                         folder_list_cur = folder_list_cur->next;
2085
2086                         if (cache_list_cur != NULL)
2087                                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
2088                         else
2089                                 cache_cur_num = G_MAXINT;
2090
2091                         if (folder_list_cur != NULL)
2092                                 folder_cur_num = GPOINTER_TO_INT(folder_list_cur->data);
2093                         else
2094                                 folder_cur_num = G_MAXINT;
2095
2096                         continue;
2097                 }
2098         }
2099         
2100         for(cache_list_cur = cache_list; cache_list_cur != NULL; cache_list_cur = g_slist_next(cache_list_cur))
2101                 procmsg_msginfo_free((MsgInfo *) cache_list_cur->data);
2102
2103         g_slist_free(cache_list);
2104         g_slist_free(folder_list);
2105
2106         if (new_list != NULL) {
2107                 GSList *tmp_list = NULL;
2108                 newmsg_list = get_msginfos(item, new_list);
2109                 g_slist_free(new_list);
2110                 tmp_list = g_slist_concat(g_slist_copy(exists_list), g_slist_copy(newmsg_list));
2111                 syncronize_flags(item, tmp_list);
2112                 g_slist_free(tmp_list);
2113         } else {
2114                 syncronize_flags(item, exists_list);
2115         }
2116
2117         folder_item_update_freeze();
2118         if (newmsg_list != NULL) {
2119                 GSList *elem, *to_filter = NULL;
2120                 gboolean do_filter = (filtering == TRUE) &&
2121                                         (item->stype == F_INBOX) &&
2122                                         (item->folder->account != NULL) && 
2123                                         (item->folder->account->filter_on_recv);
2124                 
2125                 for (elem = newmsg_list; elem != NULL; elem = g_slist_next(elem)) {
2126                         MsgInfo *msginfo = (MsgInfo *) elem->data;
2127
2128                         msgcache_add_msg(item->cache, msginfo);
2129                         if (!do_filter) {
2130                                 exists_list = g_slist_prepend(exists_list, msginfo);
2131
2132                                 if(prefs_common.thread_by_subject &&
2133                                         MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2134                                         !subject_table_lookup(subject_table, msginfo->subject)) {
2135                                         subject_table_insert(subject_table, msginfo->subject, msginfo);
2136                                 }                       
2137                         }
2138                 }
2139
2140                 if (do_filter) {
2141                         GSList *unfiltered;
2142                         procmsg_msglist_filter(newmsg_list, item->folder->account, 
2143                                         &to_filter, &unfiltered, 
2144                                         TRUE);
2145                         
2146                         filtering_move_and_copy_msgs(newmsg_list);
2147                         if (to_filter != NULL) {
2148                                 for (elem = to_filter; elem; elem = g_slist_next(elem)) {
2149                                         MsgInfo *msginfo = (MsgInfo *)elem->data;
2150                                         procmsg_msginfo_free(msginfo);
2151                                 }
2152                                 g_slist_free(to_filter);
2153                         }
2154                         if (unfiltered != NULL) {
2155                                 for (elem = unfiltered; elem; elem = g_slist_next(elem)) {
2156                                         MsgInfo *msginfo = (MsgInfo *)elem->data;
2157                                         exists_list = g_slist_prepend(exists_list, msginfo);
2158
2159                                         if(prefs_common.thread_by_subject &&
2160                                                 MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2161                                                 !subject_table_lookup(subject_table, msginfo->subject)) {
2162                                                 subject_table_insert(subject_table, msginfo->subject, msginfo);
2163                                         }
2164                                 }
2165                                 g_slist_free(unfiltered);
2166                         }
2167                         if (prefs_common.real_time_sync)
2168                                 folder_item_synchronise(item);
2169                 } else {
2170                         if (prefs_common.real_time_sync)
2171                                 folder_item_synchronise(item);
2172                 }
2173
2174                 g_slist_free(newmsg_list);
2175
2176                 update_flags |= F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT;
2177         }
2178
2179         folder_item_set_batch(item, TRUE);
2180         for (elem = exists_list; elem != NULL; elem = g_slist_next(elem)) {
2181                 MsgInfo *msginfo, *parent_msginfo;
2182
2183                 msginfo = elem->data;
2184                 if (MSG_IS_IGNORE_THREAD(msginfo->flags) && (MSG_IS_NEW(msginfo->flags) || MSG_IS_UNREAD(msginfo->flags)))
2185                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
2186                 if (!MSG_IS_IGNORE_THREAD(msginfo->flags) && procmsg_msg_has_flagged_parent(msginfo, MSG_IGNORE_THREAD)) {
2187                         procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0, MSG_NEW | MSG_UNREAD, 0);
2188                 }
2189                 if (!MSG_IS_WATCH_THREAD(msginfo->flags) && procmsg_msg_has_flagged_parent(msginfo, MSG_WATCH_THREAD)) {
2190                         procmsg_msginfo_set_flags(msginfo, MSG_WATCH_THREAD, 0);
2191                 }
2192                 if(prefs_common.thread_by_subject && !msginfo->inreplyto &&
2193                         !msginfo->references && !MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2194                         (parent_msginfo = subject_table_lookup(subject_table, msginfo->subject)))
2195                 {
2196                         if(MSG_IS_IGNORE_THREAD(parent_msginfo->flags)) {
2197                                 procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0,
2198                                                 MSG_NEW | MSG_UNREAD, 0);
2199                         }
2200                 }
2201                 if ((folder_has_parent_of_type(item, F_OUTBOX) ||
2202                      folder_has_parent_of_type(item, F_QUEUE)  ||
2203                      folder_has_parent_of_type(item, F_DRAFT)  ||
2204                      folder_has_parent_of_type(item, F_TRASH)) &&
2205                     (MSG_IS_NEW(msginfo->flags) || MSG_IS_UNREAD(msginfo->flags)))
2206                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
2207                 if (MSG_IS_NEW(msginfo->flags))
2208                         newcnt++;
2209                 if (MSG_IS_UNREAD(msginfo->flags))
2210                         unreadcnt++;
2211                 if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2212                         unreadmarkedcnt++;
2213                 if (MSG_IS_MARKED(msginfo->flags))
2214                         markedcnt++;
2215
2216                 totalcnt++;
2217
2218                 procmsg_msginfo_free(msginfo);
2219         }
2220         folder_item_set_batch(item, FALSE);
2221         g_slist_free(exists_list);
2222         
2223         if(prefs_common.thread_by_subject) {
2224                 g_hash_table_destroy(subject_table);
2225         }
2226         
2227         if (item->new_msgs != newcnt || item->unread_msgs != unreadcnt
2228         ||  item->total_msgs != totalcnt || item->marked_msgs != markedcnt
2229         ||  item->unreadmarked_msgs != unreadmarkedcnt) {
2230                 update_flags |= F_ITEM_UPDATE_CONTENT;
2231         }
2232
2233         item->new_msgs = newcnt;
2234         item->unread_msgs = unreadcnt;
2235         item->total_msgs = totalcnt;
2236         item->unreadmarked_msgs = unreadmarkedcnt;
2237         item->marked_msgs = markedcnt;
2238
2239         update_flags |= F_ITEM_UPDATE_MSGCNT;
2240
2241         folder_item_update(item, update_flags);
2242         folder_item_update_thaw();
2243         
2244         item->scanning = FALSE;
2245
2246         return 0;
2247 }
2248
2249 gint folder_item_scan(FolderItem *item)
2250 {
2251         return folder_item_scan_full(item, TRUE);
2252 }
2253
2254 static void folder_count_total_cache_memusage(FolderItem *item, gpointer data)
2255 {
2256         gint *memusage = (gint *)data;
2257
2258         if (item->cache == NULL)
2259                 return;
2260         
2261         *memusage += msgcache_get_memory_usage(item->cache);
2262 }
2263
2264 static gint folder_cache_time_compare_func(gconstpointer a, gconstpointer b)
2265 {
2266         FolderItem *fa = (FolderItem *)a;
2267         FolderItem *fb = (FolderItem *)b;
2268         
2269         return (gint) (msgcache_get_last_access_time(fa->cache) - msgcache_get_last_access_time(fb->cache));
2270 }
2271
2272 static void folder_find_expired_caches(FolderItem *item, gpointer data)
2273 {
2274         GSList **folder_item_list = (GSList **)data;
2275         gint difftime, expiretime;
2276         
2277         if (item->cache == NULL)
2278                 return;
2279
2280         if (item->opened > 0)
2281                 return;
2282
2283         difftime = (gint) (time(NULL) - msgcache_get_last_access_time(item->cache));
2284         expiretime = prefs_common.cache_min_keep_time * 60;
2285         debug_print("Cache unused time: %d (Expire time: %d)\n", difftime, expiretime);
2286
2287         if (difftime > expiretime && !item->opened && !item->processing_pending) {
2288                 *folder_item_list = g_slist_insert_sorted(*folder_item_list, item, folder_cache_time_compare_func);
2289         }
2290 }
2291
2292 gboolean folder_item_free_cache(FolderItem *item, gboolean force)
2293 {
2294         g_return_val_if_fail(item != NULL, TRUE);
2295         
2296         if (item->cache == NULL)
2297                 return TRUE;
2298         
2299         if (item->opened > 0 && !force)
2300                 return FALSE;
2301
2302         folder_item_write_cache(item);
2303         msgcache_destroy(item->cache);
2304         item->cache = NULL;
2305         return TRUE;
2306 }
2307
2308 void folder_clean_cache_memory_force(void)
2309 {
2310         int old_cache_max_mem_usage = prefs_common.cache_max_mem_usage;
2311         int old_cache_min_keep_time = prefs_common.cache_min_keep_time;
2312
2313         prefs_common.cache_max_mem_usage = 0;
2314         prefs_common.cache_min_keep_time = 0;
2315
2316         folder_clean_cache_memory(NULL);
2317
2318         prefs_common.cache_max_mem_usage = old_cache_max_mem_usage;
2319         prefs_common.cache_min_keep_time = old_cache_min_keep_time;
2320 }
2321
2322 void folder_clean_cache_memory(FolderItem *protected_item)
2323 {
2324         gint memusage = 0;
2325
2326         folder_func_to_all_folders(folder_count_total_cache_memusage, &memusage);       
2327         debug_print("Total cache memory usage: %d\n", memusage);
2328         
2329         if (memusage > (prefs_common.cache_max_mem_usage * 1024)) {
2330                 GSList *folder_item_list = NULL, *listitem;
2331                 
2332                 debug_print("Trying to free cache memory\n");
2333
2334                 folder_func_to_all_folders(folder_find_expired_caches, &folder_item_list);      
2335                 listitem = folder_item_list;
2336                 while((listitem != NULL) && (memusage > (prefs_common.cache_max_mem_usage * 1024))) {
2337                         FolderItem *item = (FolderItem *)(listitem->data);
2338                         gint cache_size = 0;
2339                         if (item == protected_item) {
2340                                 listitem = listitem->next;
2341                                 continue;
2342                         }
2343                         debug_print("Freeing cache memory for %s\n", item->path ? item->path : item->name);
2344                         cache_size = msgcache_get_memory_usage(item->cache);
2345                         if (folder_item_free_cache(item, FALSE))
2346                                 memusage -= cache_size;
2347
2348                         listitem = listitem->next;
2349                 }
2350                 g_slist_free(folder_item_list);
2351         }
2352 }
2353
2354 static void folder_item_remove_cached_msg(FolderItem *item, MsgInfo *msginfo)
2355 {
2356         Folder *folder = item->folder;
2357
2358         g_return_if_fail(folder != NULL);
2359
2360         if (folder->klass->remove_cached_msg == NULL)
2361                 return;
2362         
2363         folder->klass->remove_cached_msg(folder, item, msginfo);
2364 }
2365
2366 static void folder_item_clean_local_files(FolderItem *item, gint days)
2367 {
2368         g_return_if_fail(item != NULL);
2369         g_return_if_fail(item->folder != NULL);
2370
2371         if (FOLDER_TYPE(item->folder) == F_IMAP ||
2372             FOLDER_TYPE(item->folder) == F_NEWS) {
2373                 GSList *msglist = folder_item_get_msg_list(item);
2374                 GSList *cur;
2375                 time_t t = time(NULL);
2376                 for (cur = msglist; cur; cur = cur->next) {
2377                         MsgInfo *msginfo = (MsgInfo *)cur->data;
2378                         gint age = (t - msginfo->date_t) / (60*60*24);
2379                         if (age > days)
2380                                 folder_item_remove_cached_msg(item, msginfo);
2381                 }
2382                 procmsg_msg_list_free(msglist);
2383         }
2384 }
2385
2386 static void folder_item_read_cache(FolderItem *item)
2387 {
2388         gchar *cache_file, *mark_file, *tags_file;
2389         START_TIMING("");
2390         g_return_if_fail(item != NULL);
2391
2392         if (item->path != NULL) {
2393                 cache_file = folder_item_get_cache_file(item);
2394                 mark_file = folder_item_get_mark_file(item);
2395                 tags_file = folder_item_get_tags_file(item);
2396                 item->cache = msgcache_read_cache(item, cache_file);
2397                 if (!item->cache) {
2398                         MsgInfoList *list, *cur;
2399                         guint newcnt = 0, unreadcnt = 0;
2400                         guint markedcnt = 0, unreadmarkedcnt = 0;
2401                         MsgInfo *msginfo;
2402
2403                         item->cache = msgcache_new();
2404                         folder_item_scan_full(item, TRUE);
2405
2406                         msgcache_read_mark(item->cache, mark_file);
2407
2408                         list = msgcache_get_msg_list(item->cache);
2409                         for (cur = list; cur != NULL; cur = g_slist_next(cur)) {
2410                                 msginfo = cur->data;
2411
2412                                 if (MSG_IS_NEW(msginfo->flags))
2413                                         newcnt++;
2414                                 if (MSG_IS_UNREAD(msginfo->flags))
2415                                         unreadcnt++;
2416                                 if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2417                                         unreadmarkedcnt++;
2418                                 if (MSG_IS_MARKED(msginfo->flags))
2419                                         markedcnt++;
2420                                 procmsg_msginfo_unset_flags(msginfo, MSG_FULLY_CACHED, 0);
2421                         }
2422                         item->new_msgs = newcnt;
2423                         item->unread_msgs = unreadcnt;
2424                         item->unreadmarked_msgs = unreadmarkedcnt;
2425                         item->marked_msgs = markedcnt;
2426                         procmsg_msg_list_free(list);
2427                 } else
2428                         msgcache_read_mark(item->cache, mark_file);
2429
2430                 msgcache_read_tags(item->cache, tags_file);
2431
2432                 g_free(cache_file);
2433                 g_free(mark_file);
2434                 g_free(tags_file);
2435         } else {
2436                 item->cache = msgcache_new();
2437         }
2438         END_TIMING();
2439         folder_clean_cache_memory(item);
2440 }
2441
2442 void folder_item_write_cache(FolderItem *item)
2443 {
2444         gchar *cache_file, *mark_file, *tags_file;
2445         FolderItemPrefs *prefs;
2446         gint filemode = 0;
2447         gchar *id;
2448         time_t last_mtime = (time_t)0;
2449         gboolean need_scan = FALSE;
2450         
2451         if (!item || !item->path || !item->cache)
2452                 return;
2453
2454         last_mtime = item->mtime;
2455         need_scan = item->folder->klass->scan_required(item->folder, item);
2456
2457         id = folder_item_get_identifier(item);
2458         debug_print("Save cache for folder %s\n", id);
2459         g_free(id);
2460
2461         cache_file = folder_item_get_cache_file(item);
2462         mark_file = folder_item_get_mark_file(item);
2463         tags_file = folder_item_get_tags_file(item);
2464         if (msgcache_write(cache_file, mark_file, tags_file, item->cache) < 0) {
2465                 prefs = item->prefs;
2466                 if (prefs && prefs->enable_folder_chmod && prefs->folder_chmod) {
2467                         /* for cache file */
2468                         filemode = prefs->folder_chmod;
2469                         if (filemode & S_IRGRP) filemode |= S_IWGRP;
2470                         if (filemode & S_IROTH) filemode |= S_IWOTH;
2471                         chmod(cache_file, filemode);
2472                 }
2473         }
2474
2475         if (!need_scan && item->folder->klass->set_mtime) {
2476                 if (item->mtime == last_mtime) {
2477                         item->folder->klass->set_mtime(item->folder, item);
2478                 }
2479         }
2480
2481         g_free(cache_file);
2482         g_free(mark_file);
2483         g_free(tags_file);
2484 }
2485
2486 MsgInfo *folder_item_get_msginfo(FolderItem *item, gint num)
2487 {
2488         Folder *folder;
2489         MsgInfo *msginfo = NULL;
2490         
2491         g_return_val_if_fail(item != NULL, NULL);
2492         if (item->no_select)
2493                 return NULL;
2494         folder = item->folder;
2495         if (!item->cache)
2496                 folder_item_read_cache(item);
2497         
2498         if ((msginfo = msgcache_get_msg(item->cache, num)) != NULL)
2499                 return msginfo;
2500         
2501         msginfo = get_msginfo(item, num);
2502         if (msginfo != NULL) {
2503                 msgcache_add_msg(item->cache, msginfo);
2504                 return msginfo;
2505         }
2506         
2507         return NULL;
2508 }
2509
2510 MsgInfo *folder_item_get_msginfo_by_msgid(FolderItem *item, const gchar *msgid)
2511 {
2512         Folder *folder;
2513         MsgInfo *msginfo;
2514         
2515         g_return_val_if_fail(item != NULL, NULL);
2516         g_return_val_if_fail(msgid != NULL, NULL);
2517         if (item->no_select)
2518                 return FALSE;
2519         
2520         folder = item->folder;
2521         if (!item->cache)
2522                 folder_item_read_cache(item);
2523         
2524         if ((msginfo = msgcache_get_msg_by_id(item->cache, msgid)) != NULL)
2525                 return msginfo;
2526
2527         return NULL;
2528 }
2529
2530 GSList *folder_item_get_msg_list(FolderItem *item)
2531 {
2532         g_return_val_if_fail(item != NULL, NULL);
2533         if (item->no_select)
2534                 return FALSE;
2535         
2536         if (item->cache == 0)
2537                 folder_item_read_cache(item);
2538
2539         g_return_val_if_fail(item->cache != NULL, NULL);
2540         
2541         return msgcache_get_msg_list(item->cache);
2542 }
2543
2544 static void msginfo_set_mime_flags(GNode *node, gpointer data)
2545 {
2546         MsgInfo *msginfo = data;
2547         MimeInfo *mimeinfo = node->data;
2548         
2549         if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT
2550          && (!mimeinfo->subtype ||  strcmp(mimeinfo->subtype, "pgp-signature"))) {
2551                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2552         } else if (mimeinfo->disposition == DISPOSITIONTYPE_UNKNOWN && 
2553                  mimeinfo->type != MIMETYPE_TEXT &&
2554                  mimeinfo->type != MIMETYPE_MULTIPART) {
2555                 if (!mimeinfo->subtype 
2556                 ||  strcmp(mimeinfo->subtype, "pgp-signature"))
2557                         procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2558         } else if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE &&
2559                 strcmp(mimeinfo->subtype, "pgp-signature") && 
2560                 (procmime_mimeinfo_get_parameter(mimeinfo, "name") != NULL ||
2561                  procmime_mimeinfo_get_parameter(mimeinfo, "filename") != NULL)) {
2562                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2563         } 
2564
2565         /* don't descend below top level message for signed and encrypted info */
2566         if (mimeinfo->type == MIMETYPE_MESSAGE)
2567                 return;
2568
2569         if (privacy_mimeinfo_is_signed(mimeinfo)) {
2570                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
2571         }
2572
2573         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
2574                 procmsg_msginfo_set_flags(msginfo, 0, MSG_ENCRYPTED);
2575         } else {
2576                 /* searching inside encrypted parts doesn't really make sense */
2577                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2578         }
2579 }
2580
2581 gchar *folder_item_fetch_msg(FolderItem *item, gint num)
2582 {
2583         Folder *folder;
2584         gchar *msgfile;
2585         MsgInfo *msginfo;
2586
2587         g_return_val_if_fail(item != NULL, NULL);
2588
2589         folder = item->folder;
2590
2591         g_return_val_if_fail(folder->klass->fetch_msg != NULL, NULL);
2592         if (item->no_select)
2593                 return NULL;
2594
2595         msgfile = folder->klass->fetch_msg(folder, item, num);
2596
2597         if (msgfile != NULL) {
2598                 msginfo = folder_item_get_msginfo(item, num);
2599                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2600                         MimeInfo *mimeinfo;
2601
2602                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) && 
2603                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2604                                 mimeinfo = procmime_scan_file(msgfile);
2605                         else
2606                                 mimeinfo = procmime_scan_queue_file(msgfile);
2607                         /* check for attachments */
2608                         if (mimeinfo != NULL) { 
2609                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2610                                 procmime_mimeinfo_free_all(mimeinfo);
2611
2612                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2613                         }
2614                 }
2615                 procmsg_msginfo_free(msginfo);
2616         }
2617
2618         return msgfile;
2619 }
2620
2621 gchar *folder_item_fetch_msg_full(FolderItem *item, gint num, gboolean headers,
2622                                   gboolean body)
2623 {
2624         Folder *folder;
2625         gchar *msgfile;
2626         MsgInfo *msginfo;
2627
2628         g_return_val_if_fail(item != NULL, NULL);
2629         if (item->no_select)
2630                 return NULL;
2631         
2632         folder = item->folder;
2633
2634         if (folder->klass->fetch_msg_full == NULL)
2635                 return folder_item_fetch_msg(item, num);
2636
2637         if (item->prefs->offlinesync && prefs_common.real_time_sync)
2638                 msgfile = folder->klass->fetch_msg_full(folder, item, num, 
2639                                                 TRUE, TRUE);
2640         else
2641                 msgfile = folder->klass->fetch_msg_full(folder, item, num, 
2642                                                 headers, body);
2643
2644         if (msgfile != NULL) {
2645                 msginfo = folder_item_get_msginfo(item, num);
2646                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2647                         MimeInfo *mimeinfo;
2648
2649                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
2650                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2651                                 mimeinfo = procmime_scan_file(msgfile);
2652                         else
2653                                 mimeinfo = procmime_scan_queue_file(msgfile);
2654                         /* check for attachments */
2655                         if (mimeinfo != NULL) { 
2656                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2657                                 procmime_mimeinfo_free_all(mimeinfo);
2658
2659                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2660                         }
2661                 }
2662                 procmsg_msginfo_free(msginfo);
2663         }
2664
2665         return msgfile;
2666 }
2667
2668
2669 static gint folder_item_get_msg_num_by_file(FolderItem *dest, const gchar *file)
2670 {
2671         static HeaderEntry hentry[] = {{"Message-ID:",  NULL, TRUE},
2672                                        {NULL,           NULL, FALSE}};
2673         FILE *fp;
2674         MsgInfo *msginfo;
2675         gint msgnum = 0;
2676         gchar buf[BUFFSIZE];
2677
2678         if ((fp = g_fopen(file, "rb")) == NULL)
2679                 return 0;
2680
2681         if ((folder_has_parent_of_type(dest, F_QUEUE)) || 
2682             (folder_has_parent_of_type(dest, F_DRAFT)))
2683                 while (fgets(buf, sizeof(buf), fp) != NULL) {
2684                         /* new way */
2685                         if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2686                                 strlen("X-Claws-End-Special-Headers:"))) ||
2687                             (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2688                                 strlen("X-Sylpheed-End-Special-Headers:"))))
2689                                 break;
2690                         /* old way */
2691                         if (buf[0] == '\r' || buf[0] == '\n') break;
2692                         /* from other mailers */
2693                         if (!strncmp(buf, "Date: ", 6)
2694                         ||  !strncmp(buf, "To: ", 4)
2695                         ||  !strncmp(buf, "From: ", 6)
2696                         ||  !strncmp(buf, "Subject: ", 9)) {
2697                                 rewind(fp);
2698                                 break;
2699                         }
2700                 }
2701
2702         procheader_get_header_fields(fp, hentry);
2703         debug_print("looking for %s\n", hentry[0].body);
2704         if (hentry[0].body) {
2705                 extract_parenthesis(hentry[0].body, '<', '>');
2706                 remove_space(hentry[0].body);
2707                 if ((msginfo = msgcache_get_msg_by_id(dest->cache, hentry[0].body)) != NULL) {
2708                         msgnum = msginfo->msgnum;
2709                         procmsg_msginfo_free(msginfo);
2710
2711                         debug_print("found message as uid %d\n", msgnum);
2712                 }
2713         }
2714         
2715         g_free(hentry[0].body);
2716         hentry[0].body = NULL;
2717         fclose(fp);
2718
2719         return msgnum;
2720 }
2721
2722 static void copy_msginfo_flags(MsgInfo *source, MsgInfo *dest)
2723 {
2724         MsgPermFlags perm_flags = 0;
2725         MsgTmpFlags tmp_flags = 0;
2726
2727         /* create new flags */
2728         if (source != NULL) {
2729                 /* copy original flags */
2730                 perm_flags = source->flags.perm_flags;
2731                 tmp_flags = source->flags.tmp_flags;
2732         } else {
2733                 perm_flags = dest->flags.perm_flags;
2734                 tmp_flags = dest->flags.tmp_flags;
2735         }
2736
2737         /* remove new, unread and deleted in special folders */
2738         if (folder_has_parent_of_type(dest->folder, F_OUTBOX) || 
2739             folder_has_parent_of_type(dest->folder, F_QUEUE) || 
2740             folder_has_parent_of_type(dest->folder, F_DRAFT) || 
2741             folder_has_parent_of_type(dest->folder, F_TRASH))
2742                 perm_flags &= ~(MSG_NEW | MSG_UNREAD | MSG_DELETED);
2743
2744         /* set ignore flag of ignored parent exists */
2745         if (procmsg_msg_has_flagged_parent(dest, MSG_IGNORE_THREAD))
2746                 perm_flags |= MSG_IGNORE_THREAD;
2747
2748         /* unset FULLY_CACHED flags */
2749         perm_flags &= ~MSG_FULLY_CACHED;
2750
2751         if (procmsg_msg_has_flagged_parent(dest, MSG_WATCH_THREAD))
2752                 perm_flags |= MSG_WATCH_THREAD;
2753
2754         /* Unset tmp flags that should not be copied */
2755         tmp_flags &= ~(MSG_MOVE | MSG_COPY | MSG_MOVE_DONE);
2756
2757         /* unset flags that are set but should not */
2758         /* and set new flags */
2759         procmsg_msginfo_change_flags(dest,
2760                                   ~dest->flags.perm_flags & perm_flags,
2761                                   ~dest->flags.tmp_flags  & tmp_flags,
2762                                    dest->flags.perm_flags & ~perm_flags,
2763                                    dest->flags.tmp_flags  & ~tmp_flags);
2764         
2765         if (source && source->tags) {
2766                 g_slist_free(dest->tags);
2767                 dest->tags = g_slist_copy(source->tags);
2768                 folder_item_commit_tags(dest->folder, dest, dest->tags, NULL);
2769         }
2770 }
2771
2772 static void add_msginfo_to_cache(FolderItem *item, MsgInfo *newmsginfo, MsgInfo *flagsource)
2773 {
2774         /* update folder stats */
2775         if (MSG_IS_NEW(newmsginfo->flags))
2776                 item->new_msgs++;
2777         if (MSG_IS_UNREAD(newmsginfo->flags))
2778                 item->unread_msgs++;
2779         if (MSG_IS_UNREAD(newmsginfo->flags) && procmsg_msg_has_marked_parent(newmsginfo))
2780                 item->unreadmarked_msgs++;
2781         if (MSG_IS_MARKED(newmsginfo->flags))
2782                 item->marked_msgs++;
2783         item->total_msgs++;
2784
2785         folder_item_update_freeze();
2786
2787         if (!item->cache)
2788                 folder_item_read_cache(item);
2789
2790         msgcache_add_msg(item->cache, newmsginfo);
2791         copy_msginfo_flags(flagsource, newmsginfo);
2792         folder_item_update_with_msg(item,  F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_ADDMSG, newmsginfo);
2793         folder_item_update_thaw();
2794 }
2795
2796 static void remove_msginfo_from_cache(FolderItem *item, MsgInfo *msginfo)
2797 {
2798         MsgInfoUpdate msginfo_update;
2799
2800         if (!item->cache)
2801                 folder_item_read_cache(item);
2802
2803         if (MSG_IS_NEW(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
2804                 msginfo->folder->new_msgs--;
2805         if (MSG_IS_UNREAD(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
2806                 msginfo->folder->unread_msgs--;
2807         if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2808                 msginfo->folder->unreadmarked_msgs--;
2809         if (MSG_IS_MARKED(msginfo->flags))
2810                 item->marked_msgs--;
2811
2812         msginfo->folder->total_msgs--;
2813
2814         msginfo_update.msginfo = msginfo;
2815         msginfo_update.flags = MSGINFO_UPDATE_DELETED;
2816         hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
2817
2818         msgcache_remove_msg(item->cache, msginfo->msgnum);
2819         folder_item_update_with_msg(msginfo->folder, F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_REMOVEMSG, msginfo);
2820 }
2821
2822 gint folder_item_add_msg(FolderItem *dest, const gchar *file,
2823                          MsgFlags *flags, gboolean remove_source)
2824 {
2825         GSList file_list;
2826         MsgFileInfo fileinfo;
2827
2828         g_return_val_if_fail(dest != NULL, -1);
2829         g_return_val_if_fail(file != NULL, -1);
2830  
2831         fileinfo.msginfo = NULL;
2832         fileinfo.file = (gchar *)file;
2833         fileinfo.flags = flags;
2834         file_list.data = &fileinfo;
2835         file_list.next = NULL;
2836
2837         return folder_item_add_msgs(dest, &file_list, remove_source);
2838 }
2839
2840 gint folder_item_add_msgs(FolderItem *dest, GSList *file_list,
2841                           gboolean remove_source)
2842 {
2843         Folder *folder;
2844         gint ret, num, lastnum = -1;
2845         GSList *file_cur;
2846         GRelation *relation;
2847         MsgFileInfo *fileinfo = NULL;
2848         gboolean folderscan = FALSE;
2849
2850         g_return_val_if_fail(dest != NULL, -1);
2851         g_return_val_if_fail(file_list != NULL, -1);
2852         g_return_val_if_fail(dest->folder != NULL, -1);
2853         if (dest->no_select)
2854                 return -1;
2855
2856         folder = dest->folder;
2857
2858         relation = g_relation_new(2);
2859         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
2860
2861         if (folder->klass->add_msgs != NULL) {
2862                 ret = folder->klass->add_msgs(folder, dest, file_list, relation);
2863                 if (ret < 0) {
2864                         g_relation_destroy(relation);
2865                         return ret;
2866                 }
2867         } else {
2868                 for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
2869                         fileinfo = (MsgFileInfo *) file_cur->data;
2870
2871                         ret = folder->klass->add_msg(folder, dest, fileinfo->file, fileinfo->flags);
2872                         if (ret < 0) {
2873                                 g_relation_destroy(relation);
2874                                 return ret;
2875                         }
2876                         g_relation_insert(relation, fileinfo, GINT_TO_POINTER(ret));
2877                 }
2878         }
2879
2880         for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
2881                 GTuples *tuples;
2882
2883                 fileinfo = (MsgFileInfo *) file_cur->data;
2884                 tuples = g_relation_select(relation, fileinfo, 0);
2885                 num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
2886                 g_tuples_destroy(tuples);
2887
2888                 if (num >= 0) {
2889                         MsgInfo *newmsginfo;
2890
2891                         if (num == 0) {
2892                                 if (!folderscan) {
2893                                         folder_item_scan_full(dest, FALSE);
2894                                         folderscan = TRUE;
2895                                 }
2896                                 num = folder_item_get_msg_num_by_file(dest, fileinfo->file);
2897                                 debug_print("got num %d\n", num);
2898                         }
2899
2900                         if (num > lastnum)
2901                                 lastnum = num;
2902
2903                         if (num >= 0 && remove_source) {
2904                                 if (g_unlink(fileinfo->file) < 0)
2905                                         FILE_OP_ERROR(fileinfo->file, "unlink");
2906                         }
2907
2908                         if (num == 0)
2909                                 continue;
2910
2911                         if (!folderscan && 
2912                             ((newmsginfo = get_msginfo(dest, num)) != NULL)) {
2913                                 add_msginfo_to_cache(dest, newmsginfo, NULL);
2914                                 procmsg_msginfo_free(newmsginfo);
2915                         } else if ((newmsginfo = msgcache_get_msg(dest->cache, num)) != NULL) {
2916                                 /* TODO: set default flags */
2917                                 procmsg_msginfo_free(newmsginfo);
2918                         }
2919                 }
2920         }
2921
2922         g_relation_destroy(relation);
2923
2924         return lastnum;
2925 }
2926
2927 static FolderItem *folder_item_move_recursive(FolderItem *src, FolderItem *dest, gboolean copy) 
2928 {
2929         GSList *mlist;
2930         FolderItem *new_item;
2931         FolderItem *next_item;
2932         GNode *srcnode;
2933         gchar *old_id, *new_id;
2934
2935         /* move messages */
2936         debug_print("%s %s to %s\n", copy?"Copying":"Moving", src->path, dest->path);
2937         new_item = folder_create_folder(dest, src->name);
2938         if (new_item == NULL) {
2939                 g_print("Can't create folder\n");
2940                 return NULL;
2941         }
2942         
2943         if (new_item->folder == NULL)
2944                 new_item->folder = dest->folder;
2945
2946         /* move messages */
2947         log_message(LOG_PROTOCOL, copy ?_("Copying %s to %s...\n"):_("Moving %s to %s...\n"), 
2948                         src->name, new_item->path);
2949
2950         mlist = folder_item_get_msg_list(src);
2951         
2952         if (mlist != NULL) {
2953                 if (copy)
2954                         folder_item_copy_msgs(new_item, mlist);
2955                 else
2956                         folder_item_move_msgs(new_item, mlist);
2957                 procmsg_msg_list_free(mlist);
2958         }
2959         
2960         /*copy prefs*/
2961         folder_item_prefs_copy_prefs(src, new_item);
2962         
2963         /* copy internal data */
2964         if (src->folder->klass == new_item->folder->klass &&
2965             src->folder->klass->copy_private_data != NULL)
2966                 src->folder->klass->copy_private_data(src->folder,
2967                                         src, new_item);
2968         new_item->collapsed = src->collapsed;
2969         new_item->thread_collapsed = src->thread_collapsed;
2970         new_item->threaded  = src->threaded;
2971         new_item->ret_rcpt  = src->ret_rcpt;
2972         new_item->hide_read_msgs = src->hide_read_msgs;
2973         new_item->sort_key  = src->sort_key;
2974         new_item->sort_type = src->sort_type;
2975
2976         prefs_matcher_write_config();
2977         
2978         /* recurse */
2979         srcnode = src->folder->node;    
2980         srcnode = g_node_find(srcnode, G_PRE_ORDER, G_TRAVERSE_ALL, src);
2981         srcnode = srcnode->children;
2982         while (srcnode != NULL) {
2983                 if (srcnode && srcnode->data) {
2984                         next_item = (FolderItem*) srcnode->data;
2985                         srcnode = srcnode->next;
2986                         if (folder_item_move_recursive(next_item, new_item, copy) == NULL) {
2987                                 return NULL;
2988                         }
2989                 }
2990         }
2991         old_id = folder_item_get_identifier(src);
2992         new_id = folder_item_get_identifier(new_item);
2993
2994         /* if src supports removing, otherwise only copy folder */
2995         if (src->folder->klass->remove_folder != NULL && !copy) 
2996                 src->folder->klass->remove_folder(src->folder, src);
2997         folder_write_list();
2998
2999         if (!copy) {
3000                 debug_print("updating rules : %s => %s\n", old_id, new_id);
3001                 if (old_id != NULL && new_id != NULL) {
3002                         prefs_filtering_rename_path(old_id, new_id);
3003                         account_rename_path(old_id, new_id);
3004                 }
3005         }
3006         g_free(old_id);
3007         g_free(new_id);
3008         
3009         return new_item;
3010 }
3011
3012 gint folder_item_move_to(FolderItem *src, FolderItem *dest, FolderItem **new_item, gboolean copy)
3013 {
3014         FolderItem *tmp = folder_item_parent(dest);
3015         gchar * src_identifier, * dst_identifier;
3016         gchar * phys_srcpath, * phys_dstpath, *tmppath;
3017
3018         while (tmp) {
3019                 if (tmp == src) {
3020                         return F_MOVE_FAILED_DEST_IS_CHILD;
3021                 }
3022                 tmp = folder_item_parent(tmp);
3023         }
3024         
3025         tmp = folder_item_parent(src);
3026         
3027         src_identifier = folder_item_get_identifier(src);
3028         dst_identifier = folder_item_get_identifier(dest);
3029         
3030         if(dst_identifier == NULL && dest->folder && folder_item_parent(dest) == NULL) {
3031                 /* dest can be a root folder */
3032                 dst_identifier = folder_get_identifier(dest->folder);
3033         }
3034         if (src_identifier == NULL || dst_identifier == NULL) {
3035                 debug_print("Can't get identifiers\n");
3036                 return F_MOVE_FAILED;
3037         }
3038
3039         if (src->folder != dest->folder && !copy) {
3040                 return F_MOVE_FAILED_DEST_OUTSIDE_MAILBOX;
3041         }
3042
3043         phys_srcpath = folder_item_get_path(src);
3044         tmppath = folder_item_get_path(dest);
3045         phys_dstpath = g_strconcat(tmppath,
3046                        G_DIR_SEPARATOR_S,
3047                        g_path_get_basename(phys_srcpath),
3048                        NULL);
3049         g_free(tmppath);
3050
3051         if (folder_item_parent(src) == dest || src == dest) {
3052                 g_free(src_identifier);
3053                 g_free(dst_identifier);
3054                 g_free(phys_srcpath);
3055                 g_free(phys_dstpath);
3056                 return F_MOVE_FAILED_DEST_IS_PARENT;
3057         }
3058         debug_print("moving \"%s\" to \"%s\"\n", phys_srcpath, phys_dstpath);
3059         if ((tmp = folder_item_move_recursive(src, dest, copy)) == NULL) {
3060                 return F_MOVE_FAILED;
3061         }
3062         
3063         g_free(src_identifier);
3064         g_free(dst_identifier);
3065         g_free(phys_srcpath);
3066         g_free(phys_dstpath);
3067
3068         *new_item = tmp;
3069
3070         return F_MOVE_OK;
3071 }
3072
3073 /**
3074  * Copy a list of message to a new folder and remove
3075  * source messages if wanted
3076  */
3077 static gint do_copy_msgs(FolderItem *dest, GSList *msglist, gboolean remove_source)
3078 {
3079         Folder *folder;
3080         GSList *l;
3081         gint num, lastnum = -1;
3082         gboolean folderscan = FALSE;
3083         GRelation *relation;
3084         GSList *not_moved = NULL;
3085         gint total = 0, curmsg = 0;
3086         MsgInfo *msginfo = NULL;
3087
3088         g_return_val_if_fail(dest != NULL, -1);
3089         g_return_val_if_fail(msglist != NULL, -1);
3090
3091         folder = dest->folder;
3092
3093         g_return_val_if_fail(folder->klass->copy_msg != NULL, -1);
3094         if (dest->no_select)
3095                 return -1;
3096
3097         msginfo = (MsgInfo *)msglist->data;
3098         
3099         if (!msginfo)
3100                 return -1;
3101         
3102         if (!MSG_IS_QUEUED(msginfo->flags) && 
3103             MSG_IS_DRAFT(msginfo->flags) && 
3104             folder_has_parent_of_type(dest, F_QUEUE)) {
3105                 GSList *cur = msglist;
3106                 gboolean queue_err = FALSE;
3107                 for (; cur; cur = cur->next) {
3108                         Compose *compose = NULL;
3109                         FolderItem *queue = dest;
3110                         int val = 0;
3111                         
3112                         msginfo = (MsgInfo *)cur->data;
3113                         compose = compose_reedit(msginfo, TRUE);
3114                         if (compose == NULL) {
3115                                 queue_err = TRUE;
3116                                 continue;
3117                         }
3118                         val = compose_queue(compose, NULL, &queue, NULL,
3119                                         FALSE);
3120                         if (val < 0) {
3121                                 queue_err = TRUE;
3122                         } else if (remove_source) {
3123                                 folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
3124                         }
3125                         if (val == 0)
3126                                 compose_close(compose);
3127                 }
3128                 return queue_err ? -1:0;
3129         }
3130
3131         relation = g_relation_new(2);
3132         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
3133         g_relation_index(relation, 1, g_direct_hash, g_direct_equal);
3134
3135         for (l = msglist ; l != NULL ; l = g_slist_next(l)) {
3136                 MsgInfo * msginfo = (MsgInfo *) l->data;
3137
3138                 if (msginfo->planned_download != 0) {
3139                         int old_planned = msginfo->planned_download;
3140                         partial_unmark(msginfo);
3141                         /* little hack to reenable after */
3142                         msginfo->planned_download = old_planned;
3143                 }
3144         }
3145
3146         /* 
3147          * Copy messages to destination folder and 
3148          * store new message numbers in newmsgnums
3149          */
3150         if (folder->klass->copy_msgs != NULL) {
3151                 if (folder->klass->copy_msgs(folder, dest, msglist, relation) < 0) {
3152                         g_relation_destroy(relation);
3153                         return -1;
3154                 }
3155         } else {
3156                 MsgInfo * msginfo;
3157                 l = msglist;
3158
3159                 /* immediately stop if src and dest folders are identical */
3160                 if (l != NULL) {
3161                         msginfo = (MsgInfo *) l->data;
3162                         if (msginfo != NULL && msginfo->folder == dest) {
3163                                 g_relation_destroy(relation);
3164                                 return -1;
3165                         }
3166                 }
3167
3168                 for (; l != NULL ; l = g_slist_next(l)) {
3169                         msginfo = (MsgInfo *) l->data;
3170
3171                         num = folder->klass->copy_msg(folder, dest, msginfo);
3172                         if (num > 0)
3173                                 g_relation_insert(relation, msginfo, GINT_TO_POINTER(num));
3174                         else
3175                                 not_moved = g_slist_prepend(not_moved, msginfo);
3176                 }
3177         }
3178
3179         if (remove_source) {
3180                 MsgInfo *msginfo = (MsgInfo *) msglist->data;
3181                 FolderItem *item = msginfo->folder;
3182                 /*
3183                  * Remove source messages from their folders if
3184                  * copying was successfull and update folder
3185                  * message counts
3186                  */
3187                 if (not_moved == NULL && item->folder->klass->remove_msgs) {
3188                         item->folder->klass->remove_msgs(item->folder,
3189                                                                 msginfo->folder,
3190                                                                 msglist,
3191                                                                 relation);
3192                 }
3193                 for (l = msglist; l != NULL; l = g_slist_next(l)) {
3194                         GTuples *tuples;
3195                         msginfo = (MsgInfo *) l->data;
3196                         item = msginfo->folder;
3197
3198                         tuples = g_relation_select(relation, msginfo, 0);
3199                         if (tuples) {
3200                                 if (tuples->len)
3201                                         num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
3202                                 else
3203                                         num = 0;
3204                                 g_tuples_destroy(tuples);
3205                         } else {
3206                                 num = -1;
3207                         }
3208
3209                         if (g_slist_find(not_moved, msginfo))
3210                                 continue;
3211
3212                         if ((num >= 0) && (item->folder->klass->remove_msg != NULL)) {
3213                                 if (!item->folder->klass->remove_msgs)
3214                                         item->folder->klass->remove_msg(item->folder,
3215                                                                 msginfo->folder,
3216                                                                 msginfo->msgnum);
3217                                 remove_msginfo_from_cache(item, msginfo);
3218                         }
3219                 }
3220         }
3221
3222         /* Read cache for dest folder */
3223         if (!dest->cache) folder_item_read_cache(dest);
3224
3225         /* 
3226          * Fetch new MsgInfos for new messages in dest folder,
3227          * add them to the msgcache and update folder message counts
3228          */
3229         if (g_relation_count(relation, GINT_TO_POINTER(0), 1) > 0) {
3230                 folder_item_scan_full(dest, FALSE);
3231                 folderscan = TRUE;
3232         }
3233
3234         statusbar_print_all(_("Updating cache for %s..."), dest->path ? dest->path : "(null)");
3235         total = g_slist_length(msglist);
3236         for (l = msglist; l != NULL; l = g_slist_next(l)) {
3237                 MsgInfo *msginfo = (MsgInfo *) l->data;
3238                 GTuples *tuples;
3239
3240                 tuples = g_relation_select(relation, msginfo, 0);
3241                 if (tuples->len > 0) {
3242                         num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
3243                         g_tuples_destroy(tuples);
3244                 } else {
3245                         num = 0;
3246                         if (tuples)
3247                                 g_tuples_destroy(tuples);
3248                 }
3249                 statusbar_progress_all(curmsg++,total, 100);
3250                 if (curmsg % 100 == 0)
3251                         GTK_EVENTS_FLUSH();
3252
3253                 if (num >= 0) {
3254                         MsgInfo *newmsginfo = NULL;
3255
3256                         if (!folderscan && num > 0) {
3257                                 newmsginfo = get_msginfo(dest, num);
3258                                 if (newmsginfo != NULL) {
3259                                         add_msginfo_to_cache(dest, newmsginfo, msginfo);
3260                                 }
3261                         }
3262                         if (newmsginfo == NULL) {
3263                                 if (!folderscan) {
3264                                         folder_item_scan_full(dest, FALSE);
3265                                         folderscan = TRUE;
3266                                 }
3267                                 if (msginfo->msgid != NULL) {
3268                                         newmsginfo = folder_item_get_msginfo_by_msgid(dest, msginfo->msgid);
3269                                         if (newmsginfo != NULL) {
3270                                                 copy_msginfo_flags(msginfo, newmsginfo);
3271                                                 num = newmsginfo->msgnum;
3272                                         }
3273                                 }
3274                         }
3275
3276                         if (msginfo->planned_download 
3277                             == POP3_PARTIAL_DLOAD_DELE) {
3278                                 partial_mark_for_delete(newmsginfo);
3279                         }
3280                         if (msginfo->planned_download 
3281                             == POP3_PARTIAL_DLOAD_DLOAD) {
3282                                 partial_mark_for_download(newmsginfo);
3283                         }
3284                         if (!MSG_IS_POSTFILTERED (msginfo->flags)) {
3285                             procmsg_msginfo_set_flags (   msginfo, MSG_POSTFILTERED, 0);
3286                             procmsg_msginfo_set_flags (newmsginfo, MSG_POSTFILTERED, 0);
3287                             hooks_invoke (MAIL_POSTFILTERING_HOOKLIST, newmsginfo);
3288                         }
3289                         procmsg_msginfo_free(newmsginfo);
3290
3291
3292                         if (num > lastnum)
3293                                 lastnum = num;
3294                 }
3295         }
3296         statusbar_progress_all(0,0,0);
3297         statusbar_pop_all();
3298
3299         g_relation_destroy(relation);
3300         if (not_moved != NULL) {
3301                 g_slist_free(not_moved);
3302                 return -1;
3303         } else
3304                 return lastnum;
3305 }
3306
3307 /**
3308  * Move a message to a new folder.
3309  *
3310  * \param dest Destination folder
3311  * \param msginfo The message
3312  */
3313 gint folder_item_move_msg(FolderItem *dest, MsgInfo *msginfo)
3314 {
3315         GSList list;
3316
3317         g_return_val_if_fail(dest != NULL, -1);
3318         g_return_val_if_fail(msginfo != NULL, -1);
3319
3320         list.data = msginfo;
3321         list.next = NULL;
3322
3323         return do_copy_msgs(dest, &list, TRUE);
3324 }
3325
3326 /**
3327  * Move a list of messages to a new folder.
3328  *
3329  * \param dest Destination folder
3330  * \param msglist List of messages
3331  */
3332 gint folder_item_move_msgs(FolderItem *dest, GSList *msglist)
3333 {
3334         gint result = -1;
3335         g_return_val_if_fail(dest != NULL, -1);
3336         g_return_val_if_fail(msglist != NULL, -1);
3337         inc_lock();
3338         result = do_copy_msgs(dest, msglist, TRUE);
3339         inc_unlock();
3340         return result;
3341 }
3342
3343 /**
3344  * Copy a message to a new folder.
3345  *
3346  * \param dest Destination folder
3347  * \param msginfo The message
3348  */
3349 gint folder_item_copy_msg(FolderItem *dest, MsgInfo *msginfo)
3350 {
3351         GSList list;
3352
3353         g_return_val_if_fail(dest != NULL, -1);
3354         g_return_val_if_fail(msginfo != NULL, -1);
3355     
3356         list.data = msginfo;
3357         list.next = NULL;
3358
3359         return do_copy_msgs(dest, &list, FALSE);
3360 }
3361
3362 /**
3363  * Copy a list of messages to a new folder.
3364  *
3365  * \param dest Destination folder
3366  * \param msglist List of messages
3367  */
3368 gint folder_item_copy_msgs(FolderItem *dest, GSList *msglist)
3369 {
3370         gint result;
3371         g_return_val_if_fail(dest != NULL, -1);
3372         g_return_val_if_fail(msglist != NULL, -1);
3373
3374         inc_lock();
3375         result = do_copy_msgs(dest, msglist, FALSE);
3376         inc_unlock();
3377         
3378         return result;
3379 }
3380
3381 gint folder_item_remove_msg(FolderItem *item, gint num)
3382 {
3383         Folder *folder;
3384         gint ret;
3385         MsgInfo *msginfo;
3386
3387         g_return_val_if_fail(item != NULL, -1);
3388         folder = item->folder;
3389         g_return_val_if_fail(folder->klass->remove_msg != NULL, -1);
3390         if (item->no_select)
3391                 return -1;
3392
3393         if (!item->cache) folder_item_read_cache(item);
3394
3395         msginfo = msgcache_get_msg(item->cache, num);
3396         if (msginfo && MSG_IS_LOCKED(msginfo->flags)) {
3397                 procmsg_msginfo_free(msginfo);
3398                 return -1;
3399         }
3400         ret = folder->klass->remove_msg(folder, item, num);
3401
3402         if (msginfo != NULL) {
3403                 remove_msginfo_from_cache(item, msginfo);
3404                 procmsg_msginfo_free(msginfo);
3405         }
3406
3407         return ret;
3408 }
3409
3410 gint folder_item_remove_msgs(FolderItem *item, GSList *msglist)
3411 {
3412         Folder *folder;
3413         gint ret = 0;
3414
3415         g_return_val_if_fail(item != NULL, -1);
3416         folder = item->folder;
3417         g_return_val_if_fail(folder != NULL, -1);
3418         if (item->no_select)
3419                 return -1;
3420         inc_lock();
3421         if (!item->cache) folder_item_read_cache(item);
3422
3423         folder_item_update_freeze();
3424         if (item->folder->klass->remove_msgs) {
3425                 ret = item->folder->klass->remove_msgs(item->folder,
3426                                                         item,
3427                                                         msglist,
3428                                                         NULL);
3429         }
3430         while (ret == 0 && msglist != NULL) {
3431                 MsgInfo *msginfo = (MsgInfo *)msglist->data;
3432                 if (msginfo && MSG_IS_LOCKED(msginfo->flags)) {
3433                         msglist = msglist->next;
3434                         continue;
3435                 }
3436                 if (!item->folder->klass->remove_msgs)
3437                         ret = folder_item_remove_msg(item, msginfo->msgnum);
3438                 if (ret != 0) break;
3439                 msgcache_remove_msg(item->cache, msginfo->msgnum);
3440                 msglist = msglist->next;
3441         }
3442         folder_item_scan_full(item, FALSE);
3443         folder_item_update_thaw();
3444         inc_unlock();
3445         return ret;
3446 }
3447
3448 gint folder_item_remove_all_msg(FolderItem *item)
3449 {
3450         Folder *folder;
3451         gint result;
3452
3453         g_return_val_if_fail(item != NULL, -1);
3454         if (item->no_select)
3455                 return -1;
3456
3457         folder = item->folder;
3458
3459         inc_lock();
3460         if (folder->klass->remove_all_msg != NULL) {
3461                 result = folder->klass->remove_all_msg(folder, item);
3462
3463                 if (result == 0) {
3464                         folder_item_free_cache(item, TRUE);
3465                         item->cache = msgcache_new();
3466                 }
3467         } else {
3468                 MsgInfoList *msglist;
3469
3470                 msglist = folder_item_get_msg_list(item);
3471                 result = folder_item_remove_msgs(item, msglist);
3472                 procmsg_msg_list_free(msglist);
3473         }
3474
3475         if (result == 0) {
3476                 item->new_msgs = 0;
3477                 item->unread_msgs = 0;
3478                 item->unreadmarked_msgs = 0;
3479                 item->marked_msgs = 0;
3480                 item->total_msgs = 0;
3481                 folder_item_update(item, F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT);
3482         }
3483
3484         inc_unlock();
3485         return result;
3486 }
3487
3488 void folder_item_change_msg_flags(FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
3489 {
3490         g_return_if_fail(item != NULL);
3491         g_return_if_fail(msginfo != NULL);
3492         if (item->no_select)
3493                 return;
3494         
3495         if (item->folder->klass->change_flags != NULL) {
3496                 item->folder->klass->change_flags(item->folder, item, msginfo, newflags);
3497         } else {
3498                 msginfo->flags.perm_flags = newflags;
3499         }
3500 }
3501
3502 void folder_item_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
3503 {
3504         Folder *folder = NULL;
3505
3506         if (!msginfo)
3507                 return;
3508         if (!item)
3509                 return;
3510         if (!tags_set && !tags_unset)
3511                 return;
3512
3513         folder = item->folder;
3514         if (!folder)
3515                 return;
3516         
3517         if (folder->klass->commit_tags == NULL)
3518                 return;
3519         
3520         folder->klass->commit_tags(item, msginfo, tags_set, tags_unset);
3521 }
3522
3523 gboolean folder_item_is_msg_changed(FolderItem *item, MsgInfo *msginfo)
3524 {
3525         Folder *folder;
3526
3527         g_return_val_if_fail(item != NULL, FALSE);
3528         if (item->no_select)
3529                 return FALSE;
3530
3531         folder = item->folder;
3532
3533         g_return_val_if_fail(folder->klass->is_msg_changed != NULL, -1);
3534
3535         return folder->klass->is_msg_changed(folder, item, msginfo);
3536 }
3537
3538 void folder_item_discard_cache(FolderItem *item)
3539 {
3540         gchar *dir;
3541         gchar *cache;
3542
3543         if (!item)
3544                 return;
3545
3546         if (item->cache) {
3547                 msgcache_destroy(item->cache);
3548                 item->cache = NULL;
3549         }
3550         dir = folder_item_get_path(item);
3551         if (is_dir_exist(dir))
3552                 remove_all_numbered_files(dir);
3553         g_free(dir);
3554         
3555         cache = folder_item_get_cache_file(item);
3556         if (is_file_exist(cache))
3557                 g_unlink(cache);
3558         g_free(cache);
3559         
3560 }
3561
3562 static gchar *folder_item_get_cache_file(FolderItem *item)
3563 {
3564         gchar *path;
3565         gchar *file;
3566         gchar *old_file;
3567
3568         g_return_val_if_fail(item != NULL, NULL);
3569         g_return_val_if_fail(item->path != NULL, NULL);
3570
3571         path = folder_item_get_path(item);
3572         g_return_val_if_fail(path != NULL, NULL);
3573         if (!is_dir_exist(path))
3574                 make_dir_hier(path);
3575         file = g_strconcat(path, G_DIR_SEPARATOR_S, CACHE_FILE, NULL);
3576         old_file = g_strconcat(path, G_DIR_SEPARATOR_S, OLD_CACHE_FILE, NULL);
3577
3578         if (!is_file_exist(file) && is_file_exist(old_file))
3579                 move_file(old_file, file, FALSE);
3580         g_free(old_file);
3581         g_free(path);
3582
3583         return file;
3584 }
3585
3586 static gchar *folder_item_get_mark_file(FolderItem *item)
3587 {
3588         gchar *path;
3589         gchar *file;
3590         gchar *old_file;
3591
3592         g_return_val_if_fail(item != NULL, NULL);
3593         g_return_val_if_fail(item->path != NULL, NULL);
3594
3595         path = folder_item_get_path(item);
3596         g_return_val_if_fail(path != NULL, NULL);
3597         if (!is_dir_exist(path))
3598                 make_dir_hier(path);
3599         file = g_strconcat(path, G_DIR_SEPARATOR_S, MARK_FILE, NULL);
3600         old_file = g_strconcat(path, G_DIR_SEPARATOR_S, OLD_MARK_FILE, NULL);
3601
3602         if (!is_file_exist(file) && is_file_exist(old_file))
3603                 move_file(old_file, file, FALSE);
3604         g_free(old_file);
3605         g_free(path);
3606
3607         return file;
3608 }
3609
3610 static gchar *folder_item_get_tags_file(FolderItem *item)
3611 {
3612         gchar *path;
3613         gchar *identifier;
3614         gchar *file;
3615
3616         /* we save tags files in rc_dir, because tagsrc is there too,
3617          * and storing tags directly in the mailboxes would give strange
3618          * result when using another Claws mailbox from another install
3619          * with different tags. */
3620
3621         g_return_val_if_fail(item != NULL, NULL);
3622
3623         identifier = folder_item_get_identifier(item);
3624         g_return_val_if_fail(identifier != NULL, NULL);
3625
3626 #ifdef G_OS_WIN32
3627         while (strchr(identifier, '/'))
3628                 *strchr(identifier, '/') = '\\';
3629 #endif
3630
3631         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
3632                            "tagsdb", G_DIR_SEPARATOR_S,
3633                            identifier, NULL);
3634         
3635         g_free(identifier);
3636                            
3637         if (!is_dir_exist(path))
3638                 make_dir_hier(path);
3639
3640         file = g_strconcat(path, G_DIR_SEPARATOR_S, TAGS_FILE, NULL);
3641         
3642         g_free(path);
3643
3644         return file;
3645 }
3646
3647 static gpointer xml_to_folder_item(gpointer nodedata, gpointer data)
3648 {
3649         XMLNode *xmlnode = (XMLNode *) nodedata;
3650         Folder *folder = (Folder *) data;
3651         FolderItem *item;
3652
3653         g_return_val_if_fail(xmlnode != NULL, NULL);
3654         g_return_val_if_fail(folder != NULL, NULL);
3655
3656         if (strcmp2(xmlnode->tag->tag, "folderitem") != 0) {
3657                 g_warning("tag name != \"folderitem\"\n");
3658                 return NULL;
3659         }
3660
3661         item = folder_item_new(folder, "", "");
3662         if (folder->klass->item_set_xml != NULL)
3663                 folder->klass->item_set_xml(folder, item, xmlnode->tag);
3664         else
3665                 folder_item_set_xml(folder, item, xmlnode->tag);
3666
3667         item->folder = folder;
3668
3669         switch (item->stype) {
3670         case F_INBOX:  folder->inbox  = item; break;
3671         case F_OUTBOX: folder->outbox = item; break;
3672         case F_DRAFT:  folder->draft  = item; break;
3673         case F_QUEUE:  folder->queue  = item; break;
3674         case F_TRASH:  folder->trash  = item; break;
3675         default:       break;
3676         }
3677         folder_item_prefs_read_config(item);
3678
3679         return item;
3680 }
3681
3682 static gboolean folder_item_set_node(GNode *node, gpointer data)
3683 {
3684         FolderItem *item = (FolderItem *) node->data;
3685         item->node = node;
3686
3687         return FALSE;
3688 }
3689
3690 static Folder *folder_get_from_xml(GNode *node)
3691 {
3692         Folder *folder;
3693         XMLNode *xmlnode;
3694         GList *list;
3695         FolderClass *klass = NULL;
3696         GNode *cur;
3697
3698         g_return_val_if_fail(node->data != NULL, NULL);
3699
3700         xmlnode = node->data;
3701         if (strcmp2(xmlnode->tag->tag, "folder") != 0) {
3702                 g_warning("tag name != \"folder\"\n");
3703                 return NULL;
3704         }
3705         list = xmlnode->tag->attr;
3706         for (; list != NULL; list = list->next) {
3707                 XMLAttr *attr = list->data;
3708
3709                 if (!attr || !attr->name || !attr->value) continue;
3710                 if (!strcmp(attr->name, "type"))
3711                         klass = folder_get_class_from_string(attr->value);
3712         }
3713         if (klass == NULL)
3714                 return NULL;
3715
3716         folder = folder_new(klass, "", "");
3717         g_return_val_if_fail(folder != NULL, NULL);
3718
3719         if (klass->set_xml)
3720                 klass->set_xml(folder, xmlnode->tag);
3721         else
3722                 folder_set_xml(folder, xmlnode->tag);
3723
3724         cur = node->children;
3725         while (cur != NULL) {
3726                 GNode *itemnode;
3727
3728                 itemnode = g_node_map(cur, xml_to_folder_item, (gpointer) folder);
3729                 g_node_append(folder->node, itemnode);
3730                 cur = cur->next;
3731         }
3732         g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, folder_item_set_node, NULL);
3733         
3734         return folder;
3735 }
3736
3737 static gchar *folder_get_list_path(void)
3738 {
3739         static gchar *filename = NULL;
3740
3741         if (!filename)
3742                 filename =  g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
3743                                         FOLDER_LIST, NULL);
3744
3745         return filename;
3746 }
3747
3748 static gpointer folder_item_to_xml(gpointer nodedata, gpointer data)
3749 {
3750         FolderItem *item = (FolderItem *) nodedata;
3751         XMLTag *tag;
3752
3753         g_return_val_if_fail(item != NULL, NULL);
3754
3755         if (item->folder->klass->item_get_xml != NULL)
3756                 tag = item->folder->klass->item_get_xml(item->folder, item);
3757         else
3758                 tag = folder_item_get_xml(item->folder, item);
3759
3760         return xml_node_new(tag, NULL);
3761 }
3762
3763 static GNode *folder_get_xml_node(Folder *folder)
3764 {
3765         GNode *node;
3766         XMLNode *xmlnode;
3767         XMLTag *tag;
3768
3769         g_return_val_if_fail(folder != NULL, NULL);
3770
3771         if (folder->klass->get_xml != NULL)
3772                 tag = folder->klass->get_xml(folder);
3773         else
3774                 tag = folder_get_xml(folder);
3775
3776         xml_tag_add_attr(tag, xml_attr_new("type", folder->klass->idstr));
3777
3778         xmlnode = xml_node_new(tag, NULL);
3779
3780         node = g_node_new(xmlnode);
3781         
3782         g_return_val_if_fail (folder->node != NULL, NULL);
3783         
3784         if (folder->node->children) {
3785                 GNode *cur;
3786
3787                 cur = folder->node->children;
3788                 while (cur) {
3789                         GNode *xmlnode;
3790
3791                         xmlnode = g_node_map(cur, folder_item_to_xml, (gpointer) folder);
3792                         g_node_append(node, xmlnode);
3793                         cur = cur->next;
3794                 }
3795         }
3796
3797         return node;
3798 }
3799
3800 static void folder_update_op_count_rec(GNode *node)
3801 {
3802         FolderItem *fitem = FOLDER_ITEM(node->data);
3803
3804         if (g_node_depth(node) > 0) {
3805                 if (fitem->op_count > 0) {
3806                         fitem->op_count = 0;
3807                         folder_item_update(fitem, F_ITEM_UPDATE_MSGCNT);
3808                 }
3809                 if (node->children) {
3810                         GNode *child;
3811
3812                         child = node->children;
3813                         while (child) {
3814                                 GNode *cur;
3815
3816                                 cur = child;
3817                                 child = cur->next;
3818                                 folder_update_op_count_rec(cur);
3819                         }
3820                 }
3821         }
3822 }
3823
3824 void folder_update_op_count(void) 
3825 {
3826         GList *cur;
3827         Folder *folder;
3828
3829         for (cur = folder_list; cur != NULL; cur = cur->next) {
3830                 folder = cur->data;
3831                 folder_update_op_count_rec(folder->node);
3832         }
3833 }
3834
3835 typedef struct _type_str {
3836         gchar * str;
3837         gint type;
3838 } type_str;
3839
3840
3841 /*
3842 static gchar * folder_item_get_tree_identifier(FolderItem * item)
3843 {
3844         if (item->parent != NULL) {
3845                 gchar * path;
3846                 gchar * id;
3847
3848                 path = folder_item_get_tree_identifier(item->parent);
3849                 if (path == NULL)
3850                         return NULL;
3851
3852                 id = g_strconcat(path, "/", item->name, NULL);
3853                 g_free(path);
3854
3855                 return id;
3856         }
3857         else {
3858                 return g_strconcat("/", item->name, NULL);
3859         }
3860 }
3861 */
3862
3863 /* CLAWS: temporary local folder for filtering */
3864 #define TEMP_FOLDER "TEMP_FOLDER"
3865 #define PROCESSING_FOLDER_ITEM "processing"     
3866
3867 static FolderItem *processing_folder_item;
3868
3869 static void folder_create_processing_folder(void)
3870 {
3871         Folder *processing_folder;
3872         gchar      *tmpname;
3873
3874         if ((processing_folder = folder_find_from_name(TEMP_FOLDER, mh_get_class())) == NULL) {
3875                 gchar *tmppath;
3876
3877                 tmppath =
3878                     g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
3879                                 "tempfolder", NULL);
3880                 processing_folder =
3881                     folder_new(mh_get_class(), TEMP_FOLDER, tmppath);
3882                 g_free(tmppath);
3883         }
3884         g_assert(processing_folder != NULL);
3885
3886         debug_print("tmpparentroot %s\n", LOCAL_FOLDER(processing_folder)->rootpath);
3887         /* FIXME: [W32] The code below does not correctly merge
3888            relative filenames; there should be a function to handle
3889            this.  */
3890         if (!is_relative_filename(LOCAL_FOLDER(processing_folder)->rootpath))
3891                 tmpname = g_strconcat(LOCAL_FOLDER(processing_folder)->rootpath,
3892                                       G_DIR_SEPARATOR_S, PROCESSING_FOLDER_ITEM,
3893                                       NULL);
3894         else
3895                 tmpname = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3896                                       LOCAL_FOLDER(processing_folder)->rootpath,
3897                                       G_DIR_SEPARATOR_S, PROCESSING_FOLDER_ITEM,
3898                                       NULL);
3899
3900         if (!is_dir_exist(tmpname)) {
3901                 debug_print("*TMP* creating %s\n", tmpname);
3902                 processing_folder_item = processing_folder->klass->create_folder(processing_folder,
3903                                                                                  processing_folder->node->data,
3904                                                                                  PROCESSING_FOLDER_ITEM);
3905         } else {
3906                 debug_print("*TMP* already created\n");
3907                 processing_folder_item = folder_item_new(processing_folder, PROCESSING_FOLDER_ITEM, PROCESSING_FOLDER_ITEM);
3908                 g_assert(processing_folder_item);
3909                 folder_item_append(processing_folder->node->data, processing_folder_item);
3910         }
3911         g_assert(processing_folder_item != NULL);
3912         g_free(tmpname);
3913 }
3914
3915 FolderItem *folder_get_default_processing(void)
3916 {
3917         if (!processing_folder_item) {
3918                 folder_create_processing_folder();
3919         }
3920         return processing_folder_item;
3921 }
3922
3923 /* folder_persist_prefs_new() - return hash table with persistent
3924  * settings (and folder name as key). 
3925  * (note that in claws other options are in the folder_item_prefs_RC
3926  * file, so those don't need to be included in PersistPref yet) 
3927  */
3928 static GHashTable *folder_persist_prefs_new(Folder *folder)
3929 {
3930         GHashTable *pptable;
3931
3932         g_return_val_if_fail(folder, NULL);
3933         pptable = g_hash_table_new(g_str_hash, g_str_equal);
3934         folder_get_persist_prefs_recursive(folder->node, pptable);
3935         return pptable;
3936 }
3937
3938 static void folder_persist_prefs_free(GHashTable *pptable)
3939 {
3940         g_return_if_fail(pptable);
3941         g_hash_table_foreach_remove(pptable, persist_prefs_free, NULL);
3942         g_hash_table_destroy(pptable);
3943 }
3944
3945 static const PersistPrefs *folder_get_persist_prefs(GHashTable *pptable, const char *name)
3946 {
3947         if (pptable == NULL || name == NULL) return NULL;
3948         return g_hash_table_lookup(pptable, name);
3949 }
3950
3951 static void folder_item_restore_persist_prefs(FolderItem *item, GHashTable *pptable)
3952 {
3953         const PersistPrefs *pp;
3954         gchar *id = folder_item_get_identifier(item);
3955
3956         pp = folder_get_persist_prefs(pptable, id); 
3957         g_free(id);
3958
3959         if (!pp) return;
3960
3961         /* CLAWS: since not all folder properties have been migrated to 
3962          * folderlist.xml, we need to call the old stuff first before
3963          * setting things that apply both to Main and Claws. */
3964         folder_item_prefs_read_config(item); 
3965
3966         item->collapsed = pp->collapsed;
3967         item->thread_collapsed = pp->thread_collapsed;
3968         item->threaded  = pp->threaded;
3969         item->ret_rcpt  = pp->ret_rcpt;
3970         item->hide_read_msgs = pp->hide_read_msgs;
3971         item->sort_key  = pp->sort_key;
3972         item->sort_type = pp->sort_type;
3973 }
3974
3975 static void folder_get_persist_prefs_recursive(GNode *node, GHashTable *pptable)
3976 {
3977         FolderItem *item = FOLDER_ITEM(node->data);
3978         PersistPrefs *pp;
3979         GNode *child, *cur;
3980         gchar *id;
3981
3982         g_return_if_fail(node != NULL);
3983         g_return_if_fail(item != NULL);
3984
3985         /* NOTE: item->path == NULL means top level folder; not interesting
3986          * to store preferences of that one.  */
3987         if (item->path) {
3988                 id = folder_item_get_identifier(item);
3989                 pp = g_new0(PersistPrefs, 1);
3990                 g_return_if_fail(pp != NULL);
3991                 pp->collapsed = item->collapsed;
3992                 pp->thread_collapsed = item->thread_collapsed;
3993                 pp->threaded  = item->threaded;
3994                 pp->ret_rcpt  = item->ret_rcpt; 
3995                 pp->hide_read_msgs = item->hide_read_msgs;
3996                 pp->sort_key  = item->sort_key;
3997                 pp->sort_type = item->sort_type;
3998                 g_hash_table_insert(pptable, id, pp);
3999         }
4000
4001         if (node->children) {
4002                 child = node->children;
4003                 while (child) {
4004                         cur = child;
4005                         child = cur->next;
4006                         folder_get_persist_prefs_recursive(cur, pptable);
4007                 }
4008         }       
4009 }
4010
4011 static gboolean persist_prefs_free(gpointer key, gpointer val, gpointer data)
4012 {
4013         g_free(key);
4014         g_free(val);
4015         return TRUE;    
4016 }
4017
4018 void folder_item_apply_processing(FolderItem *item)
4019 {
4020         GSList *processing_list;
4021         GSList *mlist, *cur;
4022         guint total = 0, curmsg = 0;
4023         gint last_apply_per_account;
4024
4025         g_return_if_fail(item != NULL);
4026
4027         if (item->no_select)
4028                return;
4029
4030         processing_list = item->prefs->processing;
4031
4032         if (!pre_global_processing && !processing_list
4033         &&  !post_global_processing)
4034                 return;
4035
4036         debug_print("processing %s\n", item->name);
4037         folder_item_update_freeze();
4038
4039         inc_lock();
4040
4041         mlist = folder_item_get_msg_list(item);
4042         total = g_slist_length(mlist);
4043         statusbar_print_all(_("Processing messages..."));
4044
4045         last_apply_per_account = prefs_common.apply_per_account_filtering_rules;
4046         prefs_common.apply_per_account_filtering_rules = FILTERING_ACCOUNT_RULES_SKIP;
4047
4048         for (cur = mlist ; cur != NULL ; cur = cur->next) {
4049                 MsgInfo * msginfo;
4050
4051                 msginfo = (MsgInfo *) cur->data;
4052                 
4053                 /* reset parameters that can be modified by processing */
4054                 msginfo->hidden = 0;
4055                 msginfo->score = 0;
4056
4057                 statusbar_progress_all(curmsg++,total, 10);
4058
4059                 /* apply pre global rules */
4060                 filter_message_by_msginfo(pre_global_processing, msginfo, NULL,
4061                                 FILTERING_PRE_PROCESSING, NULL);
4062                 
4063                 /* apply rules of the folder */
4064                 filter_message_by_msginfo(processing_list, msginfo, NULL,
4065                                 FILTERING_FOLDER_PROCESSING, item->name);
4066
4067                 /* apply post global rules */
4068                 filter_message_by_msginfo(post_global_processing, msginfo, NULL,
4069                                 FILTERING_POST_PROCESSING, NULL);
4070                 if (curmsg % 1000 == 0)
4071                         GTK_EVENTS_FLUSH();
4072         }
4073         prefs_common.apply_per_account_filtering_rules = last_apply_per_account;
4074
4075         if (pre_global_processing || processing_list
4076             || post_global_processing)
4077                 filtering_move_and_copy_msgs(mlist);
4078         for (cur = mlist ; cur != NULL ; cur = cur->next) {
4079                 MsgInfo * msginfo = (MsgInfo *)cur->data;
4080                 procmsg_msginfo_free(msginfo);
4081         }
4082         g_slist_free(mlist);
4083         
4084         statusbar_progress_all(0,0,0);
4085         statusbar_pop_all();
4086
4087         inc_unlock();
4088
4089         folder_item_update_thaw();
4090 }
4091
4092 /*
4093  *  functions for handling FolderItem content changes
4094  */
4095 static gint folder_item_update_freeze_cnt = 0;
4096
4097 static void folder_item_update_with_msg(FolderItem *item, FolderItemUpdateFlags update_flags, MsgInfo *msg)
4098 {
4099         if (folder_item_update_freeze_cnt == 0 /* || (msg != NULL && item->opened) */) {
4100                 FolderItemUpdateData source;
4101         
4102                 source.item = item;
4103                 source.update_flags = update_flags;
4104                 source.msg = msg;
4105                 hooks_invoke(FOLDER_ITEM_UPDATE_HOOKLIST, &source);
4106         } else {
4107                 item->update_flags |= update_flags & ~(F_ITEM_UPDATE_ADDMSG | F_ITEM_UPDATE_REMOVEMSG);
4108         }
4109 }
4110
4111 /**
4112  * Notify the folder system about changes to a folder. If the
4113  * update system is not frozen the FOLDER_ITEM_UPDATE_HOOKLIST will
4114  * be invoked, otherwise the changes will be remebered until
4115  * the folder system is thawed.
4116  *
4117  * \param item The FolderItem that was changed
4118  * \param update_flags Type of changed that was made
4119  */
4120 void folder_item_update(FolderItem *item, FolderItemUpdateFlags update_flags)
4121 {
4122         folder_item_update_with_msg(item, update_flags, NULL);
4123 }
4124
4125 void folder_item_update_recursive(FolderItem *item, FolderItemUpdateFlags update_flags)
4126 {
4127         GNode *node = item->folder->node;       
4128
4129         node = g_node_find(node, G_PRE_ORDER, G_TRAVERSE_ALL, item);
4130         node = node->children;
4131
4132         folder_item_update(item, update_flags);
4133         while (node != NULL) {
4134                 if (node && node->data) {
4135                         FolderItem *next_item = (FolderItem*) node->data;
4136
4137                         folder_item_update(next_item, update_flags);
4138                 }
4139                 node = node->next;
4140         }
4141 }
4142
4143 void folder_item_update_freeze(void)
4144 {
4145         folder_item_update_freeze_cnt++;
4146 }
4147
4148 static void folder_item_update_func(FolderItem *item, gpointer data)
4149 {
4150         FolderItemUpdateData source;
4151     
4152         if (item->update_flags) {
4153                 source.item = item;
4154                 source.update_flags = item->update_flags;
4155                 source.msg = NULL;
4156                 hooks_invoke(FOLDER_ITEM_UPDATE_HOOKLIST, &source);                             
4157                 item->update_flags = 0;
4158         }
4159 }
4160
4161 void folder_item_update_thaw(void)
4162 {
4163         if (folder_item_update_freeze_cnt > 0)
4164                 folder_item_update_freeze_cnt--;
4165         if (folder_item_update_freeze_cnt == 0) {
4166                 /* Update all folders */
4167                 folder_func_to_all_folders(folder_item_update_func, NULL);
4168         }
4169 }
4170
4171 void folder_item_synchronise(FolderItem *item)
4172 {
4173         if (!item)
4174                 return;
4175         if (item->prefs->offlinesync && item->folder->klass->synchronise) {
4176                 statuswindow_print_all(_("Synchronising %s for offline use...\n"), item->path ? item->path : "(null)");
4177                 item->folder->klass->synchronise(item, 
4178                         item->prefs->offlinesync_days);
4179                 if (item->prefs->offlinesync_days > 0 &&
4180                     item->prefs->remove_old_bodies)
4181                         folder_item_clean_local_files(item, item->prefs->offlinesync_days);
4182                 statuswindow_pop_all();
4183         }
4184 }
4185
4186 static void folder_item_synchronise_func(FolderItem *item, gpointer data)
<