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