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