5ed9790d58ce2c4d6a12cd17ef077ea3bff48e24
[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_draft(void)
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->draft == NULL)
1479                         continue;
1480                 if (folder->klass->type == F_UNKNOWN)
1481                         continue;
1482
1483                 return folder->draft;
1484         }
1485
1486         return NULL;
1487 }
1488
1489 FolderItem *folder_get_default_queue(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->queue == NULL)
1499                         continue;
1500                 if (folder->klass->type == F_UNKNOWN)
1501                         continue;
1502
1503                 return folder->queue;
1504         }
1505
1506         return NULL;
1507 }
1508
1509 FolderItem *folder_get_default_trash(void)
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->trash == NULL)
1519                         continue;
1520                 if (folder->klass->type == F_UNKNOWN)
1521                         continue;
1522
1523                 return folder->trash;
1524         }
1525
1526         return NULL;
1527 }
1528
1529 #define CREATE_FOLDER_IF_NOT_EXIST(member, dir, type)           \
1530 {                                                               \
1531         if (!folder->member) {                                  \
1532                 item = folder_item_new(folder, dir, dir);       \
1533                 item->stype = type;                             \
1534                 folder_item_append(rootitem, item);             \
1535                 folder->member = item;                          \
1536         }                                                       \
1537 }
1538
1539 void folder_set_missing_folders(void)
1540 {
1541         Folder *folder;
1542         FolderItem *rootitem;
1543         FolderItem *item;
1544         GList *list;
1545
1546         for (list = folder_list; list != NULL; list = list->next) {
1547                 folder = list->data;
1548                 if (FOLDER_TYPE(folder) != F_MH) continue;
1549                 rootitem = FOLDER_ITEM(folder->node->data);
1550                 g_return_if_fail(rootitem != NULL);
1551
1552                 if (folder->inbox && folder->outbox && folder->draft &&
1553                     folder->queue && folder->trash)
1554                         continue;
1555
1556                 if (folder->klass->create_tree(folder) < 0) {
1557                         g_warning("%s: can't create the folder tree.\n",
1558                                   LOCAL_FOLDER(folder)->rootpath);
1559                         continue;
1560                 }
1561
1562                 CREATE_FOLDER_IF_NOT_EXIST(inbox,  INBOX_DIR,  F_INBOX);
1563                 CREATE_FOLDER_IF_NOT_EXIST(outbox, OUTBOX_DIR, F_OUTBOX);
1564                 CREATE_FOLDER_IF_NOT_EXIST(draft,  DRAFT_DIR,  F_DRAFT);
1565                 CREATE_FOLDER_IF_NOT_EXIST(queue,  QUEUE_DIR,  F_QUEUE);
1566                 CREATE_FOLDER_IF_NOT_EXIST(trash,  TRASH_DIR,  F_TRASH);
1567         }
1568 }
1569
1570 static gboolean folder_unref_account_func(GNode *node, gpointer data)
1571 {
1572         FolderItem *item = node->data;
1573         PrefsAccount *account = data;
1574
1575         if (item->account == account)
1576                 item->account = NULL;
1577
1578         return FALSE;
1579 }
1580
1581 void folder_unref_account_all(PrefsAccount *account)
1582 {
1583         Folder *folder;
1584         GList *list;
1585
1586         if (!account) return;
1587
1588         for (list = folder_list; list != NULL; list = list->next) {
1589                 folder = list->data;
1590                 if (folder->account == account)
1591                         folder->account = NULL;
1592                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1593                                 folder_unref_account_func, account);
1594         }
1595 }
1596
1597 #undef CREATE_FOLDER_IF_NOT_EXIST
1598
1599 gchar *folder_item_get_path(FolderItem *item)
1600 {
1601         Folder *folder;
1602
1603         g_return_val_if_fail(item != NULL, NULL);
1604         folder = item->folder;
1605         g_return_val_if_fail(folder != NULL, NULL);
1606
1607         return folder->klass->item_get_path(folder, item);
1608 }
1609
1610 void folder_item_set_default_flags(FolderItem *dest, MsgFlags *flags)
1611 {
1612         if (!(folder_has_parent_of_type(dest, F_OUTBOX) ||
1613               folder_has_parent_of_type(dest, F_QUEUE)  ||
1614               folder_has_parent_of_type(dest, F_DRAFT) ||
1615               folder_has_parent_of_type(dest, F_TRASH))) {
1616                 flags->perm_flags = MSG_NEW|MSG_UNREAD;
1617         } else {
1618                 flags->perm_flags = 0;
1619         }
1620         if (FOLDER_TYPE(dest->folder) == F_MH) {
1621                 if (folder_has_parent_of_type(dest, F_QUEUE)) {
1622                         MSG_SET_TMP_FLAGS(*flags, MSG_QUEUED);
1623                 } else if (folder_has_parent_of_type(dest, F_DRAFT)) {
1624                         MSG_SET_TMP_FLAGS(*flags, MSG_DRAFT);
1625                 }
1626         }
1627 }
1628
1629 static gint folder_sort_cache_list_by_msgnum(gconstpointer a, gconstpointer b)
1630 {
1631         MsgInfo *msginfo_a = (MsgInfo *) a;
1632         MsgInfo *msginfo_b = (MsgInfo *) b;
1633
1634         return (msginfo_a->msgnum - msginfo_b->msgnum);
1635 }
1636
1637 static gint folder_sort_folder_list(gconstpointer a, gconstpointer b)
1638 {
1639         guint gint_a = GPOINTER_TO_INT(a);
1640         guint gint_b = GPOINTER_TO_INT(b);
1641         
1642         return (gint_a - gint_b);
1643 }
1644
1645 void folder_item_process_open (FolderItem *item,
1646                                  void (*before_proc_func)(gpointer data),
1647                                  void (*after_proc_func)(gpointer data),
1648                                  gpointer data)
1649 {
1650         gchar *buf;
1651         if (item == NULL)
1652                 return;
1653         if((item->folder->klass->scan_required != NULL) &&
1654            (item->folder->klass->scan_required(item->folder, item))) {
1655                 folder_item_scan_full(item, TRUE);
1656         } else {
1657                 folder_item_syncronize_flags(item);
1658         }
1659         
1660         /* Processing */
1661         buf = g_strdup_printf(_("Processing (%s)...\n"), 
1662                               item->path ? item->path : item->name);
1663         g_free(buf);
1664
1665         if (before_proc_func)
1666                 before_proc_func(data);
1667
1668         folder_item_apply_processing(item);
1669
1670         if (after_proc_func)
1671                 after_proc_func(data);
1672
1673         item->processing_pending = FALSE;
1674         return; 
1675 }
1676
1677 gint folder_item_open(FolderItem *item)
1678 {
1679         START_TIMING(""); 
1680         if (item->no_select)
1681                 return -1;
1682
1683         if (item->scanning) {
1684                 debug_print("%s is scanning... \n", item->path ? item->path : item->name);
1685                 return -2;
1686         }
1687
1688         item->processing_pending = TRUE;
1689         folder_item_process_open (item, NULL, NULL, NULL);
1690         
1691         item->opened = TRUE;
1692         END_TIMING();
1693         return 0;
1694 }
1695
1696 gint folder_item_close(FolderItem *item)
1697 {
1698         GSList *mlist, *cur;
1699         Folder *folder;
1700         
1701         g_return_val_if_fail(item != NULL, -1);
1702
1703         if (item->no_select)
1704                 return -1;
1705
1706         if (item->new_msgs) {
1707                 folder_item_update_freeze();
1708                 mlist = folder_item_get_msg_list(item);
1709                 for (cur = mlist ; cur != NULL ; cur = cur->next) {
1710                         MsgInfo * msginfo;
1711
1712                         msginfo = (MsgInfo *) cur->data;
1713                         if (MSG_IS_NEW(msginfo->flags))
1714                                 procmsg_msginfo_unset_flags(msginfo, MSG_NEW, 0);
1715                         procmsg_msginfo_free(msginfo);
1716                 }
1717                 g_slist_free(mlist);
1718                 folder_item_update_thaw();
1719         }               
1720
1721         folder_item_write_cache(item);
1722         
1723         folder_item_update(item, F_ITEM_UPDATE_MSGCNT);
1724
1725         item->opened = FALSE;
1726         folder = item->folder;
1727
1728         if (folder->klass->close == NULL)
1729                 return 0;
1730
1731         return folder->klass->close(folder, item);
1732 }
1733
1734 static MsgInfoList *get_msginfos(FolderItem *item, MsgNumberList *numlist)
1735 {
1736         MsgInfoList *msglist = NULL;
1737         Folder *folder = item->folder;
1738         if (item->no_select)
1739                 return NULL;
1740         
1741         if (folder->klass->get_msginfos != NULL)
1742                 msglist = folder->klass->get_msginfos(folder, item, numlist);
1743         else {
1744                 MsgNumberList *elem;
1745
1746                 for (elem = numlist; elem != NULL; elem = g_slist_next(elem)) {
1747                         MsgInfo *msginfo;
1748                         guint num;
1749
1750                         num = GPOINTER_TO_INT(elem->data);
1751                         msginfo = folder->klass->get_msginfo(folder, item, num);
1752                         if (msginfo != NULL)
1753                                 msglist = g_slist_prepend(msglist, msginfo);
1754                 }               
1755         }
1756
1757         return msglist;
1758 }
1759
1760 static MsgInfo *get_msginfo(FolderItem *item, guint num)
1761 {
1762         MsgNumberList numlist;
1763         MsgInfoList *msglist;
1764         MsgInfo *msginfo = NULL;
1765
1766         numlist.data = GINT_TO_POINTER(num);
1767         numlist.next = NULL;
1768         msglist = get_msginfos(item, &numlist);
1769         if (msglist != NULL)
1770                 msginfo = procmsg_msginfo_new_ref(msglist->data);
1771         procmsg_msg_list_free(msglist);
1772
1773         return msginfo;
1774 }
1775
1776 static gint syncronize_flags(FolderItem *item, MsgInfoList *msglist)
1777 {
1778         GRelation *relation;
1779         gint ret = 0;
1780         GSList *cur;
1781
1782         if(msglist == NULL)
1783                 return 0;
1784         if(item->folder->klass->get_flags == NULL)
1785                 return 0;
1786         if (item->no_select)
1787                 return 0;
1788
1789         relation = g_relation_new(2);
1790         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
1791         folder_item_set_batch(item, TRUE);
1792         if ((ret = item->folder->klass->get_flags(
1793             item->folder, item, msglist, relation)) == 0) {
1794                 GTuples *tuples;
1795                 MsgInfo *msginfo;
1796                 MsgPermFlags permflags = 0;
1797                 gboolean skip;
1798
1799                 folder_item_update_freeze();
1800                 for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1801                         msginfo = (MsgInfo *) cur->data;
1802                 
1803                         tuples = g_relation_select(relation, msginfo, 0);
1804                         skip = tuples->len < 1;
1805                         if (!skip)
1806                                 permflags = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
1807                         g_tuples_destroy(tuples);
1808                         if (skip)
1809                                 continue;
1810                         
1811                         if (msginfo->flags.perm_flags != permflags) {
1812                                 procmsg_msginfo_change_flags(msginfo,
1813                                         permflags & ~msginfo->flags.perm_flags, 0,
1814                                         ~permflags & msginfo->flags.perm_flags, 0);
1815                         }
1816                 }
1817                 folder_item_update_thaw();
1818         }
1819         folder_item_set_batch(item, FALSE);
1820         g_relation_destroy(relation);   
1821
1822         return ret;
1823 }
1824
1825 gint folder_item_scan_full(FolderItem *item, gboolean filtering)
1826 {
1827         Folder *folder;
1828         GSList *folder_list = NULL, *cache_list = NULL;
1829         GSList *folder_list_cur, *cache_list_cur, *new_list = NULL;
1830         GSList *exists_list = NULL, *elem;
1831         GSList *newmsg_list = NULL;
1832         guint newcnt = 0, unreadcnt = 0, totalcnt = 0;
1833         guint markedcnt = 0, unreadmarkedcnt = 0;
1834         guint cache_max_num, folder_max_num, cache_cur_num, folder_cur_num;
1835         gboolean update_flags = 0, old_uids_valid = FALSE;
1836         GHashTable *subject_table = NULL;
1837         
1838         g_return_val_if_fail(item != NULL, -1);
1839         if (item->path == NULL) return -1;
1840
1841         folder = item->folder;
1842
1843         g_return_val_if_fail(folder != NULL, -1);
1844         g_return_val_if_fail(folder->klass->get_num_list != NULL, -1);
1845
1846         item->scanning = TRUE;
1847
1848         debug_print("Scanning folder %s for cache changes.\n", item->path ? item->path : "(null)");
1849         
1850         /* Get list of messages for folder and cache */
1851         if (folder->klass->get_num_list(item->folder, item, &folder_list, &old_uids_valid) < 0) {
1852                 debug_print("Error fetching list of message numbers\n");
1853                 item->scanning = FALSE;
1854                 return(-1);
1855         }
1856
1857         if(prefs_common.thread_by_subject) {
1858                 subject_table = g_hash_table_new(g_str_hash, g_str_equal);
1859         }
1860         
1861         if (old_uids_valid) {
1862                 if (!item->cache)
1863                         folder_item_read_cache(item);
1864                 cache_list = msgcache_get_msg_list(item->cache);
1865         } else {
1866                 if (item->cache)
1867                         msgcache_destroy(item->cache);
1868                 item->cache = msgcache_new();
1869                 cache_list = NULL;
1870         }
1871
1872         /* Sort both lists */
1873         cache_list = g_slist_sort(cache_list, folder_sort_cache_list_by_msgnum);
1874         folder_list = g_slist_sort(folder_list, folder_sort_folder_list);
1875
1876         cache_list_cur = cache_list;
1877         folder_list_cur = folder_list;
1878
1879         if (cache_list_cur != NULL) {
1880                 GSList *cache_list_last;
1881         
1882                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
1883                 cache_list_last = g_slist_last(cache_list);
1884                 cache_max_num = ((MsgInfo *)cache_list_last->data)->msgnum;
1885         } else {
1886                 cache_cur_num = G_MAXINT;
1887                 cache_max_num = 0;
1888         }
1889
1890         if (folder_list_cur != NULL) {
1891                 GSList *folder_list_last;
1892         
1893                 folder_cur_num = GPOINTER_TO_INT(folder_list_cur->data);
1894                 folder_list_last = g_slist_last(folder_list);
1895                 folder_max_num = GPOINTER_TO_INT(folder_list_last->data);
1896         } else {
1897                 folder_cur_num = G_MAXINT;
1898                 folder_max_num = 0;
1899         }
1900
1901         while ((cache_cur_num != G_MAXINT) || (folder_cur_num != G_MAXINT)) {
1902                 /*
1903                  *  Message only exists in the folder
1904                  *  Remember message for fetching
1905                  */
1906                 if (folder_cur_num < cache_cur_num) {
1907                         gboolean add = FALSE;
1908
1909                         switch(FOLDER_TYPE(folder)) {
1910                                 case F_NEWS:
1911                                         if (folder_cur_num < cache_max_num)
1912                                                 break;
1913                                         
1914                                         if (folder->account->max_articles == 0) {
1915                                                 add = TRUE;
1916                                         }
1917
1918                                         if (folder_max_num <= folder->account->max_articles) {
1919                                                 add = TRUE;
1920                                         } else if (folder_cur_num > (folder_max_num - folder->account->max_articles)) {
1921                                                 add = TRUE;
1922                                         }
1923                                         break;
1924                                 default:
1925                                         add = TRUE;
1926                                         break;
1927                         }
1928                         
1929                         if (add) {
1930                                 new_list = g_slist_prepend(new_list, GINT_TO_POINTER(folder_cur_num));
1931                                 debug_print("Remembered message %d for fetching\n", folder_cur_num);
1932                         }
1933
1934                         /* Move to next folder number */
1935                         folder_list_cur = folder_list_cur->next;
1936
1937                         if (folder_list_cur != NULL)
1938                                 folder_cur_num = GPOINTER_TO_INT(folder_list_cur->data);
1939                         else
1940                                 folder_cur_num = G_MAXINT;
1941
1942                         continue;
1943                 }
1944
1945                 /*
1946                  *  Message only exists in the cache
1947                  *  Remove the message from the cache
1948                  */
1949                 if (cache_cur_num < folder_cur_num) {
1950                         msgcache_remove_msg(item->cache, cache_cur_num);
1951                         debug_print("Removed message %d from cache.\n", cache_cur_num);
1952
1953                         /* Move to next cache number */
1954                         cache_list_cur = cache_list_cur->next;
1955
1956                         if (cache_list_cur != NULL)
1957                                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
1958                         else
1959                                 cache_cur_num = G_MAXINT;
1960
1961                         update_flags |= F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT;
1962
1963                         continue;
1964                 }
1965
1966                 /*
1967                  *  Message number exists in folder and cache!
1968                  *  Check if the message has been modified
1969                  */
1970                 if (cache_cur_num == folder_cur_num) {
1971                         MsgInfo *msginfo;
1972
1973                         msginfo = msgcache_get_msg(item->cache, folder_cur_num);
1974                         if (folder->klass->is_msg_changed && folder->klass->is_msg_changed(folder, item, msginfo)) {
1975                                 msgcache_remove_msg(item->cache, msginfo->msgnum);
1976                                 new_list = g_slist_prepend(new_list, GINT_TO_POINTER(msginfo->msgnum));
1977                                 procmsg_msginfo_free(msginfo);
1978
1979                                 debug_print("Remembering message %d to update...\n", folder_cur_num);
1980                         } else {
1981                                 exists_list = g_slist_prepend(exists_list, msginfo);
1982
1983                                 if(prefs_common.thread_by_subject &&
1984                                         MSG_IS_IGNORE_THREAD(msginfo->flags) &&
1985                                         !subject_table_lookup(subject_table, msginfo->subject)) {
1986                                         subject_table_insert(subject_table, msginfo->subject, msginfo);
1987                                 }
1988                         }
1989                         
1990                         /* Move to next folder and cache number */
1991                         cache_list_cur = cache_list_cur->next;
1992                         folder_list_cur = folder_list_cur->next;
1993
1994                         if (cache_list_cur != NULL)
1995                                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
1996                         else
1997                                 cache_cur_num = G_MAXINT;
1998
1999                         if (folder_list_cur != NULL)
2000                                 folder_cur_num = GPOINTER_TO_INT(folder_list_cur->data);
2001                         else
2002                                 folder_cur_num = G_MAXINT;
2003
2004                         continue;
2005                 }
2006         }
2007         
2008         for(cache_list_cur = cache_list; cache_list_cur != NULL; cache_list_cur = g_slist_next(cache_list_cur))
2009                 procmsg_msginfo_free((MsgInfo *) cache_list_cur->data);
2010
2011         g_slist_free(cache_list);
2012         g_slist_free(folder_list);
2013
2014         if (new_list != NULL) {
2015                 GSList *tmp_list = NULL;
2016                 newmsg_list = get_msginfos(item, new_list);
2017                 g_slist_free(new_list);
2018                 tmp_list = g_slist_concat(g_slist_copy(exists_list), g_slist_copy(newmsg_list));
2019                 syncronize_flags(item, tmp_list);
2020                 g_slist_free(tmp_list);
2021         } else {
2022                 syncronize_flags(item, exists_list);
2023         }
2024
2025         folder_item_update_freeze();
2026         if (newmsg_list != NULL) {
2027                 GSList *elem, *to_filter = NULL;
2028                 gboolean do_filter = (filtering == TRUE) &&
2029                                         (item->stype == F_INBOX) &&
2030                                         (item->folder->account != NULL) && 
2031                                         (item->folder->account->filter_on_recv);
2032                 
2033                 for (elem = newmsg_list; elem != NULL; elem = g_slist_next(elem)) {
2034                         MsgInfo *msginfo = (MsgInfo *) elem->data;
2035
2036                         msgcache_add_msg(item->cache, msginfo);
2037                         if (!do_filter) {
2038                                 exists_list = g_slist_prepend(exists_list, msginfo);
2039
2040                                 if(prefs_common.thread_by_subject &&
2041                                         MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2042                                         !subject_table_lookup(subject_table, msginfo->subject)) {
2043                                         subject_table_insert(subject_table, msginfo->subject, msginfo);
2044                                 }                       
2045                         }
2046                 }
2047
2048                 if (do_filter) {
2049                         GSList *unfiltered;
2050                         procmsg_msglist_filter(newmsg_list, item->folder->account, 
2051                                         &to_filter, &unfiltered, 
2052                                         TRUE);
2053                         
2054                         filtering_move_and_copy_msgs(newmsg_list);
2055                         if (to_filter != NULL) {
2056                                 for (elem = to_filter; elem; elem = g_slist_next(elem)) {
2057                                         MsgInfo *msginfo = (MsgInfo *)elem->data;
2058                                         procmsg_msginfo_free(msginfo);
2059                                 }
2060                                 g_slist_free(to_filter);
2061                         }
2062                         if (unfiltered != NULL) {
2063                                 for (elem = unfiltered; elem; elem = g_slist_next(elem)) {
2064                                         MsgInfo *msginfo = (MsgInfo *)elem->data;
2065                                         exists_list = g_slist_prepend(exists_list, msginfo);
2066
2067                                         if(prefs_common.thread_by_subject &&
2068                                                 MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2069                                                 !subject_table_lookup(subject_table, msginfo->subject)) {
2070                                                 subject_table_insert(subject_table, msginfo->subject, msginfo);
2071                                         }
2072                                 }
2073                                 g_slist_free(unfiltered);
2074                         }
2075                         if (prefs_common.real_time_sync)
2076                                 folder_item_synchronise(item);
2077                 } else {
2078                         if (prefs_common.real_time_sync)
2079                                 folder_item_synchronise(item);
2080                 }
2081
2082                 g_slist_free(newmsg_list);
2083
2084                 update_flags |= F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT;
2085         }
2086
2087         folder_item_set_batch(item, TRUE);
2088         for (elem = exists_list; elem != NULL; elem = g_slist_next(elem)) {
2089                 MsgInfo *msginfo, *parent_msginfo;
2090
2091                 msginfo = elem->data;
2092                 if (MSG_IS_IGNORE_THREAD(msginfo->flags) && (MSG_IS_NEW(msginfo->flags) || MSG_IS_UNREAD(msginfo->flags)))
2093                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
2094                 if (!MSG_IS_IGNORE_THREAD(msginfo->flags) && procmsg_msg_has_flagged_parent(msginfo, MSG_IGNORE_THREAD)) {
2095                         procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0, MSG_NEW | MSG_UNREAD, 0);
2096                 }
2097                 if(prefs_common.thread_by_subject && !msginfo->inreplyto &&
2098                         !msginfo->references && !MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2099                         (parent_msginfo = subject_table_lookup(subject_table, msginfo->subject)))
2100                 {
2101                         if(MSG_IS_IGNORE_THREAD(parent_msginfo->flags)) {
2102                                 procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0,
2103                                                 MSG_NEW | MSG_UNREAD, 0);
2104                         }
2105                 }
2106                 if ((folder_has_parent_of_type(item, F_OUTBOX) ||
2107                      folder_has_parent_of_type(item, F_QUEUE)  ||
2108                      folder_has_parent_of_type(item, F_DRAFT)  ||
2109                      folder_has_parent_of_type(item, F_TRASH)) &&
2110                     (MSG_IS_NEW(msginfo->flags) || MSG_IS_UNREAD(msginfo->flags)))
2111                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
2112                 if (MSG_IS_NEW(msginfo->flags))
2113                         newcnt++;
2114                 if (MSG_IS_UNREAD(msginfo->flags))
2115                         unreadcnt++;
2116                 if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2117                         unreadmarkedcnt++;
2118                 if (MSG_IS_MARKED(msginfo->flags))
2119                         markedcnt++;
2120
2121                 totalcnt++;
2122
2123                 procmsg_msginfo_free(msginfo);
2124         }
2125         folder_item_set_batch(item, FALSE);
2126         g_slist_free(exists_list);
2127         
2128         if(prefs_common.thread_by_subject) {
2129                 g_hash_table_destroy(subject_table);
2130         }
2131         
2132         if (item->new_msgs != newcnt || item->unread_msgs != unreadcnt
2133         ||  item->total_msgs != totalcnt || item->marked_msgs != markedcnt
2134         ||  item->unreadmarked_msgs != unreadmarkedcnt) {
2135                 update_flags |= F_ITEM_UPDATE_CONTENT;
2136         }
2137
2138         item->new_msgs = newcnt;
2139         item->unread_msgs = unreadcnt;
2140         item->total_msgs = totalcnt;
2141         item->unreadmarked_msgs = unreadmarkedcnt;
2142         item->marked_msgs = markedcnt;
2143
2144         update_flags |= F_ITEM_UPDATE_MSGCNT;
2145
2146         folder_item_update(item, update_flags);
2147         folder_item_update_thaw();
2148         
2149         item->scanning = FALSE;
2150
2151         return 0;
2152 }
2153
2154 gint folder_item_scan(FolderItem *item)
2155 {
2156         return folder_item_scan_full(item, TRUE);
2157 }
2158
2159 static void folder_item_scan_foreach_func(gpointer key, gpointer val,
2160                                           gpointer data)
2161 {
2162         folder_item_scan(FOLDER_ITEM(key));
2163 }
2164
2165 void folder_item_scan_foreach(GHashTable *table)
2166 {
2167         g_hash_table_foreach(table, folder_item_scan_foreach_func, NULL);
2168 }
2169
2170 static void folder_count_total_cache_memusage(FolderItem *item, gpointer data)
2171 {
2172         gint *memusage = (gint *)data;
2173
2174         if (item->cache == NULL)
2175                 return;
2176         
2177         *memusage += msgcache_get_memory_usage(item->cache);
2178 }
2179
2180 gint folder_item_syncronize_flags(FolderItem *item)
2181 {
2182         MsgInfoList *msglist = NULL;
2183         GSList *cur;
2184         gint ret = 0;
2185         
2186         g_return_val_if_fail(item != NULL, -1);
2187         g_return_val_if_fail(item->folder != NULL, -1);
2188         g_return_val_if_fail(item->folder->klass != NULL, -1);
2189         if (item->no_select)
2190                 return -1;
2191
2192         item->scanning = TRUE;
2193
2194         if (item->cache == NULL)
2195                 folder_item_read_cache(item);
2196         
2197         msglist = msgcache_get_msg_list(item->cache);
2198         
2199         ret = syncronize_flags(item, msglist);
2200
2201         for (cur = msglist; cur != NULL; cur = g_slist_next(cur))
2202                 procmsg_msginfo_free((MsgInfo *) cur->data);
2203         
2204         g_slist_free(msglist);
2205
2206         item->scanning = FALSE;
2207
2208         return ret;
2209 }
2210
2211 static gint folder_cache_time_compare_func(gconstpointer a, gconstpointer b)
2212 {
2213         FolderItem *fa = (FolderItem *)a;
2214         FolderItem *fb = (FolderItem *)b;
2215         
2216         return (gint) (msgcache_get_last_access_time(fa->cache) - msgcache_get_last_access_time(fb->cache));
2217 }
2218
2219 static void folder_find_expired_caches(FolderItem *item, gpointer data)
2220 {
2221         GSList **folder_item_list = (GSList **)data;
2222         gint difftime, expiretime;
2223         
2224         if (item->cache == NULL)
2225                 return;
2226
2227         if (item->opened > 0)
2228                 return;
2229
2230         difftime = (gint) (time(NULL) - msgcache_get_last_access_time(item->cache));
2231         expiretime = prefs_common.cache_min_keep_time * 60;
2232         debug_print("Cache unused time: %d (Expire time: %d)\n", difftime, expiretime);
2233
2234         if (difftime > expiretime && !item->opened && !item->processing_pending) {
2235                 *folder_item_list = g_slist_insert_sorted(*folder_item_list, item, folder_cache_time_compare_func);
2236         }
2237 }
2238
2239 gboolean folder_item_free_cache(FolderItem *item, gboolean force)
2240 {
2241         g_return_val_if_fail(item != NULL, TRUE);
2242         
2243         if (item->cache == NULL)
2244                 return TRUE;
2245         
2246         if (item->opened > 0 && !force)
2247                 return FALSE;
2248
2249         folder_item_write_cache(item);
2250         msgcache_destroy(item->cache);
2251         item->cache = NULL;
2252         return TRUE;
2253 }
2254
2255 void folder_clean_cache_memory_force(void)
2256 {
2257         int old_cache_max_mem_usage = prefs_common.cache_max_mem_usage;
2258         int old_cache_min_keep_time = prefs_common.cache_min_keep_time;
2259
2260         prefs_common.cache_max_mem_usage = 0;
2261         prefs_common.cache_min_keep_time = 0;
2262
2263         folder_clean_cache_memory(NULL);
2264
2265         prefs_common.cache_max_mem_usage = old_cache_max_mem_usage;
2266         prefs_common.cache_min_keep_time = old_cache_min_keep_time;
2267 }
2268
2269 void folder_clean_cache_memory(FolderItem *protected_item)
2270 {
2271         gint memusage = 0;
2272
2273         folder_func_to_all_folders(folder_count_total_cache_memusage, &memusage);       
2274         debug_print("Total cache memory usage: %d\n", memusage);
2275         
2276         if (memusage > (prefs_common.cache_max_mem_usage * 1024)) {
2277                 GSList *folder_item_list = NULL, *listitem;
2278                 
2279                 debug_print("Trying to free cache memory\n");
2280
2281                 folder_func_to_all_folders(folder_find_expired_caches, &folder_item_list);      
2282                 listitem = folder_item_list;
2283                 while((listitem != NULL) && (memusage > (prefs_common.cache_max_mem_usage * 1024))) {
2284                         FolderItem *item = (FolderItem *)(listitem->data);
2285                         gint cache_size = 0;
2286                         if (item == protected_item) {
2287                                 listitem = listitem->next;
2288                                 continue;
2289                         }
2290                         debug_print("Freeing cache memory for %s\n", item->path ? item->path : item->name);
2291                         cache_size = msgcache_get_memory_usage(item->cache);
2292                         if (folder_item_free_cache(item, FALSE))
2293                                 memusage -= cache_size;
2294
2295                         listitem = listitem->next;
2296                 }
2297                 g_slist_free(folder_item_list);
2298         }
2299 }
2300
2301 static void folder_item_remove_cached_msg(FolderItem *item, MsgInfo *msginfo)
2302 {
2303         Folder *folder = item->folder;
2304
2305         g_return_if_fail(folder != NULL);
2306
2307         if (folder->klass->remove_cached_msg == NULL)
2308                 return;
2309         
2310         folder->klass->remove_cached_msg(folder, item, msginfo);
2311 }
2312
2313 static void folder_item_clean_local_files(FolderItem *item, gint days)
2314 {
2315         g_return_if_fail(item != NULL);
2316         g_return_if_fail(item->folder != NULL);
2317
2318         if (FOLDER_TYPE(item->folder) == F_IMAP ||
2319             FOLDER_TYPE(item->folder) == F_NEWS) {
2320                 GSList *msglist = folder_item_get_msg_list(item);
2321                 GSList *cur;
2322                 time_t t = time(NULL);
2323                 for (cur = msglist; cur; cur = cur->next) {
2324                         MsgInfo *msginfo = (MsgInfo *)cur->data;
2325                         gint age = (t - msginfo->date_t) / (60*60*24);
2326                         if (age > days)
2327                                 folder_item_remove_cached_msg(item, msginfo);
2328                 }
2329                 procmsg_msg_list_free(msglist);
2330         }
2331 }
2332
2333 static void folder_item_read_cache(FolderItem *item)
2334 {
2335         gchar *cache_file, *mark_file, *tags_file;
2336         START_TIMING("");
2337         g_return_if_fail(item != NULL);
2338
2339         if (item->path != NULL) {
2340                 cache_file = folder_item_get_cache_file(item);
2341                 mark_file = folder_item_get_mark_file(item);
2342                 tags_file = folder_item_get_tags_file(item);
2343                 item->cache = msgcache_read_cache(item, cache_file);
2344                 if (!item->cache) {
2345                         MsgInfoList *list, *cur;
2346                         guint newcnt = 0, unreadcnt = 0;
2347                         guint markedcnt = 0, unreadmarkedcnt = 0;
2348                         MsgInfo *msginfo;
2349
2350                         item->cache = msgcache_new();
2351                         folder_item_scan_full(item, TRUE);
2352
2353                         msgcache_read_mark(item->cache, mark_file);
2354
2355                         list = msgcache_get_msg_list(item->cache);
2356                         for (cur = list; cur != NULL; cur = g_slist_next(cur)) {
2357                                 msginfo = cur->data;
2358
2359                                 if (MSG_IS_NEW(msginfo->flags))
2360                                         newcnt++;
2361                                 if (MSG_IS_UNREAD(msginfo->flags))
2362                                         unreadcnt++;
2363                                 if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2364                                         unreadmarkedcnt++;
2365                                 if (MSG_IS_MARKED(msginfo->flags))
2366                                         markedcnt++;
2367                         }
2368                         item->new_msgs = newcnt;
2369                         item->unread_msgs = unreadcnt;
2370                         item->unreadmarked_msgs = unreadmarkedcnt;
2371                         item->marked_msgs = markedcnt;
2372                         procmsg_msg_list_free(list);
2373                 } else
2374                         msgcache_read_mark(item->cache, mark_file);
2375
2376                 msgcache_read_tags(item->cache, tags_file);
2377
2378                 g_free(cache_file);
2379                 g_free(mark_file);
2380                 g_free(tags_file);
2381         } else {
2382                 item->cache = msgcache_new();
2383         }
2384         END_TIMING();
2385         folder_clean_cache_memory(item);
2386 }
2387
2388 void folder_item_write_cache(FolderItem *item)
2389 {
2390         gchar *cache_file, *mark_file, *tags_file;
2391         FolderItemPrefs *prefs;
2392         gint filemode = 0;
2393         gchar *id;
2394         time_t last_mtime = (time_t)0;
2395         gboolean need_scan = FALSE;
2396         
2397         if (!item || !item->path || !item->cache)
2398                 return;
2399
2400         if (FOLDER_TYPE(item->folder) == F_MH) {
2401                 last_mtime = item->mtime;
2402                 need_scan = item->folder->klass->scan_required(item->folder, item);
2403         }
2404
2405         id = folder_item_get_identifier(item);
2406         debug_print("Save cache for folder %s\n", id);
2407         g_free(id);
2408
2409         cache_file = folder_item_get_cache_file(item);
2410         mark_file = folder_item_get_mark_file(item);
2411         tags_file = folder_item_get_tags_file(item);
2412         if (msgcache_write(cache_file, mark_file, tags_file, item->cache) < 0) {
2413                 prefs = item->prefs;
2414                 if (prefs && prefs->enable_folder_chmod && prefs->folder_chmod) {
2415                         /* for cache file */
2416                         filemode = prefs->folder_chmod;
2417                         if (filemode & S_IRGRP) filemode |= S_IWGRP;
2418                         if (filemode & S_IROTH) filemode |= S_IWOTH;
2419                         chmod(cache_file, filemode);
2420                 }
2421         }
2422
2423         if (!need_scan && FOLDER_TYPE(item->folder) == F_MH) {
2424                 if (item->mtime == last_mtime) {
2425                         mh_set_mtime(item);
2426                 }
2427         }
2428
2429         g_free(cache_file);
2430         g_free(mark_file);
2431         g_free(tags_file);
2432 }
2433
2434 MsgInfo *folder_item_get_msginfo(FolderItem *item, gint num)
2435 {
2436         Folder *folder;
2437         MsgInfo *msginfo = NULL;
2438         
2439         g_return_val_if_fail(item != NULL, NULL);
2440         if (item->no_select)
2441                 return NULL;
2442         folder = item->folder;
2443         if (!item->cache)
2444                 folder_item_read_cache(item);
2445         
2446         if ((msginfo = msgcache_get_msg(item->cache, num)) != NULL)
2447                 return msginfo;
2448         
2449         msginfo = get_msginfo(item, num);
2450         if (msginfo != NULL) {
2451                 msgcache_add_msg(item->cache, msginfo);
2452                 return msginfo;
2453         }
2454         
2455         return NULL;
2456 }
2457
2458 MsgInfo *folder_item_get_msginfo_by_msgid(FolderItem *item, const gchar *msgid)
2459 {
2460         Folder *folder;
2461         MsgInfo *msginfo;
2462         
2463         g_return_val_if_fail(item != NULL, NULL);
2464         g_return_val_if_fail(msgid != NULL, NULL);
2465         if (item->no_select)
2466                 return FALSE;
2467         
2468         folder = item->folder;
2469         if (!item->cache)
2470                 folder_item_read_cache(item);
2471         
2472         if ((msginfo = msgcache_get_msg_by_id(item->cache, msgid)) != NULL)
2473                 return msginfo;
2474
2475         return NULL;
2476 }
2477
2478 GSList *folder_item_get_msg_list(FolderItem *item)
2479 {
2480         g_return_val_if_fail(item != NULL, NULL);
2481         if (item->no_select)
2482                 return FALSE;
2483         
2484         if (item->cache == 0)
2485                 folder_item_read_cache(item);
2486
2487         g_return_val_if_fail(item->cache != NULL, NULL);
2488         
2489         return msgcache_get_msg_list(item->cache);
2490 }
2491
2492 static void msginfo_set_mime_flags(GNode *node, gpointer data)
2493 {
2494         MsgInfo *msginfo = data;
2495         MimeInfo *mimeinfo = node->data;
2496         
2497         if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT
2498          && (!mimeinfo->subtype ||  strcmp(mimeinfo->subtype, "pgp-signature"))) {
2499                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2500         } else if (mimeinfo->disposition == DISPOSITIONTYPE_UNKNOWN && 
2501                  mimeinfo->type != MIMETYPE_TEXT &&
2502                  mimeinfo->type != MIMETYPE_MULTIPART) {
2503                 if (!mimeinfo->subtype 
2504                 ||  strcmp(mimeinfo->subtype, "pgp-signature"))
2505                         procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2506         } else if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE &&
2507                 strcmp(mimeinfo->subtype, "pgp-signature") && 
2508                 (procmime_mimeinfo_get_parameter(mimeinfo, "name") != NULL ||
2509                  procmime_mimeinfo_get_parameter(mimeinfo, "filename") != NULL)) {
2510                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2511         } 
2512
2513         /* don't descend below top level message for signed and encrypted info */
2514         if (mimeinfo->type == MIMETYPE_MESSAGE)
2515                 return;
2516
2517         if (privacy_mimeinfo_is_signed(mimeinfo)) {
2518                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
2519         }
2520
2521         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
2522                 procmsg_msginfo_set_flags(msginfo, 0, MSG_ENCRYPTED);
2523         } else {
2524                 /* searching inside encrypted parts doesn't really make sense */
2525                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2526         }
2527 }
2528
2529 gchar *folder_item_fetch_msg(FolderItem *item, gint num)
2530 {
2531         Folder *folder;
2532         gchar *msgfile;
2533         MsgInfo *msginfo;
2534
2535         g_return_val_if_fail(item != NULL, NULL);
2536
2537         folder = item->folder;
2538
2539         g_return_val_if_fail(folder->klass->fetch_msg != NULL, NULL);
2540         if (item->no_select)
2541                 return NULL;
2542
2543         msgfile = folder->klass->fetch_msg(folder, item, num);
2544
2545         if (msgfile != NULL) {
2546                 msginfo = folder_item_get_msginfo(item, num);
2547                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2548                         MimeInfo *mimeinfo;
2549
2550                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) && 
2551                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2552                                 mimeinfo = procmime_scan_file(msgfile);
2553                         else
2554                                 mimeinfo = procmime_scan_queue_file(msgfile);
2555                         /* check for attachments */
2556                         if (mimeinfo != NULL) { 
2557                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2558                                 procmime_mimeinfo_free_all(mimeinfo);
2559
2560                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2561                         }
2562                 }
2563                 procmsg_msginfo_free(msginfo);
2564         }
2565
2566         return msgfile;
2567 }
2568
2569 gchar *folder_item_fetch_msg_full(FolderItem *item, gint num, gboolean headers,
2570                                   gboolean body)
2571 {
2572         Folder *folder;
2573         gchar *msgfile;
2574         MsgInfo *msginfo;
2575
2576         g_return_val_if_fail(item != NULL, NULL);
2577         if (item->no_select)
2578                 return NULL;
2579         
2580         folder = item->folder;
2581
2582         if (folder->klass->fetch_msg_full == NULL)
2583                 return folder_item_fetch_msg(item, num);
2584
2585         if (item->prefs->offlinesync && prefs_common.real_time_sync)
2586                 msgfile = folder->klass->fetch_msg_full(folder, item, num, 
2587                                                 TRUE, TRUE);
2588         else
2589                 msgfile = folder->klass->fetch_msg_full(folder, item, num, 
2590                                                 headers, body);
2591
2592         if (msgfile != NULL) {
2593                 msginfo = folder_item_get_msginfo(item, num);
2594                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2595                         MimeInfo *mimeinfo;
2596
2597                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
2598                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2599                                 mimeinfo = procmime_scan_file(msgfile);
2600                         else
2601                                 mimeinfo = procmime_scan_queue_file(msgfile);
2602                         /* check for attachments */
2603                         if (mimeinfo != NULL) { 
2604                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2605                                 procmime_mimeinfo_free_all(mimeinfo);
2606
2607                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2608                         }
2609                 }
2610                 procmsg_msginfo_free(msginfo);
2611         }
2612
2613         return msgfile;
2614 }
2615
2616
2617 gint folder_item_fetch_all_msg(FolderItem *item)
2618 {
2619         Folder *folder;
2620         GSList *mlist;
2621         GSList *cur;
2622         gint num = 0;
2623         gint ret = 0;
2624         gint total = 0;
2625
2626         g_return_val_if_fail(item != NULL, -1);
2627         if (item->no_select)
2628                 return -1;
2629
2630         debug_print("fetching all messages in %s ...\n", item->path ? item->path : "(null)");
2631         statusbar_print_all(_("Fetching all messages in %s ...\n"), item->path ? item->path : "(null)");
2632
2633         folder = item->folder;
2634
2635         if (folder->ui_func)
2636                 folder->ui_func(folder, item, folder->ui_func_data ?
2637                                 folder->ui_func_data : GINT_TO_POINTER(num));
2638
2639         mlist = folder_item_get_msg_list(item);
2640
2641         total = g_slist_length(mlist);
2642
2643         for (cur = mlist; cur != NULL; cur = cur->next) {
2644                 MsgInfo *msginfo = (MsgInfo *)cur->data;
2645                 gchar *msg;
2646
2647                 statusbar_progress_all(num++,total, 10);
2648
2649                 if (folder->ui_func)
2650                         folder->ui_func(folder, item,
2651                                         folder->ui_func_data ?
2652                                         folder->ui_func_data :
2653                                         GINT_TO_POINTER(num));
2654                 if (num % 50 == 0)
2655                         GTK_EVENTS_FLUSH();
2656
2657                 msg = folder_item_fetch_msg(item, msginfo->msgnum);
2658                 if (!msg) {
2659                         g_warning("Can't fetch message %d. Aborting.\n",
2660                                   msginfo->msgnum);
2661                         ret = -1;
2662                         break;
2663                 }
2664                 g_free(msg);
2665         }
2666         
2667         statusbar_progress_all(0,0,0);
2668         statusbar_pop_all();
2669         procmsg_msg_list_free(mlist);
2670
2671         return ret;
2672 }
2673
2674 static gint folder_item_get_msg_num_by_file(FolderItem *dest, const gchar *file)
2675 {
2676         static HeaderEntry hentry[] = {{"Message-ID:",  NULL, TRUE},
2677                                        {NULL,           NULL, FALSE}};
2678         FILE *fp;
2679         MsgInfo *msginfo;
2680         gint msgnum = 0;
2681         gchar buf[BUFFSIZE];
2682
2683         if ((fp = g_fopen(file, "rb")) == NULL)
2684                 return 0;
2685
2686         if ((folder_has_parent_of_type(dest, F_QUEUE)) || 
2687             (folder_has_parent_of_type(dest, F_DRAFT)))
2688                 while (fgets(buf, sizeof(buf), fp) != NULL)
2689                         if (buf[0] == '\r' || buf[0] == '\n') break;
2690
2691         procheader_get_header_fields(fp, hentry);
2692         if (hentry[0].body) {
2693                 extract_parenthesis(hentry[0].body, '<', '>');
2694                 remove_space(hentry[0].body);
2695                 if ((msginfo = msgcache_get_msg_by_id(dest->cache, hentry[0].body)) != NULL) {
2696                         msgnum = msginfo->msgnum;
2697                         procmsg_msginfo_free(msginfo);
2698
2699                         debug_print("found message as uid %d\n", msgnum);
2700                 }
2701         }
2702         
2703         g_free(hentry[0].body);
2704         hentry[0].body = NULL;
2705         fclose(fp);
2706
2707         return msgnum;
2708 }
2709
2710 static void copy_msginfo_flags(MsgInfo *source, MsgInfo *dest)
2711 {
2712         MsgPermFlags perm_flags = 0;
2713         MsgTmpFlags tmp_flags = 0;
2714
2715         /* create new flags */
2716         if (source != NULL) {
2717                 /* copy original flags */
2718                 perm_flags = source->flags.perm_flags;
2719                 tmp_flags = source->flags.tmp_flags;
2720         } else {
2721                 perm_flags = dest->flags.perm_flags;
2722                 tmp_flags = dest->flags.tmp_flags;
2723         }
2724
2725         /* remove new, unread and deleted in special folders */
2726         if (folder_has_parent_of_type(dest->folder, F_OUTBOX) || 
2727             folder_has_parent_of_type(dest->folder, F_QUEUE) || 
2728             folder_has_parent_of_type(dest->folder, F_DRAFT) || 
2729             folder_has_parent_of_type(dest->folder, F_TRASH))
2730                 perm_flags &= ~(MSG_NEW | MSG_UNREAD | MSG_DELETED);
2731
2732         /* set ignore flag of ignored parent exists */
2733         if (procmsg_msg_has_flagged_parent(dest, MSG_IGNORE_THREAD))
2734                 perm_flags |= MSG_IGNORE_THREAD;
2735
2736         /* Unset tmp flags that should not be copied */
2737         tmp_flags &= ~(MSG_MOVE | MSG_COPY | MSG_MOVE_DONE);
2738
2739         /* unset flags that are set but should not */
2740         /* and set new flags */
2741         procmsg_msginfo_change_flags(dest,
2742                                   ~dest->flags.perm_flags & perm_flags,
2743                                   ~dest->flags.tmp_flags  & tmp_flags,
2744                                    dest->flags.perm_flags & ~perm_flags,
2745                                    dest->flags.tmp_flags  & ~tmp_flags);
2746         
2747         if (source && source->tags) {
2748                 g_slist_free(dest->tags);
2749                 dest->tags = g_slist_copy(source->tags);
2750         }
2751 }
2752
2753 static void add_msginfo_to_cache(FolderItem *item, MsgInfo *newmsginfo, MsgInfo *flagsource)
2754 {
2755         /* update folder stats */
2756         if (MSG_IS_NEW(newmsginfo->flags))
2757                 item->new_msgs++;
2758         if (MSG_IS_UNREAD(newmsginfo->flags))
2759                 item->unread_msgs++;
2760         if (MSG_IS_UNREAD(newmsginfo->flags) && procmsg_msg_has_marked_parent(newmsginfo))
2761                 item->unreadmarked_msgs++;
2762         if (MSG_IS_MARKED(newmsginfo->flags))
2763                 item->marked_msgs++;
2764         item->total_msgs++;
2765
2766         folder_item_update_freeze();
2767
2768         if (!item->cache)
2769                 folder_item_read_cache(item);
2770
2771         msgcache_add_msg(item->cache, newmsginfo);
2772         copy_msginfo_flags(flagsource, newmsginfo);
2773         folder_item_update_with_msg(item,  F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_ADDMSG, newmsginfo);
2774         folder_item_update_thaw();
2775 }
2776
2777 static void remove_msginfo_from_cache(FolderItem *item, MsgInfo *msginfo)
2778 {
2779         MsgInfoUpdate msginfo_update;
2780
2781         if (!item->cache)
2782                 folder_item_read_cache(item);
2783
2784         if (MSG_IS_NEW(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
2785                 msginfo->folder->new_msgs--;
2786         if (MSG_IS_UNREAD(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
2787                 msginfo->folder->unread_msgs--;
2788         if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2789                 msginfo->folder->unreadmarked_msgs--;
2790         if (MSG_IS_MARKED(msginfo->flags))
2791                 item->marked_msgs--;
2792
2793         msginfo->folder->total_msgs--;
2794
2795         msginfo_update.msginfo = msginfo;
2796         msginfo_update.flags = MSGINFO_UPDATE_DELETED;
2797         hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
2798
2799         msgcache_remove_msg(item->cache, msginfo->msgnum);
2800         folder_item_update_with_msg(msginfo->folder, F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_REMOVEMSG, msginfo);
2801 }
2802
2803 gint folder_item_add_msg(FolderItem *dest, const gchar *file,
2804                          MsgFlags *flags, gboolean remove_source)
2805 {
2806         GSList file_list;
2807         MsgFileInfo fileinfo;
2808
2809         g_return_val_if_fail(dest != NULL, -1);
2810         g_return_val_if_fail(file != NULL, -1);
2811  
2812         fileinfo.msginfo = NULL;
2813         fileinfo.file = (gchar *)file;
2814         fileinfo.flags = flags;
2815         file_list.data = &fileinfo;
2816         file_list.next = NULL;
2817
2818         return folder_item_add_msgs(dest, &file_list, remove_source);
2819 }
2820
2821 gint folder_item_add_msgs(FolderItem *dest, GSList *file_list,
2822                           gboolean remove_source)
2823 {
2824         Folder *folder;
2825         gint ret, num, lastnum = -1;
2826         GSList *file_cur;
2827         GRelation *relation;
2828         MsgFileInfo *fileinfo = NULL;
2829         gboolean folderscan = FALSE;
2830
2831         g_return_val_if_fail(dest != NULL, -1);
2832         g_return_val_if_fail(file_list != NULL, -1);
2833         g_return_val_if_fail(dest->folder != NULL, -1);
2834         if (dest->no_select)
2835                 return -1;
2836
2837         folder = dest->folder;
2838
2839         relation = g_relation_new(2);
2840         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
2841
2842         if (folder->klass->add_msgs != NULL) {
2843                 ret = folder->klass->add_msgs(folder, dest, file_list, relation);
2844                 if (ret < 0) {
2845                         g_relation_destroy(relation);
2846                         return ret;
2847                 }
2848         } else {
2849                 for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
2850                         fileinfo = (MsgFileInfo *) file_cur->data;
2851
2852                         ret = folder->klass->add_msg(folder, dest, fileinfo->file, fileinfo->flags);
2853                         if (ret < 0) {
2854                                 g_relation_destroy(relation);
2855                                 return ret;
2856                         }
2857                         g_relation_insert(relation, fileinfo, GINT_TO_POINTER(ret));
2858                 }
2859         }
2860
2861         for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
2862                 GTuples *tuples;
2863
2864                 fileinfo = (MsgFileInfo *) file_cur->data;
2865                 tuples = g_relation_select(relation, fileinfo, 0);
2866                 num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
2867                 g_tuples_destroy(tuples);
2868
2869                 if (num >= 0) {
2870                         MsgInfo *newmsginfo;
2871
2872                         if (num == 0) {
2873                                 if (!folderscan) {
2874                                         folder_item_scan_full(dest, FALSE);
2875                                         folderscan = TRUE;
2876                                 }
2877                                 num = folder_item_get_msg_num_by_file(dest, fileinfo->file);
2878                         }
2879
2880                         if (num > lastnum)
2881                                 lastnum = num;
2882
2883                         if (num >= 0 && remove_source) {
2884                                 if (g_unlink(fileinfo->file) < 0)
2885                                         FILE_OP_ERROR(fileinfo->file, "unlink");
2886                         }
2887
2888                         if (num == 0)
2889                                 continue;
2890
2891                         if (!folderscan && 
2892                             ((newmsginfo = get_msginfo(dest, num)) != NULL)) {
2893                                 add_msginfo_to_cache(dest, newmsginfo, NULL);
2894                                 procmsg_msginfo_free(newmsginfo);
2895                         } else if ((newmsginfo = msgcache_get_msg(dest->cache, num)) != NULL) {
2896                                 /* TODO: set default flags */
2897                                 procmsg_msginfo_free(newmsginfo);
2898                         }
2899                 }
2900         }
2901
2902         g_relation_destroy(relation);
2903
2904         return lastnum;
2905 }
2906
2907 static FolderItem *folder_item_move_recursive(FolderItem *src, FolderItem *dest, gboolean copy) 
2908 {
2909         GSList *mlist;
2910         FolderItem *new_item;
2911         FolderItem *next_item;
2912         GNode *srcnode;
2913         gchar *old_id, *new_id;
2914
2915         /* move messages */
2916         debug_print("%s %s to %s\n", copy?"Copying":"Moving", src->path, dest->path);
2917         new_item = folder_create_folder(dest, src->name);
2918         if (new_item == NULL) {
2919                 printf("Can't create folder\n");
2920                 return NULL;
2921         }
2922         
2923         if (new_item->folder == NULL)
2924                 new_item->folder = dest->folder;
2925
2926         /* move messages */
2927         log_message(LOG_PROTOCOL, copy ?_("Copying %s to %s...\n"):_("Moving %s to %s...\n"), 
2928                         src->name, new_item->path);
2929
2930         mlist = folder_item_get_msg_list(src);
2931         
2932         if (mlist != NULL) {
2933                 if (copy)
2934                         folder_item_copy_msgs(new_item, mlist);
2935                 else
2936                         folder_item_move_msgs(new_item, mlist);
2937                 procmsg_msg_list_free(mlist);
2938         }
2939         
2940         /*copy prefs*/
2941         folder_item_prefs_copy_prefs(src, new_item);
2942         
2943         /* copy internal data */
2944         if (src->folder->klass == new_item->folder->klass &&
2945             src->folder->klass->copy_private_data != NULL)
2946                 src->folder->klass->copy_private_data(src->folder,
2947                                         src, new_item);
2948         new_item->collapsed = src->collapsed;
2949         new_item->thread_collapsed = src->thread_collapsed;
2950         new_item->threaded  = src->threaded;
2951         new_item->ret_rcpt  = src->ret_rcpt;
2952         new_item->hide_read_msgs = src->hide_read_msgs;
2953         new_item->sort_key  = src->sort_key;
2954         new_item->sort_type = src->sort_type;
2955
2956         prefs_matcher_write_config();
2957         
2958         /* recurse */
2959         srcnode = src->folder->node;    
2960         srcnode = g_node_find(srcnode, G_PRE_ORDER, G_TRAVERSE_ALL, src);
2961         srcnode = srcnode->children;
2962         while (srcnode != NULL) {
2963                 if (srcnode && srcnode->data) {
2964                         next_item = (FolderItem*) srcnode->data;
2965                         srcnode = srcnode->next;
2966                         if (folder_item_move_recursive(next_item, new_item, copy) == NULL) {
2967                                 return NULL;
2968                         }
2969                 }
2970         }
2971         old_id = folder_item_get_identifier(src);
2972         new_id = folder_item_get_identifier(new_item);
2973
2974         /* if src supports removing, otherwise only copy folder */
2975         if (src->folder->klass->remove_folder != NULL && !copy) 
2976                 src->folder->klass->remove_folder(src->folder, src);
2977         folder_write_list();
2978
2979         if (!copy) {
2980                 debug_print("updating rules : %s => %s\n", old_id, new_id);
2981                 if (old_id != NULL && new_id != NULL) {
2982                         prefs_filtering_rename_path(old_id, new_id);
2983                         account_rename_path(old_id, new_id);
2984                 }
2985         }
2986         g_free(old_id);
2987         g_free(new_id);
2988         
2989         return new_item;
2990 }
2991
2992 gint folder_item_move_to(FolderItem *src, FolderItem *dest, FolderItem **new_item, gboolean copy)
2993 {
2994         FolderItem *tmp = folder_item_parent(dest);
2995         gchar * src_identifier, * dst_identifier;
2996         gchar * phys_srcpath, * phys_dstpath, *tmppath;
2997
2998         while (tmp) {
2999                 if (tmp == src) {
3000                         return F_MOVE_FAILED_DEST_IS_CHILD;
3001                 }
3002                 tmp = folder_item_parent(tmp);
3003         }
3004         
3005         tmp = folder_item_parent(src);
3006         
3007         src_identifier = folder_item_get_identifier(src);
3008         dst_identifier = folder_item_get_identifier(dest);
3009         
3010         if(dst_identifier == NULL && dest->folder && folder_item_parent(dest) == NULL) {
3011                 /* dest can be a root folder */
3012                 dst_identifier = folder_get_identifier(dest->folder);
3013         }
3014         if (src_identifier == NULL || dst_identifier == NULL) {
3015                 debug_print("Can't get identifiers\n");
3016                 return F_MOVE_FAILED;
3017         }
3018
3019         if (src->folder != dest->folder && !copy) {
3020                 return F_MOVE_FAILED_DEST_OUTSIDE_MAILBOX;
3021         }
3022
3023         phys_srcpath = folder_item_get_path(src);
3024         tmppath = folder_item_get_path(dest);
3025         phys_dstpath = g_strconcat(tmppath,
3026                        G_DIR_SEPARATOR_S,
3027                        g_path_get_basename(phys_srcpath),
3028                        NULL);
3029         g_free(tmppath);
3030
3031         if (folder_item_parent(src) == dest || src == dest) {
3032                 g_free(src_identifier);
3033                 g_free(dst_identifier);
3034                 g_free(phys_srcpath);
3035                 g_free(phys_dstpath);
3036                 return F_MOVE_FAILED_DEST_IS_PARENT;
3037         }
3038         debug_print("moving \"%s\" to \"%s\"\n", phys_srcpath, phys_dstpath);
3039         if ((tmp = folder_item_move_recursive(src, dest, copy)) == NULL) {
3040                 return F_MOVE_FAILED;
3041         }
3042         
3043         g_free(src_identifier);
3044         g_free(dst_identifier);
3045         g_free(phys_srcpath);
3046         g_free(phys_dstpath);
3047
3048         *new_item = tmp;
3049
3050         return F_MOVE_OK;
3051 }
3052
3053 /**
3054  * Copy a list of message to a new folder and remove
3055  * source messages if wanted
3056  */
3057 static gint do_copy_msgs(FolderItem *dest, GSList *msglist, gboolean remove_source)
3058 {
3059         Folder *folder;
3060         GSList *l;
3061         gint num, lastnum = -1;
3062         gboolean folderscan = FALSE;
3063         GRelation *relation;
3064         GSList *not_moved = NULL;
3065         gint total = 0, curmsg = 0;
3066         MsgInfo *msginfo = NULL;
3067
3068         g_return_val_if_fail(dest != NULL, -1);
3069         g_return_val_if_fail(msglist != NULL, -1);
3070
3071         folder = dest->folder;
3072
3073         g_return_val_if_fail(folder->klass->copy_msg != NULL, -1);
3074         if (dest->no_select)
3075                 return -1;
3076
3077         msginfo = (MsgInfo *)msglist->data;
3078         
3079         if (!msginfo)
3080                 return -1;
3081         
3082         if (!MSG_IS_QUEUED(msginfo->flags) && 
3083             MSG_IS_DRAFT(msginfo->flags) && 
3084             folder_has_parent_of_type(dest, F_QUEUE)) {
3085                 GSList *cur = msglist;
3086                 gboolean queue_err = FALSE;
3087                 for (; cur; cur = cur->next) {
3088                         Compose *compose = NULL;
3089                         FolderItem *queue = dest;
3090                         int val = 0;
3091                         
3092                         msginfo = (MsgInfo *)cur->data;
3093                         compose = compose_reedit(msginfo, TRUE);
3094                         if (compose == NULL) {
3095                                 queue_err = TRUE;
3096                                 continue;
3097                         }
3098                         val = compose_queue(compose, NULL, &queue, NULL,
3099                                         FALSE);
3100                         if (val < 0) {
3101                                 queue_err = TRUE;
3102                         } else if (remove_source) {
3103                                 folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
3104                         }
3105                         if (val == 0)
3106                                 compose_close(compose);
3107                 }
3108                 return queue_err ? -1:0;
3109         }
3110
3111         relation = g_relation_new(2);
3112         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
3113         g_relation_index(relation, 1, g_direct_hash, g_direct_equal);
3114
3115         for (l = msglist ; l != NULL ; l = g_slist_next(l)) {
3116                 MsgInfo * msginfo = (MsgInfo *) l->data;
3117
3118                 if (msginfo->planned_download != 0) {
3119                         int old_planned = msginfo->planned_download;
3120                         partial_unmark(msginfo);
3121                         /* little hack to reenable after */
3122                         msginfo->planned_download = old_planned;
3123                 }
3124         }
3125
3126         /* 
3127          * Copy messages to destination folder and 
3128          * store new message numbers in newmsgnums
3129          */
3130         if (folder->klass->copy_msgs != NULL) {
3131                 if (folder->klass->copy_msgs(folder, dest, msglist, relation) < 0) {
3132                         g_relation_destroy(relation);
3133                         return -1;
3134                 }
3135         } else {
3136                 MsgInfo * msginfo;
3137                 l = msglist;
3138
3139                 /* immediately stop if src and dest folders are identical */
3140                 if (l != NULL) {
3141                         msginfo = (MsgInfo *) l->data;
3142                         if (msginfo != NULL && msginfo->folder == dest) {
3143                                 g_relation_destroy(relation);
3144                                 return -1;
3145                         }
3146                 }
3147
3148                 for (; l != NULL ; l = g_slist_next(l)) {
3149                         msginfo = (MsgInfo *) l->data;
3150
3151                         num = folder->klass->copy_msg(folder, dest, msginfo);
3152                         if (num > 0)
3153                                 g_relation_insert(relation, msginfo, GINT_TO_POINTER(num));
3154                         else
3155                                 not_moved = g_slist_prepend(not_moved, msginfo);
3156                 }
3157         }
3158
3159         if (remove_source) {
3160                 MsgInfo *msginfo = (MsgInfo *) msglist->data;
3161                 FolderItem *item = msginfo->folder;
3162                 /*
3163                  * Remove source messages from their folders if
3164                  * copying was successfull and update folder
3165                  * message counts
3166                  */
3167                 if (not_moved == NULL && item->folder->klass->remove_msgs) {
3168                         item->folder->klass->remove_msgs(item->folder,
3169                                                                 msginfo->folder,
3170                                                                 msglist,
3171                                                                 relation);
3172                 }
3173                 for (l = msglist; l != NULL; l = g_slist_next(l)) {
3174                         GTuples *tuples;
3175                         msginfo = (MsgInfo *) l->data;
3176                         item = msginfo->folder;
3177
3178                         tuples = g_relation_select(relation, msginfo, 0);
3179                         if (tuples) {
3180                                 if (tuples->len)
3181                                         num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
3182                                 else
3183                                         num = 0;
3184                                 g_tuples_destroy(tuples);
3185                         } else {
3186                                 num = -1;
3187                         }
3188
3189                         if (g_slist_find(not_moved, msginfo))
3190                                 continue;
3191
3192                         if ((num >= 0) && (item->folder->klass->remove_msg != NULL)) {
3193                                 if (!item->folder->klass->remove_msgs)
3194                                         item->folder->klass->remove_msg(item->folder,
3195                                                                 msginfo->folder,
3196                                                                 msginfo->msgnum);
3197                                 remove_msginfo_from_cache(item, msginfo);
3198                         }
3199                 }
3200         }
3201
3202         /* Read cache for dest folder */
3203         if (!dest->cache) folder_item_read_cache(dest);
3204
3205         /* 
3206          * Fetch new MsgInfos for new messages in dest folder,
3207          * add them to the msgcache and update folder message counts
3208          */
3209         if (g_relation_count(relation, GINT_TO_POINTER(0), 1) > 0) {
3210                 folder_item_scan_full(dest, FALSE);
3211                 folderscan = TRUE;
3212         }
3213
3214         statusbar_print_all(_("Updating cache for %s..."), dest->path ? dest->path : "(null)");
3215         total = g_slist_length(msglist);
3216         for (l = msglist; l != NULL; l = g_slist_next(l)) {
3217                 MsgInfo *msginfo = (MsgInfo *) l->data;
3218                 GTuples *tuples;
3219
3220                 tuples = g_relation_select(relation, msginfo, 0);
3221                 if (tuples->len > 0) {
3222                         num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
3223                         g_tuples_destroy(tuples);
3224                 } else {
3225                         num = 0;
3226                         if (tuples)
3227                                 g_tuples_destroy(tuples);
3228                 }
3229                 statusbar_progress_all(curmsg++,total, 100);
3230                 if (curmsg % 100 == 0)
3231                         GTK_EVENTS_FLUSH();
3232
3233                 if (num >= 0) {
3234                         MsgInfo *newmsginfo = NULL;
3235
3236                         if (!folderscan && num > 0) {
3237                                 newmsginfo = get_msginfo(dest, num);
3238                                 if (newmsginfo != NULL) {
3239                                         add_msginfo_to_cache(dest, newmsginfo, msginfo);
3240                                 }
3241                         }
3242                         if (newmsginfo == NULL) {
3243                                 if (!folderscan) {
3244                                         folder_item_scan_full(dest, FALSE);
3245                                         folderscan = TRUE;
3246                                 }
3247                                 if (msginfo->msgid != NULL) {
3248                                         newmsginfo = folder_item_get_msginfo_by_msgid(dest, msginfo->msgid);
3249                                         if (newmsginfo != NULL) {
3250                                                 copy_msginfo_flags(msginfo, newmsginfo);
3251                                                 num = newmsginfo->msgnum;
3252                                         }
3253                                 }
3254                         }
3255
3256                         if (msginfo->planned_download 
3257                             == POP3_PARTIAL_DLOAD_DELE) {
3258                                 partial_mark_for_delete(newmsginfo);
3259                         }
3260                         if (msginfo->planned_download 
3261                             == POP3_PARTIAL_DLOAD_DLOAD) {
3262                                 partial_mark_for_download(newmsginfo);
3263                         }
3264                         if (!MSG_IS_POSTFILTERED (msginfo->flags)) {
3265                             procmsg_msginfo_set_flags (   msginfo, MSG_POSTFILTERED, 0);
3266                             procmsg_msginfo_set_flags (newmsginfo, MSG_POSTFILTERED, 0);
3267                             hooks_invoke (MAIL_POSTFILTERING_HOOKLIST, newmsginfo);
3268                         }
3269                         procmsg_msginfo_free(newmsginfo);
3270
3271
3272                         if (num > lastnum)
3273                                 lastnum = num;
3274                 }
3275         }
3276         statusbar_progress_all(0,0,0);
3277         statusbar_pop_all();
3278
3279         g_relation_destroy(relation);
3280         if (not_moved != NULL) {
3281                 g_slist_free(not_moved);
3282                 return -1;
3283         } else
3284                 return lastnum;
3285 }
3286
3287 /**
3288  * Move a message to a new folder.
3289  *
3290  * \param dest Destination folder
3291  * \param msginfo The message
3292  */
3293 gint folder_item_move_msg(FolderItem *dest, MsgInfo *msginfo)
3294 {
3295         GSList list;
3296
3297         g_return_val_if_fail(dest != NULL, -1);
3298         g_return_val_if_fail(msginfo != NULL, -1);
3299
3300         list.data = msginfo;
3301         list.next = NULL;
3302
3303         return do_copy_msgs(dest, &list, TRUE);
3304 }
3305
3306 /**
3307  * Move a list of messages to a new folder.
3308  *
3309  * \param dest Destination folder
3310  * \param msglist List of messages
3311  */
3312 gint folder_item_move_msgs(FolderItem *dest, GSList *msglist)
3313 {
3314         gint result = -1;
3315         g_return_val_if_fail(dest != NULL, -1);
3316         g_return_val_if_fail(msglist != NULL, -1);
3317         inc_lock();
3318         result = do_copy_msgs(dest, msglist, TRUE);
3319         inc_unlock();
3320         return result;
3321 }
3322
3323 /**
3324  * Copy a message to a new folder.
3325  *
3326  * \param dest Destination folder
3327  * \param msginfo The message
3328  */
3329 gint folder_item_copy_msg(FolderItem *dest, MsgInfo *msginfo)
3330 {
3331         GSList list;
3332
3333         g_return_val_if_fail(dest != NULL, -1);
3334         g_return_val_if_fail(msginfo != NULL, -1);
3335     
3336         list.data = msginfo;
3337         list.next = NULL;
3338
3339         return do_copy_msgs(dest, &list, FALSE);
3340 }
3341
3342 /**
3343  * Copy a list of messages to a new folder.
3344  *
3345  * \param dest Destination folder
3346  * \param msglist List of messages
3347  */
3348 gint folder_item_copy_msgs(FolderItem *dest, GSList *msglist)
3349 {
3350         gint result;
3351         g_return_val_if_fail(dest != NULL, -1);
3352         g_return_val_if_fail(msglist != NULL, -1);
3353
3354         inc_lock();
3355         result = do_copy_msgs(dest, msglist, FALSE);
3356         inc_unlock();
3357         
3358         return result;
3359 }
3360
3361 gint folder_item_remove_msg(FolderItem *item, gint num)
3362 {
3363         Folder *folder;
3364         gint ret;
3365         MsgInfo *msginfo;
3366
3367         g_return_val_if_fail(item != NULL, -1);
3368         folder = item->folder;
3369         g_return_val_if_fail(folder->klass->remove_msg != NULL, -1);
3370         if (item->no_select)
3371                 return -1;
3372
3373         if (!item->cache) folder_item_read_cache(item);
3374
3375         ret = folder->klass->remove_msg(folder, item, num);
3376
3377         msginfo = msgcache_get_msg(item->cache, num);
3378         if (msginfo != NULL) {
3379                 remove_msginfo_from_cache(item, msginfo);
3380                 procmsg_msginfo_free(msginfo);
3381         }
3382
3383         return ret;
3384 }
3385
3386 gint folder_item_remove_msgs(FolderItem *item, GSList *msglist)
3387 {
3388         Folder *folder;
3389         gint ret = 0;
3390
3391         g_return_val_if_fail(item != NULL, -1);
3392         folder = item->folder;
3393         g_return_val_if_fail(folder != NULL, -1);
3394         if (item->no_select)
3395                 return -1;
3396         inc_lock();
3397         if (!item->cache) folder_item_read_cache(item);
3398
3399         folder_item_update_freeze();
3400         if (item->folder->klass->remove_msgs) {
3401                 ret = item->folder->klass->remove_msgs(item->folder,
3402                                                         item,
3403                                                         msglist,
3404                                                         NULL);
3405         }
3406         while (ret == 0 && msglist != NULL) {
3407                 MsgInfo *msginfo = (MsgInfo *)msglist->data;
3408                 if (MSG_IS_LOCKED(msginfo->flags)) {
3409                         msglist = msglist->next;
3410                         continue;
3411                 }
3412                 if (!item->folder->klass->remove_msgs)
3413                         ret = folder_item_remove_msg(item, msginfo->msgnum);
3414                 if (ret != 0) break;
3415                 msgcache_remove_msg(item->cache, msginfo->msgnum);
3416                 msglist = msglist->next;
3417         }
3418         folder_item_scan_full(item, FALSE);
3419         folder_item_update_thaw();
3420         inc_unlock();
3421         return ret;
3422 }
3423
3424 gint folder_item_remove_all_msg(FolderItem *item)
3425 {
3426         Folder *folder;
3427         gint result;
3428
3429         g_return_val_if_fail(item != NULL, -1);
3430         if (item->no_select)
3431                 return -1;
3432
3433         folder = item->folder;
3434
3435         inc_lock();
3436         if (folder->klass->remove_all_msg != NULL) {
3437                 result = folder->klass->remove_all_msg(folder, item);
3438
3439                 if (result == 0) {
3440                         folder_item_free_cache(item, TRUE);
3441                         item->cache = msgcache_new();
3442                 }
3443         } else {
3444                 MsgInfoList *msglist;
3445
3446                 msglist = folder_item_get_msg_list(item);
3447                 result = folder_item_remove_msgs(item, msglist);
3448                 procmsg_msg_list_free(msglist);
3449         }
3450
3451         if (result == 0) {
3452                 item->new_msgs = 0;
3453                 item->unread_msgs = 0;
3454                 item->unreadmarked_msgs = 0;
3455                 item->marked_msgs = 0;
3456                 item->total_msgs = 0;
3457                 folder_item_update(item, F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT);
3458         }
3459
3460         inc_unlock();
3461         return result;
3462 }
3463
3464 void folder_item_change_msg_flags(FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
3465 {
3466         g_return_if_fail(item != NULL);
3467         g_return_if_fail(msginfo != NULL);
3468         if (item->no_select)
3469                 return;
3470         
3471         if (item->folder->klass->change_flags != NULL) {
3472                 item->folder->klass->change_flags(item->folder, item, msginfo, newflags);
3473         } else {
3474                 msginfo->flags.perm_flags = newflags;
3475         }
3476 }
3477
3478 gboolean folder_item_is_msg_changed(FolderItem *item, MsgInfo *msginfo)
3479 {
3480         Folder *folder;
3481
3482         g_return_val_if_fail(item != NULL, FALSE);
3483         if (item->no_select)
3484                 return FALSE;
3485
3486         folder = item->folder;
3487
3488         g_return_val_if_fail(folder->klass->is_msg_changed != NULL, -1);
3489
3490         return folder->klass->is_msg_changed(folder, item, msginfo);
3491 }
3492
3493 static gchar *folder_item_get_cache_file(FolderItem *item)
3494 {
3495         gchar *path;
3496         gchar *file;
3497         gchar *old_file;
3498
3499         g_return_val_if_fail(item != NULL, NULL);
3500         g_return_val_if_fail(item->path != NULL, NULL);
3501
3502         path = folder_item_get_path(item);
3503         g_return_val_if_fail(path != NULL, NULL);
3504         if (!is_dir_exist(path))
3505                 make_dir_hier(path);
3506         file = g_strconcat(path, G_DIR_SEPARATOR_S, CACHE_FILE, NULL);
3507         old_file = g_strconcat(path, G_DIR_SEPARATOR_S, OLD_CACHE_FILE, NULL);
3508
3509         if (!is_file_exist(file) && is_file_exist(old_file))
3510                 move_file(old_file, file, FALSE);
3511         g_free(old_file);
3512         g_free(path);
3513
3514         return file;
3515 }
3516
3517 static gchar *folder_item_get_mark_file(FolderItem *item)
3518 {
3519         gchar *path;
3520         gchar *file;
3521         gchar *old_file;
3522
3523         g_return_val_if_fail(item != NULL, NULL);
3524         g_return_val_if_fail(item->path != NULL, NULL);
3525
3526         path = folder_item_get_path(item);
3527         g_return_val_if_fail(path != NULL, NULL);
3528         if (!is_dir_exist(path))
3529                 make_dir_hier(path);
3530         file = g_strconcat(path, G_DIR_SEPARATOR_S, MARK_FILE, NULL);
3531         old_file = g_strconcat(path, G_DIR_SEPARATOR_S, OLD_MARK_FILE, NULL);
3532
3533         if (!is_file_exist(file) && is_file_exist(old_file))
3534                 move_file(old_file, file, FALSE);
3535         g_free(old_file);
3536         g_free(path);
3537
3538         return file;
3539 }
3540
3541 static gchar *folder_item_get_tags_file(FolderItem *item)
3542 {
3543         gchar *path;
3544         gchar *identifier;
3545         gchar *file;
3546
3547         /* we save tags files in rc_dir, because tagsrc is there too,
3548          * and storing tags directly in the mailboxes would give strange
3549          * result when using another Claws mailbox from another install
3550          * with different tags. */
3551
3552         g_return_val_if_fail(item != NULL, NULL);
3553
3554         identifier = folder_item_get_identifier(item);
3555         g_return_val_if_fail(identifier != NULL, NULL);
3556         
3557         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
3558                            "tagsdb", G_DIR_SEPARATOR_S,
3559                            identifier, NULL);
3560         
3561         g_free(identifier);
3562                            
3563         if (!is_dir_exist(path))
3564                 make_dir_hier(path);
3565
3566         file = g_strconcat(path, G_DIR_SEPARATOR_S, TAGS_FILE, NULL);
3567         
3568         g_free(path);
3569
3570         return file;
3571 }
3572
3573 static gpointer xml_to_folder_item(gpointer nodedata, gpointer data)
3574 {
3575         XMLNode *xmlnode = (XMLNode *) nodedata;
3576         Folder *folder = (Folder *) data;
3577         FolderItem *item;
3578
3579         g_return_val_if_fail(xmlnode != NULL, NULL);
3580         g_return_val_if_fail(folder != NULL, NULL);
3581
3582         if (strcmp2(xmlnode->tag->tag, "folderitem") != 0) {
3583                 g_warning("tag name != \"folderitem\"\n");
3584                 return NULL;
3585         }
3586
3587         item = folder_item_new(folder, "", "");
3588         if (folder->klass->item_set_xml != NULL)
3589                 folder->klass->item_set_xml(folder, item, xmlnode->tag);
3590         else
3591                 folder_item_set_xml(folder, item, xmlnode->tag);
3592
3593         item->folder = folder;
3594
3595         switch (item->stype) {
3596         case F_INBOX:  folder->inbox  = item; break;
3597         case F_OUTBOX: folder->outbox = item; break;
3598         case F_DRAFT:  folder->draft  = item; break;
3599         case F_QUEUE:  folder->queue  = item; break;
3600         case F_TRASH:  folder->trash  = item; break;
3601         default:       break;
3602         }
3603         folder_item_prefs_read_config(item);
3604
3605         return item;
3606 }
3607
3608 static gboolean folder_item_set_node(GNode *node, gpointer data)
3609 {
3610         FolderItem *item = (FolderItem *) node->data;
3611         item->node = node;
3612
3613         return FALSE;
3614 }
3615
3616 static Folder *folder_get_from_xml(GNode *node)
3617 {
3618         Folder *folder;
3619         XMLNode *xmlnode;
3620         GList *list;
3621         FolderClass *klass = NULL;
3622         GNode *cur;
3623
3624         g_return_val_if_fail(node->data != NULL, NULL);
3625
3626         xmlnode = node->data;
3627         if (strcmp2(xmlnode->tag->tag, "folder") != 0) {
3628                 g_warning("tag name != \"folder\"\n");
3629                 return NULL;
3630         }
3631         list = xmlnode->tag->attr;
3632         for (; list != NULL; list = list->next) {
3633                 XMLAttr *attr = list->data;
3634
3635                 if (!attr || !attr->name || !attr->value) continue;
3636                 if (!strcmp(attr->name, "type"))
3637                         klass = folder_get_class_from_string(attr->value);
3638         }
3639         if (klass == NULL)
3640                 return NULL;
3641
3642         folder = folder_new(klass, "", "");
3643         g_return_val_if_fail(folder != NULL, NULL);
3644
3645         if (klass->set_xml)
3646                 klass->set_xml(folder, xmlnode->tag);
3647         else
3648                 folder_set_xml(folder, xmlnode->tag);
3649
3650         cur = node->children;
3651         while (cur != NULL) {
3652                 GNode *itemnode;
3653
3654                 itemnode = g_node_map(cur, xml_to_folder_item, (gpointer) folder);
3655                 g_node_append(folder->node, itemnode);
3656                 cur = cur->next;
3657         }
3658         g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, folder_item_set_node, NULL);
3659         
3660         return folder;
3661 }
3662
3663 static gchar *folder_get_list_path(void)
3664 {
3665         static gchar *filename = NULL;
3666
3667         if (!filename)
3668                 filename =  g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
3669                                         FOLDER_LIST, NULL);
3670
3671         return filename;
3672 }
3673
3674 #define PUT_ESCAPE_STR(fp, attr, str)                   \
3675 {                                                       \
3676         fputs(" " attr "=\"", fp);                      \
3677         xml_file_put_escape_str(fp, str);               \
3678         fputs("\"", fp);                                \
3679 }
3680
3681 static gpointer folder_item_to_xml(gpointer nodedata, gpointer data)
3682 {
3683         FolderItem *item = (FolderItem *) nodedata;
3684         XMLTag *tag;
3685
3686         g_return_val_if_fail(item != NULL, NULL);
3687
3688         if (item->folder->klass->item_get_xml != NULL)
3689                 tag = item->folder->klass->item_get_xml(item->folder, item);
3690         else
3691                 tag = folder_item_get_xml(item->folder, item);
3692
3693         return xml_node_new(tag, NULL);
3694 }
3695
3696 static GNode *folder_get_xml_node(Folder *folder)
3697 {
3698         GNode *node;
3699         XMLNode *xmlnode;
3700         XMLTag *tag;
3701
3702         g_return_val_if_fail(folder != NULL, NULL);
3703
3704         if (folder->klass->get_xml != NULL)
3705                 tag = folder->klass->get_xml(folder);
3706         else
3707                 tag = folder_get_xml(folder);
3708
3709         xml_tag_add_attr(tag, xml_attr_new("type", folder->klass->idstr));
3710
3711         xmlnode = xml_node_new(tag, NULL);
3712
3713         node = g_node_new(xmlnode);
3714         
3715         g_return_val_if_fail (folder->node != NULL, NULL);
3716         
3717         if (folder->node->children) {
3718                 GNode *cur;
3719
3720                 cur = folder->node->children;
3721                 while (cur) {
3722                         GNode *xmlnode;
3723
3724                         xmlnode = g_node_map(cur, folder_item_to_xml, (gpointer) folder);
3725                         g_node_append(node, xmlnode);
3726                         cur = cur->next;
3727                 }
3728         }
3729
3730         return node;
3731 }
3732
3733 static void folder_update_op_count_rec(GNode *node)
3734 {
3735         FolderItem *fitem = FOLDER_ITEM(node->data);
3736
3737         if (g_node_depth(node) > 0) {
3738                 if (fitem->op_count > 0) {
3739                         fitem->op_count = 0;
3740                         folder_item_update(fitem, F_ITEM_UPDATE_MSGCNT);
3741                 }
3742                 if (node->children) {
3743                         GNode *child;
3744
3745                         child = node->children;
3746                         while (child) {
3747                                 GNode *cur;
3748
3749                                 cur = child;
3750                                 child = cur->next;
3751                                 folder_update_op_count_rec(cur);
3752                         }
3753                 }
3754         }
3755 }
3756
3757 void folder_update_op_count(void) 
3758 {
3759         GList *cur;
3760         Folder *folder;
3761
3762         for (cur = folder_list; cur != NULL; cur = cur->next) {
3763                 folder = cur->data;
3764                 folder_update_op_count_rec(folder->node);
3765         }
3766 }
3767
3768 typedef struct _type_str {
3769         gchar * str;
3770         gint type;
3771 } type_str;
3772
3773
3774 /*
3775 static gchar * folder_item_get_tree_identifier(FolderItem * item)
3776 {
3777         if (item->parent != NULL) {
3778                 gchar * path;
3779                 gchar * id;
3780
3781                 path = folder_item_get_tree_identifier(item->parent);
3782                 if (path == NULL)
3783                         return NULL;
3784
3785                 id = g_strconcat(path, "/", item->name, NULL);
3786                 g_free(path);
3787
3788                 return id;
3789         }
3790         else {
3791                 return g_strconcat("/", item->name, NULL);
3792         }
3793 }
3794 */
3795
3796 /* CLAWS: temporary local folder for filtering */
3797 #define TEMP_FOLDER "TEMP_FOLDER"
3798 #define PROCESSING_FOLDER_ITEM "processing"     
3799
3800 static FolderItem *processing_folder_item;
3801
3802 static void folder_create_processing_folder(void)
3803 {
3804         Folder *processing_folder;
3805         gchar      *tmpname;
3806
3807         if ((processing_folder = folder_find_from_name(TEMP_FOLDER, mh_get_class())) == NULL) {
3808                 gchar *tmppath;
3809
3810                 tmppath =
3811                     g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
3812                                 "tempfolder", NULL);
3813                 processing_folder =
3814                     folder_new(mh_get_class(), TEMP_FOLDER, tmppath);
3815                 g_free(tmppath);
3816         }
3817         g_assert(processing_folder != NULL);
3818
3819         debug_print("tmpparentroot %s\n", LOCAL_FOLDER(processing_folder)->rootpath);
3820         /* FIXME: [W32] The code below does not correctly merge
3821            relative filenames; there should be a function to handle
3822            this.  */
3823         if (!is_relative_filename(LOCAL_FOLDER(processing_folder)->rootpath))
3824                 tmpname = g_strconcat(LOCAL_FOLDER(processing_folder)->rootpath,
3825                                       G_DIR_SEPARATOR_S, PROCESSING_FOLDER_ITEM,
3826                                       NULL);
3827         else
3828                 tmpname = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3829                                       LOCAL_FOLDER(processing_folder)->rootpath,
3830                                       G_DIR_SEPARATOR_S, PROCESSING_FOLDER_ITEM,
3831                                       NULL);
3832
3833         if (!is_dir_exist(tmpname)) {
3834                 debug_print("*TMP* creating %s\n", tmpname);
3835                 processing_folder_item = processing_folder->klass->create_folder(processing_folder,
3836                                                                                  processing_folder->node->data,
3837                                                                                  PROCESSING_FOLDER_ITEM);
3838         } else {
3839                 debug_print("*TMP* already created\n");
3840                 processing_folder_item = folder_item_new(processing_folder, PROCESSING_FOLDER_ITEM, PROCESSING_FOLDER_ITEM);
3841                 g_assert(processing_folder_item);
3842                 folder_item_append(processing_folder->node->data, processing_folder_item);
3843         }
3844         g_assert(processing_folder_item != NULL);
3845         g_free(tmpname);
3846 }
3847
3848 FolderItem *folder_get_default_processing(void)
3849 {
3850         if (!processing_folder_item) {
3851                 folder_create_processing_folder();
3852         }
3853         return processing_folder_item;
3854 }
3855
3856 /* folder_persist_prefs_new() - return hash table with persistent
3857  * settings (and folder name as key). 
3858  * (note that in claws other options are in the folder_item_prefs_RC
3859  * file, so those don't need to be included in PersistPref yet) 
3860  */
3861 static GHashTable *folder_persist_prefs_new(Folder *folder)
3862 {
3863         GHashTable *pptable;
3864
3865         g_return_val_if_fail(folder, NULL);
3866         pptable = g_hash_table_new(g_str_hash, g_str_equal);
3867         folder_get_persist_prefs_recursive(folder->node, pptable);
3868         return pptable;
3869 }
3870
3871 static void folder_persist_prefs_free(GHashTable *pptable)
3872 {
3873         g_return_if_fail(pptable);
3874         g_hash_table_foreach_remove(pptable, persist_prefs_free, NULL);
3875         g_hash_table_destroy(pptable);
3876 }
3877
3878 static const PersistPrefs *folder_get_persist_prefs(GHashTable *pptable, const char *name)
3879 {
3880         if (pptable == NULL || name == NULL) return NULL;
3881         return g_hash_table_lookup(pptable, name);
3882 }
3883
3884 static void folder_item_restore_persist_prefs(FolderItem *item, GHashTable *pptable)
3885 {
3886         const PersistPrefs *pp;
3887         gchar *id = folder_item_get_identifier(item);
3888
3889         pp = folder_get_persist_prefs(pptable, id); 
3890         g_free(id);
3891
3892         if (!pp) return;
3893
3894         /* CLAWS: since not all folder properties have been migrated to 
3895          * folderlist.xml, we need to call the old stuff first before
3896          * setting things that apply both to Main and Claws. */
3897         folder_item_prefs_read_config(item); 
3898
3899         item->collapsed = pp->collapsed;
3900         item->thread_collapsed = pp->thread_collapsed;
3901         item->threaded  = pp->threaded;
3902         item->ret_rcpt  = pp->ret_rcpt;
3903         item->hide_read_msgs = pp->hide_read_msgs;
3904         item->sort_key  = pp->sort_key;
3905         item->sort_type = pp->sort_type;
3906 }
3907
3908 static void folder_get_persist_prefs_recursive(GNode *node, GHashTable *pptable)
3909 {
3910         FolderItem *item = FOLDER_ITEM(node->data);
3911         PersistPrefs *pp;
3912         GNode *child, *cur;
3913         gchar *id;
3914
3915         g_return_if_fail(node != NULL);
3916         g_return_if_fail(item != NULL);
3917
3918         /* NOTE: item->path == NULL means top level folder; not interesting
3919          * to store preferences of that one.  */
3920         if (item->path) {
3921                 id = folder_item_get_identifier(item);
3922                 pp = g_new0(PersistPrefs, 1);
3923                 g_return_if_fail(pp != NULL);
3924                 pp->collapsed = item->collapsed;
3925                 pp->thread_collapsed = item->thread_collapsed;
3926                 pp->threaded  = item->threaded;
3927                 pp->ret_rcpt  = item->ret_rcpt; 
3928                 pp->hide_read_msgs = item->hide_read_msgs;
3929                 pp->sort_key  = item->sort_key;
3930                 pp->sort_type = item->sort_type;
3931                 g_hash_table_insert(pptable, id, pp);
3932         }
3933
3934         if (node->children) {
3935                 child = node->children;
3936                 while (child) {
3937                         cur = child;
3938                         child = cur->next;
3939                         folder_get_persist_prefs_recursive(cur, pptable);
3940                 }
3941         }       
3942 }
3943
3944 static gboolean persist_prefs_free(gpointer key, gpointer val, gpointer data)
3945 {
3946         g_free(key);
3947         g_free(val);
3948         return TRUE;    
3949 }
3950
3951 void folder_item_apply_processing(FolderItem *item)
3952 {
3953         GSList *processing_list;
3954         GSList *mlist, *cur;
3955         guint total = 0, curmsg = 0;
3956         gint last_apply_per_account;
3957
3958         g_return_if_fail(item != NULL);
3959
3960         if (item->no_select)
3961                return;
3962
3963         processing_list = item->prefs->processing;
3964
3965         if (!pre_global_processing && !processing_list
3966         &&  !post_global_processing)
3967                 return;
3968
3969         debug_print("processing %s\n", item->name);
3970         folder_item_update_freeze();
3971
3972         mlist = folder_item_get_msg_list(item);
3973         total = g_slist_length(mlist);
3974         statusbar_print_all(_("Processing messages..."));
3975
3976         last_apply_per_account = prefs_common.apply_per_account_filtering_rules;
3977         prefs_common.apply_per_account_filtering_rules = FILTERING_ACCOUNT_RULES_SKIP;
3978
3979         for (cur = mlist ; cur != NULL ; cur = cur->next) {
3980                 MsgInfo * msginfo;
3981
3982                 msginfo = (MsgInfo *) cur->data;
3983                 
3984                 /* reset parameters that can be modified by processing */
3985                 msginfo->hidden = 0;
3986                 msginfo->score = 0;
3987
3988                 statusbar_progress_all(curmsg++,total, 10);
3989
3990                 /* apply pre global rules */
3991                 filter_message_by_msginfo(pre_global_processing, msginfo, NULL,
3992                                 FILTERING_PRE_PROCESSING, NULL);
3993                 
3994                 /* apply rules of the folder */
3995                 filter_message_by_msginfo(processing_list, msginfo, NULL,
3996                                 FILTERING_FOLDER_PROCESSING, item->name);
3997
3998                 /* apply post global rules */
3999                 filter_message_by_msginfo(post_global_processing, msginfo, NULL,
4000                                 FILTERING_POST_PROCESSING, NULL);
4001                 if (curmsg % 10 == 0)
4002                         GTK_EVENTS_FLUSH();
4003         }
4004         prefs_common.apply_per_account_filtering_rules = last_apply_per_account;
4005
4006         if (pre_global_processing || processing_list
4007             || post_global_processing)
4008                 filtering_move_and_copy_msgs(mlist);
4009         for (cur = mlist ; cur != NULL ; cur = cur->next) {
4010                 MsgInfo * msginfo = (MsgInfo *)cur->data;
4011                 procmsg_msginfo_free(msginfo);
4012         }
4013         g_slist_free(mlist);
4014         
4015         statusbar_progress_all(0,0,0);
4016         statusbar_pop_all();
4017
4018         folder_item_update_thaw();
4019 }
4020
4021 /*
4022  *  functions for handling FolderItem content changes
4023  */
4024 static gint folder_item_update_freeze_cnt = 0;
4025
4026 static void folder_item_update_with_msg(FolderItem *item, FolderItemUpdateFlags update_flags, MsgInfo *msg)
4027 {
4028         if (folder_item_update_freeze_cnt == 0 /* || (msg != NULL && item->opened) */) {
4029                 FolderItemUpdateData source;
4030         
4031                 source.item = item;
4032                 source.update_flags = update_flags;
4033                 source.msg = msg;
4034                 hooks_invoke(FOLDER_ITEM_UPDATE_HOOKLIST, &source);
4035         } else {
4036                 item->update_flags |= update_flags & ~(F_ITEM_UPDATE_ADDMSG | F_ITEM_UPDATE_REMOVEMSG);
4037         }
4038 }
4039
4040 /**
4041  * Notify the folder system about changes to a folder. If the
4042  * update system is not frozen the FOLDER_ITEM_UPDATE_HOOKLIST will
4043  * be invoked, otherwise the changes will be remebered until
4044  * the folder system is thawed.
4045  *
4046  * \param item The FolderItem that was changed
4047  * \param update_flags Type of changed that was made
4048  */
4049 void folder_item_update(FolderItem *item, FolderItemUpdateFlags update_flags)
4050 {
4051         folder_item_update_with_msg(item, update_flags, NULL);
4052 }
4053
4054 void folder_item_update_recursive(FolderItem *item, FolderItemUpdateFlags update_flags)
4055 {
4056         GNode *node = item->folder->node;       
4057
4058         node = g_node_find(node, G_PRE_ORDER, G_TRAVERSE_ALL, item);
4059         node = node->children;
4060
4061         folder_item_update(item, update_flags);
4062         while (node != NULL) {
4063                 if (node && node->data) {
4064                         FolderItem *next_item = (FolderItem*) node->data;
4065
4066                         folder_item_update(next_item, update_flags);
4067                 }
4068                 node = node->next;
4069         }
4070 }
4071
4072 void folder_item_update_freeze(void)
4073 {
4074         folder_item_update_freeze_cnt++;
4075 }
4076
4077 static void folder_item_update_func(FolderItem *item, gpointer data)
4078 {
4079         FolderItemUpdateData source;
4080     
4081         if (item->update_flags) {
4082                 source.item = item;
4083                 source.update_flags = item->update_flags;
4084                 source.msg = NULL;
4085                 hooks_invoke(FOLDER_ITEM_UPDATE_HOOKLIST, &source);                             
4086                 item->update_flags = 0;
4087         }
4088 }
4089
4090 void folder_item_update_thaw(void)
4091 {
4092         if (folder_item_update_freeze_cnt > 0)
4093                 folder_item_update_freeze_cnt--;
4094         if (folder_item_update_freeze_cnt == 0) {
4095                 /* Update all folders */
4096                 folder_func_to_all_folders(folder_item_update_func, NULL);
4097         }
4098 }
4099
4100 void folder_item_synchronise(FolderItem *item)
4101 {
4102         if (!item)
4103                 return;
4104         if (item->prefs->offlinesync && item->folder->klass->synchronise) {
4105                 statusbar_print_all(_("Synchronising %s for offline use...\n"), item->path ? item->path : "(null)");
4106                 item->folder->klass->synchronise(item, 
4107                         item->prefs->offlinesync_days);
4108                 if (item->prefs->offlinesync_days > 0 &&
4109                     item->prefs->remove_old_bodies)
4110                         folder_item_clean_local_files(item, item->prefs->offlinesync_days);
4111                 statusbar_pop_all();
4112         }
4113 }
4114
4115 static void folder_item_synchronise_func(FolderItem *item, gpointer data)
4116 {
4117         Folder *folder = (Folder *)data;
4118         if (folder == NULL || item->folder == folder) {
4119                 folder_item_synchronise(item);
4120         }
4121 }
4122
4123 void folder_synchronise(Folder *folder)
4124 {
4125         folder_func_to_all_folders(folder_item_synchronise_func, folder);
4126 }
4127
4128 typedef struct _WantSyncData {
4129         Folder *folder;
4130         gboolean want_sync;
4131 } WantSyncData;
4132
4133 static void folder_item_want_synchronise_func(FolderItem *item, gpointer data)
4134 {
4135         WantSyncData *want_sync_data = (WantSyncData *)data;
4136         
4137         if (want_sync_data->folder == NULL || item->folder == want_sync_data->folder) {
4138                 if (item->prefs->offlinesync && item->folder->klass->synchronise)
4139                         want_sync_data->want_sync |= TRUE;
4140         }
4141 }
4142
4143 gboolean folder_want_synchronise(Folder *folder)
4144 {
4145         WantSyncData *want_sync_data = g_new0(WantSyncData, 1);
4146         gboolean result;
4147         want_sync_data->folder = folder;
4148         want_sync_data->want_sync = FALSE;
4149         
4150         folder_func_to_all_folders(folder_item_want_synchronise_func, want_sync_data);
4151         result = want_sync_data->want_sync;
4152         g_free(want_sync_data);
4153         if (result > 0)
4154                 debug_print("Folder %s wants sync\n", folder->name);
4155         return result;
4156 }
4157
4158 void folder_item_set_batch (FolderItem *item, gboolean batch)
4159 {
4160         if (item->folder->klass->set_batch) {
4161                 item->folder->klass->set_batch(item->folder, item, batch);
4162         }
4163 }
4164
4165 gboolean folder_has_parent_of_type(FolderItem *item, 
4166                                           SpecialFolderItemType type) 
4167 {
4168         FolderItem *cur = item;
4169
4170         /* if we already know it, make it short */
4171         if (item->parent_stype != -1) {
4172                 return (item->parent_stype == type);
4173         }
4174         
4175         /* if we don't, find the type from the first possible parent,
4176          * and set our parent type to be faster next time */
4177         while (cur) {
4178                 if (cur->stype == type || cur->parent_stype == type) {
4179                         item->parent_stype = type;
4180                         return TRUE;
4181                 }
4182                 cur = folder_item_parent(cur);
4183         }
4184         
4185         /* if we didn't match what was asked, we didn't return. If our
4186         &n