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