No need to set window's position twice
[claws.git] / src / folder.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2016 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 #ifdef HAVE_CONFIG_H
20 #  include "config.h"
21 #include "claws-features.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <unistd.h>
33 #include <stdlib.h>
34 #ifdef WIN32
35 #include <w32lib.h>
36 #endif
37
38 #include "alertpanel.h"
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                                         xml_free_tree(node);
145                                 }
146                                 cur = NULL;
147                                 continue;
148                         }
149                 }
150         }
151         g_slist_free(xmllist);
152 }
153
154 void folder_unregister_class(FolderClass *klass)
155 {
156         GList *folderlist, *cur;
157
158         debug_print("unregistering folder class %s\n", klass->idstr);
159
160         class_list = g_slist_remove(class_list, klass);
161
162         folderlist = g_list_copy(folder_get_list());
163         for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
164                 Folder *folder = (Folder *) cur->data;
165
166                 if (folder->klass == klass) {
167                         GNode *xmlnode = folder_get_xml_node(folder);
168                         folder_unloaded_list = g_slist_append(folder_unloaded_list, xmlnode);
169                         folder_destroy(folder);
170                 }
171         }
172         g_list_free(folderlist);
173
174         if (klass->prefs_pages)
175                 g_slist_free(klass->prefs_pages);
176 }
177
178 Folder *folder_new(FolderClass *klass, const gchar *name, const gchar *path)
179 {
180         Folder *folder = NULL;
181         FolderItem *item;
182
183         cm_return_val_if_fail(klass != NULL, NULL);
184
185         name = name ? name : path;
186         folder = klass->new_folder(name, path);
187
188         /* Create root folder item */
189         item = folder_item_new(folder, name, NULL);
190         if (item == NULL) {
191                 return NULL;
192         }
193         item->folder = folder;
194         folder->node = item->node;
195         folder->data = NULL;
196
197         return folder;
198 }
199
200 void folder_init(Folder *folder, const gchar *name)
201 {
202         cm_return_if_fail(folder != NULL);
203
204         folder_set_name(folder, name);
205
206         /* Init folder data */
207         folder->account = NULL;
208         folder->sort = 0;
209         folder->inbox = NULL;
210         folder->outbox = NULL;
211         folder->draft = NULL;
212         folder->queue = NULL;
213         folder->trash = NULL;
214 }
215
216 static void reset_parent_type(FolderItem *item, gpointer data) {
217         item->parent_stype = -1;
218 }
219
220 void folder_item_change_type(FolderItem *item, SpecialFolderItemType newtype)
221 {
222         Folder *folder = NULL;
223         FolderUpdateData hookdata;
224
225         if (item == NULL)
226                 return;
227
228         folder = item->folder;
229         /* unset previous root of newtype */
230         switch(newtype) {
231         case F_INBOX:
232                 folder_item_change_type(folder->inbox, F_NORMAL);
233                 folder->inbox = item;
234                 break;
235         case F_OUTBOX:
236                 folder_item_change_type(folder->outbox, F_NORMAL);
237                 folder->outbox = item;
238                 break;
239         case F_QUEUE:
240                 folder_item_change_type(folder->queue, F_NORMAL);
241                 folder->queue = item;
242                 break;
243         case F_DRAFT:
244                 folder_item_change_type(folder->draft, F_NORMAL);
245                 folder->draft = item;
246                 break;
247         case F_TRASH:
248                 folder_item_change_type(folder->trash, F_NORMAL);
249                 folder->trash = item;
250                 break;
251         case F_NORMAL:
252         default:
253                 break;
254         }
255         /* set new type for current folder and sons */
256         item->stype = newtype;
257         folder_func_to_all_folders(reset_parent_type, NULL);
258         
259         hookdata.folder = folder;
260         hookdata.update_flags = FOLDER_TREE_CHANGED;
261         hookdata.item = NULL;
262         hookdata.item2 = NULL;
263         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
264 }
265
266 void folder_destroy(Folder *folder)
267 {
268         cm_return_if_fail(folder != NULL);
269         cm_return_if_fail(folder->klass->destroy_folder != NULL);
270
271         folder_remove(folder);
272
273         folder_tree_destroy(folder);
274
275         folder->klass->destroy_folder(folder);
276
277         g_free(folder->name);
278         g_free(folder);
279 }
280
281 void folder_set_xml(Folder *folder, XMLTag *tag)
282 {
283         GList *cur;
284         FolderItem *rootitem = NULL;
285
286         if ((folder->node != NULL) && (folder->node->data != NULL))
287                 rootitem = (FolderItem *) folder->node->data;
288
289         for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
290                 XMLAttr *attr = (XMLAttr *) cur->data;
291
292                 if (!attr || !attr->name || !attr->value) continue;
293                 if (!strcmp(attr->name, "name")) {
294                         g_free(folder->name);
295                         folder->name = g_strdup(attr->value);
296                         if (rootitem != NULL) {
297                                 g_free(rootitem->name);
298                                 rootitem->name = g_strdup(attr->value);
299                         }
300                 } else if (!strcmp(attr->name, "account_id")) {
301                         PrefsAccount *account;
302
303                         account = account_find_from_id(atoi(attr->value));
304                         if (!account)
305                                 g_warning("account_id: %s not found", attr->value);
306                         else {
307                                 folder->account = account;
308                                 account->folder = folder;
309                         }
310                 } else if (!strcmp(attr->name, "collapsed")) {
311                         if (rootitem != NULL)
312                                 rootitem->collapsed = *attr->value == '1' ? TRUE : FALSE;
313                 } else if (!strcmp(attr->name, "sort")) {
314                         folder->sort = atoi(attr->value);
315                 }
316         }
317 }
318
319 XMLTag *folder_get_xml(Folder *folder)
320 {
321         XMLTag *tag;
322
323         tag = xml_tag_new("folder");
324
325         if (folder->name)
326                 xml_tag_add_attr(tag, xml_attr_new("name", folder->name));
327         if (folder->account)
328                 xml_tag_add_attr(tag, xml_attr_new_int("account_id", folder->account->account_id));
329         if (folder->node && folder->node->data) {
330                 FolderItem *rootitem = (FolderItem *) folder->node->data;
331
332                 xml_tag_add_attr(tag, xml_attr_new("collapsed", rootitem->collapsed ? "1" : "0"));
333         }
334         xml_tag_add_attr(tag, xml_attr_new_int("sort", folder->sort));
335
336         return tag;
337 }
338
339 FolderItem *folder_item_new(Folder *folder, const gchar *name, const gchar *path)
340 {
341         FolderItem *item = NULL;
342
343         cm_return_val_if_fail(folder != NULL, NULL);
344
345         if (folder->klass->item_new) {
346                 item = folder->klass->item_new(folder);
347         } else {
348                 item = g_new0(FolderItem, 1);
349         }
350
351         cm_return_val_if_fail(item != NULL, NULL);
352
353         item->stype = F_NORMAL;
354
355         if(!g_utf8_validate(name, -1, NULL)) {
356                 item->name = g_malloc(strlen(name)*2+1);
357                 conv_localetodisp(item->name, strlen(name)*2+1, name);
358         } else {
359                 item->name = g_strdup(name);
360         }
361
362         item->path = g_strdup(path);
363         item->mtime = 0;
364         item->new_msgs = 0;
365         item->unread_msgs = 0;
366         item->unreadmarked_msgs = 0;
367         item->marked_msgs = 0;
368         item->total_msgs = 0;
369         item->replied_msgs = 0;
370         item->forwarded_msgs = 0;
371         item->locked_msgs = 0;
372         item->ignored_msgs = 0;
373         item->watched_msgs = 0;
374         item->order = 0;
375         item->last_num = -1;
376         item->cache = NULL;
377         item->no_sub = FALSE;
378         item->no_select = FALSE;
379         item->collapsed = FALSE;
380         item->thread_collapsed = FALSE;
381         item->threaded  = TRUE;
382         item->ret_rcpt  = FALSE;
383         item->opened    = FALSE;
384         item->node = g_node_new(item);
385         item->folder = NULL;
386         item->account = NULL;
387         item->apply_sub = FALSE;
388         item->mark_queue = NULL;
389         item->data = NULL;
390         item->parent_stype = -1;
391
392         item->sort_key = prefs_common.default_sort_key;
393         item->sort_type = prefs_common.default_sort_type;
394
395         item->prefs = folder_item_prefs_new();
396
397         return item;
398 }
399
400 void folder_item_append(FolderItem *parent, FolderItem *item)
401 {
402         cm_return_if_fail(parent != NULL);
403         cm_return_if_fail(parent->folder != NULL);
404         cm_return_if_fail(parent->node != NULL);
405         cm_return_if_fail(item != NULL);
406
407         item->folder = parent->folder;
408         g_node_append(parent->node, item->node);
409 }
410
411 void folder_item_remove(FolderItem *item)
412 {
413         GNode *node, *start_node;
414         FolderUpdateData hookdata;
415         gchar *tags_file = NULL, *tags_dir = NULL;
416
417         cm_return_if_fail(item != NULL);
418         cm_return_if_fail(item->folder != NULL);
419         cm_return_if_fail(item->folder->node != NULL);
420
421         start_node = item->node;
422         
423         node = item->folder->node;
424         
425         node = g_node_find(node, G_PRE_ORDER, G_TRAVERSE_ALL, item);
426         node = node->children;
427
428         /* remove my children */
429         while (node != NULL) {
430                 if (node && node->data) {
431                         FolderItem *sub_item = (FolderItem*) node->data;
432                         node = node->next;
433                         folder_item_remove(sub_item);
434                 }
435         }
436
437         /* remove myself */
438         if (item->cache != NULL) {
439                 msgcache_destroy(item->cache);
440                 item->cache = NULL;
441         }
442         tags_file = folder_item_get_tags_file(item);
443         if (tags_file)
444                 claws_unlink(tags_file);
445         tags_dir = g_path_get_dirname(tags_file);
446         if (tags_dir)
447                 rmdir(tags_dir);
448
449         g_free(tags_file);
450         g_free(tags_dir);
451
452         hookdata.folder = item->folder;
453         hookdata.update_flags = FOLDER_TREE_CHANGED | FOLDER_REMOVE_FOLDERITEM;
454         hookdata.item = item;
455         hookdata.item2 = NULL;
456         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
457
458         node = start_node;
459
460         if (item->folder->node == node)
461                 item->folder->node = NULL;
462
463         folder_item_destroy(item);
464
465         g_node_destroy(node);
466 }
467
468 void folder_item_remove_children(FolderItem *item)
469 {
470         GNode *node, *next;
471
472         cm_return_if_fail(item != NULL);
473         cm_return_if_fail(item->folder != NULL);
474         cm_return_if_fail(item->node != NULL);
475
476         node = item->node->children;
477         while (node != NULL) {
478                 next = node->next;
479                 folder_item_remove(FOLDER_ITEM(node->data));
480                 node = next;
481         }
482 }
483
484 void folder_item_destroy(FolderItem *item)
485 {
486         Folder *folder;
487
488         cm_return_if_fail(item != NULL);
489
490         folder = item->folder;
491         if (folder) {
492                 if (folder->inbox == item)
493                         folder->inbox = NULL;
494                 else if (folder->outbox == item)
495                         folder->outbox = NULL;
496                 else if (folder->draft == item)
497                         folder->draft = NULL;
498                 else if (folder->queue == item)
499                         folder->queue = NULL;
500                 else if (folder->trash == item)
501                         folder->trash = NULL;
502         }
503
504         if (item->cache)
505                 folder_item_free_cache(item, TRUE);
506         if (item->prefs)
507                 folder_item_prefs_free(item->prefs);
508         g_free(item->name);
509         g_free(item->path);
510
511         if (item->folder != NULL) {
512                 if(item->folder->klass->item_destroy) {
513                         item->folder->klass->item_destroy(item->folder, item);
514                 } else {
515                         g_free(item);
516                 }
517         }
518 }
519
520 FolderItem *folder_item_parent(FolderItem *item)
521 {
522         cm_return_val_if_fail(item != NULL, NULL);
523         cm_return_val_if_fail(item->node != NULL, NULL);
524
525         if (item->node->parent == NULL)
526                 return NULL;
527         return (FolderItem *) item->node->parent->data;
528 }
529
530 void folder_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
531 {
532         GList *cur;
533
534         for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
535                 XMLAttr *attr = (XMLAttr *) cur->data;
536
537                 if (!attr || !attr->name || !attr->value) continue;
538                 if (!strcmp(attr->name, "type")) {
539                         if (!g_ascii_strcasecmp(attr->value, "normal"))
540                                 item->stype = F_NORMAL;
541                         else if (!g_ascii_strcasecmp(attr->value, "inbox"))
542                                 item->stype = F_INBOX;
543                         else if (!g_ascii_strcasecmp(attr->value, "outbox"))
544                                 item->stype = F_OUTBOX;
545                         else if (!g_ascii_strcasecmp(attr->value, "draft"))
546                                 item->stype = F_DRAFT;
547                         else if (!g_ascii_strcasecmp(attr->value, "queue"))
548                                 item->stype = F_QUEUE;
549                         else if (!g_ascii_strcasecmp(attr->value, "trash"))
550                                 item->stype = F_TRASH;
551                 } else if (!strcmp(attr->name, "name")) {
552                         g_free(item->name);
553                         item->name = g_strdup(attr->value);
554                 } else if (!strcmp(attr->name, "path")) {
555                         g_free(item->path);
556                         item->path = g_strdup(attr->value);
557                 } else if (!strcmp(attr->name, "mtime"))
558                         item->mtime = strtoul(attr->value, NULL, 10);
559                 else if (!strcmp(attr->name, "new"))
560                         item->new_msgs = atoi(attr->value);
561                 else if (!strcmp(attr->name, "unread"))
562                         item->unread_msgs = atoi(attr->value);
563                 else if (!strcmp(attr->name, "unreadmarked"))
564                         item->unreadmarked_msgs = atoi(attr->value);
565                 else if (!strcmp(attr->name, "marked"))
566                         item->marked_msgs = atoi(attr->value);
567                 else if (!strcmp(attr->name, "replied"))
568                         item->replied_msgs = atoi(attr->value);
569                 else if (!strcmp(attr->name, "forwarded"))
570                         item->forwarded_msgs = atoi(attr->value);
571                 else if (!strcmp(attr->name, "locked"))
572                         item->locked_msgs = atoi(attr->value);
573                 else if (!strcmp(attr->name, "ignored"))
574                         item->ignored_msgs = atoi(attr->value);
575                 else if (!strcmp(attr->name, "watched"))
576                         item->watched_msgs = atoi(attr->value);
577                 else if (!strcmp(attr->name, "order"))
578                         item->order = atoi(attr->value);
579                 else if (!strcmp(attr->name, "total"))
580                         item->total_msgs = atoi(attr->value);
581                 else if (!strcmp(attr->name, "no_sub"))
582                         item->no_sub = *attr->value == '1' ? TRUE : FALSE;
583                 else if (!strcmp(attr->name, "no_select"))
584                         item->no_select = *attr->value == '1' ? TRUE : FALSE;
585                 else if (!strcmp(attr->name, "collapsed"))
586                         item->collapsed = *attr->value == '1' ? TRUE : FALSE;
587                 else if (!strcmp(attr->name, "thread_collapsed"))
588                         item->thread_collapsed =  *attr->value == '1' ? TRUE : FALSE;
589                 else if (!strcmp(attr->name, "threaded"))
590                         item->threaded =  *attr->value == '1' ? TRUE : FALSE;
591                 else if (!strcmp(attr->name, "hidereadmsgs"))
592                         item->hide_read_msgs =  *attr->value == '1' ? TRUE : FALSE;
593                 else if (!strcmp(attr->name, "hidedelmsgs"))
594                         item->hide_del_msgs =  *attr->value == '1' ? TRUE : FALSE;
595                 else if (!strcmp(attr->name, "hidereadthreads"))
596                         item->hide_read_threads =  *attr->value == '1' ? TRUE : FALSE;
597                 else if (!strcmp(attr->name, "reqretrcpt"))
598                         item->ret_rcpt =  *attr->value == '1' ? TRUE : FALSE;
599                 else if (!strcmp(attr->name, "sort_key")) {
600                         if (!strcmp(attr->value, "none"))
601                                 item->sort_key = SORT_BY_NONE;
602                         else if (!strcmp(attr->value, "number"))
603                                 item->sort_key = SORT_BY_NUMBER;
604                         else if (!strcmp(attr->value, "size"))
605                                 item->sort_key = SORT_BY_SIZE;
606                         else if (!strcmp(attr->value, "date"))
607                                 item->sort_key = SORT_BY_DATE;
608                         else if (!strcmp(attr->value, "from"))
609                                 item->sort_key = SORT_BY_FROM;
610                         else if (!strcmp(attr->value, "subject"))
611                                 item->sort_key = SORT_BY_SUBJECT;
612                         else if (!strcmp(attr->value, "score"))
613                                 item->sort_key = SORT_BY_SCORE;
614                         else if (!strcmp(attr->value, "label"))
615                                 item->sort_key = SORT_BY_LABEL;
616                         else if (!strcmp(attr->value, "mark"))
617                                 item->sort_key = SORT_BY_MARK;
618                         else if (!strcmp(attr->value, "unread"))
619                                 item->sort_key = SORT_BY_STATUS;
620                         else if (!strcmp(attr->value, "mime"))
621                                 item->sort_key = SORT_BY_MIME;
622                         else if (!strcmp(attr->value, "to"))
623                                 item->sort_key = SORT_BY_TO;
624                         else if (!strcmp(attr->value, "locked"))
625                                 item->sort_key = SORT_BY_LOCKED;
626                         else if (!strcmp(attr->value, "tags"))
627                                 item->sort_key = SORT_BY_TAGS;
628                         else if (!strcmp(attr->value, "thread_date"))
629                                 item->sort_key = SORT_BY_THREAD_DATE;
630                 } else if (!strcmp(attr->name, "sort_type")) {
631                         if (!strcmp(attr->value, "ascending"))
632                                 item->sort_type = SORT_ASCENDING;
633                         else
634                                 item->sort_type = SORT_DESCENDING;
635                 } else if (!strcmp(attr->name, "account_id")) {
636                         PrefsAccount *account;
637
638                         account = account_find_from_id(atoi(attr->value));
639                         if (!account)
640                                 g_warning("account_id: %s not found", attr->value);
641                         else
642                                 item->account = account;
643                 } else if (!strcmp(attr->name, "apply_sub")) {
644                         item->apply_sub = *attr->value == '1' ? TRUE : FALSE;
645                 } else if (!strcmp(attr->name, "last_seen")) {
646                         if (!claws_crashed())
647                                 item->last_seen = atoi(attr->value);
648                         else
649                                 item->last_seen = 0;
650                 }
651         }
652         /* options without meaning in drafts */
653         if (item->stype == F_DRAFT)
654                 item->hide_read_msgs =
655                         item->hide_del_msgs =
656                                 item->hide_read_threads = FALSE;
657 }
658
659 XMLTag *folder_item_get_xml(Folder *folder, FolderItem *item)
660 {
661         static gchar *folder_item_stype_str[] = {"normal", "inbox", "outbox",
662                                                  "draft", "queue", "trash"};
663         static gchar *sort_key_str[] = {"none", "number", "size", "date",
664                                         "from", "subject", "score", "label",
665                                         "mark", "unread", "mime", "to", 
666                                         "locked", "tags", "thread_date" };
667         XMLTag *tag;
668         gchar *value;
669
670         tag = xml_tag_new("folderitem");
671
672         xml_tag_add_attr(tag, xml_attr_new("type", folder_item_stype_str[item->stype]));
673         if (item->name)
674                 xml_tag_add_attr(tag, xml_attr_new("name", item->name));
675         if (item->path)
676                 xml_tag_add_attr(tag, xml_attr_new("path", item->path));
677         if (item->no_sub)
678                 xml_tag_add_attr(tag, xml_attr_new("no_sub", "1"));
679         if (item->no_select)
680                 xml_tag_add_attr(tag, xml_attr_new("no_select", "1"));
681         xml_tag_add_attr(tag, xml_attr_new("collapsed", item->collapsed && item->node->children ? "1" : "0"));
682         xml_tag_add_attr(tag, xml_attr_new("thread_collapsed", item->thread_collapsed ? "1" : "0"));
683         xml_tag_add_attr(tag, xml_attr_new("threaded", item->threaded ? "1" : "0"));
684         xml_tag_add_attr(tag, xml_attr_new("hidereadmsgs", item->hide_read_msgs ? "1" : "0"));
685         xml_tag_add_attr(tag, xml_attr_new("hidedelmsgs", item->hide_del_msgs ? "1" : "0"));
686         xml_tag_add_attr(tag, xml_attr_new("hidereadthreads", item->hide_read_threads ? "1" : "0"));
687         if (item->ret_rcpt)
688                 xml_tag_add_attr(tag, xml_attr_new("reqretrcpt", "1"));
689
690         if (item->sort_key != SORT_BY_NONE) {
691                 xml_tag_add_attr(tag, xml_attr_new("sort_key", sort_key_str[item->sort_key]));
692                 xml_tag_add_attr(tag, xml_attr_new("sort_type", item->sort_type == SORT_ASCENDING ? "ascending" : "descending"));
693         }
694
695         value = g_strdup_printf("%ld", (unsigned long int) item->mtime);
696         xml_tag_add_attr(tag, xml_attr_new("mtime", value));
697         g_free(value);
698         xml_tag_add_attr(tag, xml_attr_new_int("new", item->new_msgs));
699         xml_tag_add_attr(tag, xml_attr_new_int("unread", item->unread_msgs));
700         xml_tag_add_attr(tag, xml_attr_new_int("unreadmarked", item->unreadmarked_msgs));
701         xml_tag_add_attr(tag, xml_attr_new_int("marked", item->marked_msgs));
702         xml_tag_add_attr(tag, xml_attr_new_int("total", item->total_msgs));
703         xml_tag_add_attr(tag, xml_attr_new_int("replied", item->replied_msgs));
704         xml_tag_add_attr(tag, xml_attr_new_int("forwarded", item->forwarded_msgs));
705         xml_tag_add_attr(tag, xml_attr_new_int("locked", item->locked_msgs));
706         xml_tag_add_attr(tag, xml_attr_new_int("ignore", item->ignored_msgs));
707         xml_tag_add_attr(tag, xml_attr_new_int("watched", item->watched_msgs));
708         xml_tag_add_attr(tag, xml_attr_new_int("order", item->order));
709
710         if (item->account)
711                 xml_tag_add_attr(tag, xml_attr_new_int("account_id", item->account->account_id));
712         if (item->apply_sub)
713                 xml_tag_add_attr(tag, xml_attr_new("apply_sub", "1"));
714
715         xml_tag_add_attr(tag, xml_attr_new_int("last_seen", item->last_seen));
716
717         return tag;
718 }
719
720 void folder_set_ui_func(Folder *folder, FolderUIFunc func, gpointer data)
721 {
722         cm_return_if_fail(folder != NULL);
723
724         folder->ui_func = func;
725         folder->ui_func_data = data;
726 }
727
728 void folder_set_name(Folder *folder, const gchar *name)
729 {
730         cm_return_if_fail(folder != NULL);
731
732         g_free(folder->name);
733         folder->name = name ? g_strdup(name) : NULL;
734         if (folder->node && folder->node->data) {
735                 FolderItem *item = (FolderItem *)folder->node->data;
736
737                 g_free(item->name);
738                 item->name = name ? g_strdup(name) : NULL;
739         }
740 }
741
742 void folder_set_sort(Folder *folder, guint sort)
743 {
744         cm_return_if_fail(folder != NULL);
745
746         if (folder->sort != sort) {
747                 folder_remove(folder);
748                 folder->sort = sort;
749                 folder_add(folder);
750         }
751 }
752
753 static gboolean folder_tree_destroy_func(GNode *node, gpointer data) {
754         FolderItem *item = (FolderItem *) node->data;
755
756         folder_item_destroy(item);
757         return FALSE;
758 }
759
760 void folder_tree_destroy(Folder *folder)
761 {
762         GNode *node;
763
764         cm_return_if_fail(folder != NULL);
765
766         node = folder->node;
767         
768         prefs_filtering_clear_folder(folder);
769
770         if (node != NULL) {
771                 g_node_traverse(node, G_POST_ORDER, G_TRAVERSE_ALL, -1,
772                                 folder_tree_destroy_func, NULL);
773                 g_node_destroy(node);
774                 folder->node = NULL;
775         }
776 }
777
778 void folder_add(Folder *folder)
779 {
780         Folder *cur_folder;
781         GList *cur;
782         gint i;
783         FolderUpdateData hookdata;
784
785         cm_return_if_fail(folder != NULL);
786
787         if ((FOLDER_TYPE(folder) == F_IMAP ||
788              FOLDER_TYPE(folder) == F_NEWS) &&
789             folder->account == NULL) {
790                 return;
791         }
792
793         for (i = 0, cur = folder_list; cur != NULL; cur = cur->next, i++) {
794                 cur_folder = FOLDER(cur->data);
795                 if (cur_folder->sort < folder->sort)
796                         break;
797         }
798
799         folder_list = g_list_insert(folder_list, folder, i);
800
801         hookdata.folder = folder;
802         hookdata.update_flags = FOLDER_ADD_FOLDER;
803         hookdata.item = NULL;
804         hookdata.item2 = NULL;
805         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
806 }
807
808 void folder_remove(Folder *folder)
809 {
810         FolderUpdateData hookdata;
811
812         cm_return_if_fail(folder != NULL);
813
814         folder_list = g_list_remove(folder_list, folder);
815
816         hookdata.folder = folder;
817         hookdata.update_flags = FOLDER_REMOVE_FOLDER;
818         hookdata.item = NULL;
819         hookdata.item2 = NULL;
820         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
821 }
822
823 GList *folder_get_list(void)
824 {
825         return folder_list;
826 }
827
828 gint folder_read_list(void)
829 {
830         GNode *node, *cur;
831         XMLNode *xmlnode;
832         gchar *path;
833
834         path = folder_get_list_path();
835         if (!is_file_exist(path)) return -1;
836         node = xml_parse_file(path);
837         if (!node) return -1;
838
839         xmlnode = node->data;
840         if (strcmp2(xmlnode->tag->tag, "folderlist") != 0) {
841                 g_warning("wrong folder list");
842                 xml_free_tree(node);
843                 return -1;
844         }
845
846         cur = node->children;
847         while (cur != NULL) {
848                 Folder *folder;
849
850                 folder = folder_get_from_xml(cur);
851                 if (folder != NULL)
852                         folder_add(folder);
853                 else
854                         folder_unloaded_list = g_slist_append(folder_unloaded_list,
855                                 (gpointer) xml_copy_tree(cur));
856                 cur = cur->next;
857         }
858
859         xml_free_tree(node);
860         if (folder_list || folder_unloaded_list)
861                 return 0;
862         else
863                 return -1;
864 }
865
866 void folder_write_list(void)
867 {
868         GList *list;
869         GSList *slist;
870         Folder *folder;
871         gchar *path;
872         PrefFile *pfile;
873         GNode *rootnode;
874         XMLNode *xmlnode;
875         XMLTag *tag;
876
877         path = folder_get_list_path();
878         if ((pfile = prefs_write_open(path)) == NULL) return;
879
880         if (xml_file_put_xml_decl(pfile->fp) < 0) {
881                 prefs_file_close_revert(pfile);
882                 g_warning("failed to start write folder list.");
883                 return;         
884         }
885         tag = xml_tag_new("folderlist");
886
887         xmlnode = xml_node_new(tag, NULL);
888
889         rootnode = g_node_new(xmlnode);
890
891         for (list = folder_list; list != NULL; list = list->next) {
892                 GNode *node;
893
894                 folder = list->data;
895                 node = folder_get_xml_node(folder);
896                 if (node != NULL)
897                         g_node_append(rootnode, node);
898         }
899
900         for (slist = folder_unloaded_list; slist != NULL; slist = g_slist_next(slist)) {
901                 GNode *node = (GNode *) slist->data;
902
903                 g_node_append(rootnode, (gpointer) xml_copy_tree(node));
904         }
905
906         if (xml_write_tree(rootnode, pfile->fp) < 0) {
907                 prefs_file_close_revert(pfile);
908                 g_warning("failed to write folder list.");
909         } else if (prefs_file_close(pfile) < 0) {
910                 g_warning("failed to write folder list.");
911         }
912         xml_free_tree(rootnode);
913 }
914
915 static gboolean folder_scan_tree_func(GNode *node, gpointer data)
916 {
917         GHashTable *pptable = (GHashTable *)data;
918         FolderItem *item = (FolderItem *)node->data;
919
920         folder_item_restore_persist_prefs(item, pptable);
921         folder_item_scan_full(item, FALSE);
922
923         return FALSE;
924 }
925
926 static gboolean folder_restore_prefs_func(GNode *node, gpointer data)
927 {
928         GHashTable *pptable = (GHashTable *)data;
929         FolderItem *item = (FolderItem *)node->data;
930
931         folder_item_restore_persist_prefs(item, pptable);
932
933         return FALSE;
934 }
935
936 void folder_scan_tree(Folder *folder, gboolean rebuild)
937 {
938         GHashTable *pptable;
939         FolderUpdateData hookdata;
940         Folder *old_folder = folder;
941
942         if (!folder->klass->scan_tree)
943                 return;
944         
945         pptable = folder_persist_prefs_new(folder);
946
947         if (rebuild)
948                 folder_remove(folder);
949
950         if (folder->klass->scan_tree(folder) < 0) {
951                 if (rebuild)
952                         folder_add(old_folder);
953                 return;
954         } else if (rebuild)
955                 folder_add(folder);
956
957         hookdata.folder = folder;
958         hookdata.update_flags = FOLDER_TREE_CHANGED;
959         hookdata.item = NULL;
960         hookdata.item2 = NULL;
961         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
962
963         if (rebuild)
964                 g_node_traverse(folder->node, G_POST_ORDER, G_TRAVERSE_ALL, -1, folder_scan_tree_func, pptable);
965         else
966                 g_node_traverse(folder->node, G_POST_ORDER, G_TRAVERSE_ALL, -1, folder_restore_prefs_func, pptable);
967
968         folder_persist_prefs_free(pptable);
969
970         prefs_matcher_read_config();
971
972         folder_write_list();
973 }
974
975 FolderItem *folder_create_folder(FolderItem *parent, const gchar *name)
976 {
977         FolderItem *new_item;
978         
979         cm_return_val_if_fail(parent != NULL, NULL);
980
981         new_item = parent->folder->klass->create_folder(parent->folder, parent, name);
982         if (new_item) {
983                 FolderUpdateData hookdata;
984
985                 new_item->cache = msgcache_new();
986                 new_item->cache_dirty = TRUE;
987                 new_item->mark_dirty = TRUE;
988                 new_item->tags_dirty = TRUE;
989
990                 hookdata.folder = new_item->folder;
991                 hookdata.update_flags = FOLDER_TREE_CHANGED | FOLDER_ADD_FOLDERITEM;
992                 hookdata.item = new_item;
993                 hookdata.item2 = NULL;
994                 hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
995         }
996
997         return new_item;
998 }
999
1000 gint folder_item_rename(FolderItem *item, gchar *newname)
1001 {
1002         gint retval;
1003
1004         cm_return_val_if_fail(item != NULL, -1);
1005         cm_return_val_if_fail(newname != NULL, -1);
1006
1007         retval = item->folder->klass->rename_folder(item->folder, item, newname);
1008
1009         if (retval >= 0) {
1010                 FolderItemUpdateData hookdata;
1011                 FolderUpdateData hookdata2;
1012
1013                 hookdata.item = item;
1014                 hookdata.update_flags = F_ITEM_UPDATE_NAME;
1015                 hookdata.msg = NULL;
1016                 hooks_invoke(FOLDER_ITEM_UPDATE_HOOKLIST, &hookdata);
1017
1018                 hookdata2.folder = item->folder;
1019                 hookdata2.item = item;
1020                 hookdata2.item2 = NULL;
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.",
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         
1993         g_slist_free(msglist);
1994
1995         item->scanning = ITEM_NOT_SCANNING;
1996
1997         return ret;
1998 }
1999
2000 static void folder_item_process_open (FolderItem *item,
2001                                  void (*before_proc_func)(gpointer data),
2002                                  void (*after_proc_func)(gpointer data),
2003                                  gpointer data)
2004 {
2005         gchar *buf;
2006         if (item == NULL)
2007                 return;
2008         if((item->folder->klass->scan_required != NULL) &&
2009            (item->folder->klass->scan_required(item->folder, item))) {
2010                 folder_item_scan_full(item, TRUE);
2011         } else {
2012                 folder_item_syncronize_flags(item);
2013         }
2014         
2015         /* Processing */
2016         if (item->prefs->enable_processing_when_opening) {
2017                 buf = g_strdup_printf(_("Processing (%s)...\n"), 
2018                               item->path ? item->path : item->name);
2019                 g_free(buf);
2020
2021                 if (before_proc_func)
2022                         before_proc_func(data);
2023
2024                 folder_item_apply_processing(item);
2025
2026                 if (after_proc_func)
2027                         after_proc_func(data);
2028         }
2029         item->processing_pending = FALSE;
2030         return; 
2031 }
2032
2033 gint folder_item_open(FolderItem *item)
2034 {
2035         START_TIMING(""); 
2036         if (item->no_select)
2037                 return -1;
2038
2039         if (item->scanning != ITEM_NOT_SCANNING) {
2040                 debug_print("%s is scanning... \n", item->path ? item->path : item->name);
2041                 return -2;
2042         }
2043
2044         item->processing_pending = TRUE;
2045         folder_item_process_open (item, NULL, NULL, NULL);
2046         
2047         item->opened = TRUE;
2048         END_TIMING();
2049         return 0;
2050 }
2051
2052 gint folder_item_close(FolderItem *item)
2053 {
2054         GSList *mlist, *cur;
2055         Folder *folder;
2056         
2057         cm_return_val_if_fail(item != NULL, -1);
2058
2059         if (item->no_select)
2060                 return -1;
2061
2062         if (item->new_msgs) {
2063                 folder_item_update_freeze();
2064                 mlist = folder_item_get_msg_list(item);
2065                 for (cur = mlist ; cur != NULL ; cur = cur->next) {
2066                         MsgInfo * msginfo;
2067
2068                         msginfo = (MsgInfo *) cur->data;
2069                         if (MSG_IS_NEW(msginfo->flags))
2070                                 procmsg_msginfo_unset_flags(msginfo, MSG_NEW, 0);
2071                         procmsg_msginfo_free(&msginfo);
2072                 }
2073                 g_slist_free(mlist);
2074                 folder_item_update_thaw();
2075         }               
2076
2077         folder_item_write_cache(item);
2078         
2079         folder_item_update(item, F_ITEM_UPDATE_MSGCNT);
2080
2081         item->opened = FALSE;
2082         folder = item->folder;
2083
2084         if (folder->klass->close == NULL)
2085                 return 0;
2086
2087         return folder->klass->close(folder, item);
2088 }
2089
2090 static MsgInfoList *get_msginfos(FolderItem *item, MsgNumberList *numlist)
2091 {
2092         MsgInfoList *msglist = NULL;
2093         Folder *folder = item->folder;
2094         if (item->no_select)
2095                 return NULL;
2096         
2097         if (folder->klass->get_msginfos != NULL)
2098                 msglist = folder->klass->get_msginfos(folder, item, numlist);
2099         else {
2100                 MsgNumberList *elem;
2101
2102                 for (elem = numlist; elem != NULL; elem = g_slist_next(elem)) {
2103                         MsgInfo *msginfo;
2104                         guint num;
2105
2106                         num = GPOINTER_TO_INT(elem->data);
2107                         msginfo = folder->klass->get_msginfo(folder, item, num);
2108                         if (msginfo != NULL)
2109                                 msglist = g_slist_prepend(msglist, msginfo);
2110                 }               
2111         }
2112
2113         return msglist;
2114 }
2115
2116 static MsgInfo *get_msginfo(FolderItem *item, guint num)
2117 {
2118         MsgNumberList numlist;
2119         MsgInfoList *msglist;
2120         MsgInfo *msginfo = NULL;
2121
2122         numlist.data = GINT_TO_POINTER(num);
2123         numlist.next = NULL;
2124         msglist = get_msginfos(item, &numlist);
2125         if (msglist != NULL)
2126                 msginfo = procmsg_msginfo_new_ref(msglist->data);
2127         procmsg_msg_list_free(msglist);
2128
2129         return msginfo;
2130 }
2131
2132 gint folder_item_scan_full(FolderItem *item, gboolean filtering)
2133 {
2134         Folder *folder;
2135         GSList *folder_list = NULL, *cache_list = NULL;
2136         GSList *folder_list_cur, *cache_list_cur, *new_list = NULL;
2137         GSList *exists_list = NULL, *elem;
2138         GSList *newmsg_list = NULL;
2139         guint newcnt = 0, unreadcnt = 0, totalcnt = 0;
2140         guint markedcnt = 0, unreadmarkedcnt = 0;
2141         guint repliedcnt = 0, forwardedcnt = 0;
2142         guint lockedcnt = 0, ignoredcnt = 0, watchedcnt = 0;
2143
2144         guint cache_max_num, folder_max_num, cache_cur_num, folder_cur_num;
2145         gboolean update_flags = 0, old_uids_valid = FALSE;
2146         GHashTable *subject_table = NULL;
2147         
2148         cm_return_val_if_fail(item != NULL, -1);
2149         if (item->path == NULL) return -1;
2150
2151         folder = item->folder;
2152
2153         cm_return_val_if_fail(folder != NULL, -1);
2154         cm_return_val_if_fail(folder->klass->get_num_list != NULL, -1);
2155
2156         item->scanning = ITEM_SCANNING_WITH_FLAGS;
2157
2158         debug_print("Scanning folder %s for cache changes.\n", item->path ? item->path : "(null)");
2159         
2160         /* Get list of messages for folder and cache */
2161         if (folder->klass->get_num_list(item->folder, item, &folder_list, &old_uids_valid) < 0) {
2162                 debug_print("Error fetching list of message numbers\n");
2163                 item->scanning = ITEM_NOT_SCANNING;
2164                 return(-1);
2165         }
2166
2167         if(prefs_common.thread_by_subject) {
2168                 subject_table = g_hash_table_new(g_str_hash, g_str_equal);
2169         }
2170         
2171         if (old_uids_valid) {
2172                 if (!item->cache)
2173                         folder_item_read_cache(item);
2174                 cache_list = msgcache_get_msg_list(item->cache);
2175         } else {
2176                 if (item->cache)
2177                         msgcache_destroy(item->cache);
2178                 item->cache = msgcache_new();
2179                 item->cache_dirty = TRUE;
2180                 item->mark_dirty = TRUE;
2181                 item->tags_dirty = TRUE;
2182                 cache_list = NULL;
2183         }
2184
2185         /* Sort both lists */
2186         cache_list = g_slist_sort(cache_list, folder_sort_cache_list_by_msgnum);
2187         folder_list = g_slist_sort(folder_list, folder_sort_folder_list);
2188
2189         cache_list_cur = cache_list;
2190         folder_list_cur = folder_list;
2191
2192         if (cache_list_cur != NULL) {
2193                 GSList *cache_list_last;
2194         
2195                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
2196                 cache_list_last = g_slist_last(cache_list);
2197                 cache_max_num = ((MsgInfo *)cache_list_last->data)->msgnum;
2198         } else {
2199                 cache_cur_num = G_MAXUINT;
2200                 cache_max_num = 0;
2201         }
2202
2203         if (folder_list_cur != NULL) {
2204                 GSList *folder_list_last;
2205         
2206                 folder_cur_num = GPOINTER_TO_UINT(folder_list_cur->data);
2207                 folder_list_last = g_slist_last(folder_list);
2208                 folder_max_num = GPOINTER_TO_UINT(folder_list_last->data);
2209         } else {
2210                 folder_cur_num = G_MAXUINT;
2211                 folder_max_num = 0;
2212         }
2213
2214         while ((cache_cur_num != G_MAXUINT) || (folder_cur_num != G_MAXUINT)) {
2215                 /*
2216                  *  Message only exists in the folder
2217                  *  Remember message for fetching
2218                  */
2219                 if (folder_cur_num < cache_cur_num) {
2220                         gboolean add = FALSE;
2221
2222                         switch(FOLDER_TYPE(folder)) {
2223                                 case F_NEWS:
2224                                         if (folder_cur_num < cache_max_num)
2225                                                 break;
2226                                         
2227                                         if (folder->account->max_articles == 0) {
2228                                                 add = TRUE;
2229                                         }
2230
2231                                         if (folder_max_num <= folder->account->max_articles) {
2232                                                 add = TRUE;
2233                                         } else if (folder_cur_num > (folder_max_num - folder->account->max_articles)) {
2234                                                 add = TRUE;
2235                                         }
2236                                         break;
2237                                 default:
2238                                         add = TRUE;
2239                                         break;
2240                         }
2241                         
2242                         if (add) {
2243                                 new_list = g_slist_prepend(new_list, GUINT_TO_POINTER(folder_cur_num));
2244                                 debug_print("Remembered message %u for fetching\n", folder_cur_num);
2245                         }
2246
2247                         /* Move to next folder number */
2248                         if (folder_list_cur)
2249                                 folder_list_cur = folder_list_cur->next;
2250
2251                         if (folder_list_cur != NULL)
2252                                 folder_cur_num = GPOINTER_TO_UINT(folder_list_cur->data);
2253                         else
2254                                 folder_cur_num = G_MAXUINT;
2255
2256                         continue;
2257                 }
2258
2259                 /*
2260                  *  Message only exists in the cache
2261                  *  Remove the message from the cache
2262                  */
2263                 if (cache_cur_num < folder_cur_num) {
2264                         msgcache_remove_msg(item->cache, cache_cur_num);
2265                         debug_print("Removed message %u from cache.\n", cache_cur_num);
2266
2267                         /* Move to next cache number */
2268                         if (cache_list_cur)
2269                                 cache_list_cur = cache_list_cur->next;
2270
2271                         if (cache_list_cur != NULL)
2272                                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
2273                         else
2274                                 cache_cur_num = G_MAXUINT;
2275
2276                         update_flags |= F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT;
2277
2278                         continue;
2279                 }
2280
2281                 /*
2282                  *  Message number exists in folder and cache!
2283                  *  Check if the message has been modified
2284                  */
2285                 if (cache_cur_num == folder_cur_num) {
2286                         MsgInfo *msginfo;
2287
2288                         msginfo = msgcache_get_msg(item->cache, folder_cur_num);
2289                         if (msginfo && folder->klass->is_msg_changed && folder->klass->is_msg_changed(folder, item, msginfo)) {
2290                                 msgcache_remove_msg(item->cache, msginfo->msgnum);
2291                                 new_list = g_slist_prepend(new_list, GINT_TO_POINTER(msginfo->msgnum));
2292                                 procmsg_msginfo_free(&msginfo);
2293
2294                                 debug_print("Remembering message %u to update...\n", folder_cur_num);
2295                         } else if (msginfo) {
2296                                 exists_list = g_slist_prepend(exists_list, msginfo);
2297
2298                                 if(prefs_common.thread_by_subject &&
2299                                         MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2300                                         !subject_table_lookup(subject_table, msginfo->subject)) {
2301                                         subject_table_insert(subject_table, msginfo->subject, msginfo);
2302                                 }
2303                         }
2304                         
2305                         /* Move to next folder and cache number */
2306                         if (cache_list_cur)
2307                                 cache_list_cur = cache_list_cur->next;
2308                         
2309                         if (folder_list_cur)
2310                                 folder_list_cur = folder_list_cur->next;
2311
2312                         if (cache_list_cur != NULL)
2313                                 cache_cur_num = ((MsgInfo *)cache_list_cur->data)->msgnum;
2314                         else
2315                                 cache_cur_num = G_MAXUINT;
2316
2317                         if (folder_list_cur != NULL)
2318                                 folder_cur_num = GPOINTER_TO_UINT(folder_list_cur->data);
2319                         else
2320                                 folder_cur_num = G_MAXUINT;
2321
2322                         continue;
2323                 }
2324         }
2325         
2326         for(cache_list_cur = cache_list; cache_list_cur != NULL; cache_list_cur = g_slist_next(cache_list_cur))
2327                 procmsg_msginfo_free((MsgInfo **)&(cache_list_cur->data));
2328
2329         g_slist_free(cache_list);
2330         g_slist_free(folder_list);
2331
2332         if (new_list != NULL) {
2333                 GSList *tmp_list = NULL;
2334                 newmsg_list = get_msginfos(item, new_list);
2335                 g_slist_free(new_list);
2336                 tmp_list = g_slist_concat(g_slist_copy(exists_list), g_slist_copy(newmsg_list));
2337                 syncronize_flags(item, tmp_list);
2338                 g_slist_free(tmp_list);
2339         } else {
2340                 syncronize_flags(item, exists_list);
2341         }
2342
2343         folder_item_update_freeze();
2344         
2345         item->scanning = ITEM_SCANNING;
2346
2347         if (newmsg_list != NULL) {
2348                 GSList *elem, *to_filter = NULL;
2349                 gboolean do_filter = (filtering == TRUE) &&
2350                                         (item->stype == F_INBOX) &&
2351                                         (item->folder->account != NULL) && 
2352                                         (item->folder->account->filter_on_recv);
2353                 
2354                 for (elem = newmsg_list; elem != NULL; elem = g_slist_next(elem)) {
2355                         MsgInfo *msginfo = (MsgInfo *) elem->data;
2356
2357                         msgcache_add_msg(item->cache, msginfo);
2358                         if (!do_filter) {
2359                                 exists_list = g_slist_prepend(exists_list, msginfo);
2360
2361                                 if(prefs_common.thread_by_subject &&
2362                                         MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2363                                         !subject_table_lookup(subject_table, msginfo->subject)) {
2364                                         subject_table_insert(subject_table, msginfo->subject, msginfo);
2365                                 }                       
2366                         }
2367                 }
2368
2369                 if (do_filter) {
2370                         GSList *unfiltered;
2371                         
2372                         folder_item_set_batch(item, TRUE);
2373                         procmsg_msglist_filter(newmsg_list, item->folder->account, 
2374                                         &to_filter, &unfiltered, 
2375                                         TRUE);
2376                         folder_item_set_batch(item, FALSE);
2377                         
2378                         filtering_move_and_copy_msgs(newmsg_list);
2379                         if (to_filter != NULL) {
2380                                 for (elem = to_filter; elem; elem = g_slist_next(elem)) {
2381                                         MsgInfo *msginfo = (MsgInfo *)elem->data;
2382                                         procmsg_msginfo_free(&msginfo);
2383                                 }
2384                                 g_slist_free(to_filter);
2385                         }
2386                         if (unfiltered != NULL) {
2387                                 for (elem = unfiltered; elem; elem = g_slist_next(elem)) {
2388                                         MsgInfo *msginfo = (MsgInfo *)elem->data;
2389                                         exists_list = g_slist_prepend(exists_list, msginfo);
2390
2391                                         if(prefs_common.thread_by_subject &&
2392                                                 MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2393                                                 !subject_table_lookup(subject_table, msginfo->subject)) {
2394                                                 subject_table_insert(subject_table, msginfo->subject, msginfo);
2395                                         }
2396                                 }
2397                                 g_slist_free(unfiltered);
2398                         }
2399                         if (prefs_common.real_time_sync)
2400                                 folder_item_synchronise(item);
2401                 } else {
2402                         if (prefs_common.real_time_sync)
2403                                 folder_item_synchronise(item);
2404                 }
2405
2406                 g_slist_free(newmsg_list);
2407
2408                 update_flags |= F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT;
2409         }
2410
2411         folder_item_set_batch(item, TRUE);
2412         for (elem = exists_list; elem != NULL; elem = g_slist_next(elem)) {
2413                 MsgInfo *msginfo, *parent_msginfo;
2414
2415                 msginfo = elem->data;
2416                 if (MSG_IS_IGNORE_THREAD(msginfo->flags) && (MSG_IS_NEW(msginfo->flags) || MSG_IS_UNREAD(msginfo->flags)))
2417                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
2418                 if (!MSG_IS_IGNORE_THREAD(msginfo->flags) && procmsg_msg_has_flagged_parent(msginfo, MSG_IGNORE_THREAD)) {
2419                         procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0, MSG_NEW | MSG_UNREAD, 0);
2420                 }
2421                 if (!MSG_IS_WATCH_THREAD(msginfo->flags) && procmsg_msg_has_flagged_parent(msginfo, MSG_WATCH_THREAD)) {
2422                         procmsg_msginfo_set_flags(msginfo, MSG_WATCH_THREAD, 0);
2423                 }
2424                 if(prefs_common.thread_by_subject && !msginfo->inreplyto &&
2425                         !msginfo->references && !MSG_IS_IGNORE_THREAD(msginfo->flags) &&
2426                         (parent_msginfo = subject_table_lookup(subject_table, msginfo->subject)))
2427                 {
2428                         if(MSG_IS_IGNORE_THREAD(parent_msginfo->flags)) {
2429                                 procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0,
2430                                                 MSG_NEW | MSG_UNREAD, 0);
2431                         }
2432                 }
2433                 if ((folder_has_parent_of_type(item, F_OUTBOX) ||
2434                      folder_has_parent_of_type(item, F_QUEUE)  ||
2435                      folder_has_parent_of_type(item, F_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                         if (cache_file != NULL)
2757                                 chmod(cache_file, filemode);
2758                 }
2759         } else {
2760                 item->cache_dirty = FALSE;
2761                 item->mark_dirty = FALSE;
2762                 item->tags_dirty = FALSE;
2763         }
2764
2765         if (!need_scan && item->folder->klass->set_mtime) {
2766                 if (item->mtime == last_mtime) {
2767                         item->folder->klass->set_mtime(item->folder, item);
2768                 }
2769         }
2770
2771         g_free(cache_file);
2772         g_free(mark_file);
2773         g_free(tags_file);
2774 }
2775
2776 MsgInfo *folder_item_get_msginfo(FolderItem *item, gint num)
2777 {
2778         MsgInfo *msginfo = NULL;
2779         
2780         cm_return_val_if_fail(item != NULL, NULL);
2781         if (item->no_select)
2782                 return NULL;
2783         if (!item->cache)
2784                 folder_item_read_cache(item);
2785         
2786         if ((msginfo = msgcache_get_msg(item->cache, num)) != NULL)
2787                 return msginfo;
2788         
2789         msginfo = get_msginfo(item, num);
2790         if (msginfo != NULL) {
2791                 msgcache_add_msg(item->cache, msginfo);
2792                 return msginfo;
2793         }
2794         
2795         return NULL;
2796 }
2797
2798 MsgInfo *folder_item_get_msginfo_by_msgid(FolderItem *item, const gchar *msgid)
2799 {
2800         MsgInfo *msginfo;
2801         
2802         cm_return_val_if_fail(item != NULL, NULL);
2803         cm_return_val_if_fail(msgid != NULL, NULL);
2804         if (item->no_select)
2805                 return NULL;
2806         
2807         if (!item->cache)
2808                 folder_item_read_cache(item);
2809         
2810         if ((msginfo = msgcache_get_msg_by_id(item->cache, msgid)) != NULL)
2811                 return msginfo;
2812
2813         return NULL;
2814 }
2815
2816 GSList *folder_item_get_msg_list(FolderItem *item)
2817 {
2818         cm_return_val_if_fail(item != NULL, NULL);
2819         if (item->no_select)
2820                 return NULL;
2821         
2822         if (item->cache == 0)
2823                 folder_item_read_cache(item);
2824
2825         cm_return_val_if_fail(item->cache != NULL, NULL);
2826         
2827         return msgcache_get_msg_list(item->cache);
2828 }
2829
2830 static void msginfo_set_mime_flags(GNode *node, gpointer data)
2831 {
2832         MsgInfo *msginfo = data;
2833         MimeInfo *mimeinfo = node->data;
2834         
2835         if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT
2836          && (!mimeinfo->subtype || (strcmp(mimeinfo->subtype, "pgp-signature") &&
2837              strcmp(mimeinfo->subtype, "x-pkcs7-signature") &&
2838              strcmp(mimeinfo->subtype, "pkcs7-signature")))) {
2839                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2840         } else if (mimeinfo->disposition == DISPOSITIONTYPE_UNKNOWN && 
2841                  mimeinfo->id == NULL &&
2842                  mimeinfo->type != MIMETYPE_TEXT &&
2843                  mimeinfo->type != MIMETYPE_MULTIPART) {
2844                 if (!mimeinfo->subtype 
2845                 || (strcmp(mimeinfo->subtype, "pgp-signature") && 
2846                     strcmp(mimeinfo->subtype, "x-pkcs7-signature") &&
2847                     strcmp(mimeinfo->subtype, "pkcs7-signature")))
2848                         procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2849         } else if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE &&
2850                  mimeinfo->id == NULL &&
2851                 (strcmp(mimeinfo->subtype, "pgp-signature") &&
2852                  strcmp(mimeinfo->subtype, "x-pkcs7-signature") &&
2853                  strcmp(mimeinfo->subtype, "pkcs7-signature")) && 
2854                 (procmime_mimeinfo_get_parameter(mimeinfo, "name") != NULL ||
2855                  procmime_mimeinfo_get_parameter(mimeinfo, "filename") != NULL)) {
2856                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2857         } 
2858
2859         /* don't descend below top level message for signed and encrypted info */
2860         if (mimeinfo->type == MIMETYPE_MESSAGE)
2861                 return;
2862
2863         if (privacy_mimeinfo_is_signed(mimeinfo)) {
2864                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
2865         }
2866
2867         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
2868                 procmsg_msginfo_set_flags(msginfo, 0, MSG_ENCRYPTED);
2869         } else {
2870                 /* searching inside encrypted parts doesn't really make sense */
2871                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2872         }
2873 }
2874
2875 gchar *folder_item_fetch_msg(FolderItem *item, gint num)
2876 {
2877         Folder *folder;
2878         gchar *msgfile;
2879         MsgInfo *msginfo;
2880
2881         cm_return_val_if_fail(item != NULL, NULL);
2882
2883         folder = item->folder;
2884
2885         cm_return_val_if_fail(folder->klass->fetch_msg != NULL, NULL);
2886         if (item->no_select)
2887                 return NULL;
2888
2889         msgfile = folder->klass->fetch_msg(folder, item, num);
2890
2891         if (msgfile != NULL) {
2892                 msginfo = folder_item_get_msginfo(item, num);
2893                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2894                         MimeInfo *mimeinfo;
2895
2896                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) && 
2897                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2898                                 mimeinfo = procmime_scan_file(msgfile);
2899                         else
2900                                 mimeinfo = procmime_scan_queue_file(msgfile);
2901                         /* check for attachments */
2902                         if (mimeinfo != NULL) { 
2903                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2904                                 procmime_mimeinfo_free_all(&mimeinfo);
2905
2906                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2907                         }
2908                 }
2909                 procmsg_msginfo_free(&msginfo);
2910         }
2911
2912         return msgfile;
2913 }
2914
2915 gchar *folder_item_fetch_msg_full(FolderItem *item, gint num, gboolean headers,
2916                                   gboolean body)
2917 {
2918         Folder *folder;
2919         gchar *msgfile;
2920         MsgInfo *msginfo;
2921
2922         cm_return_val_if_fail(item != NULL, NULL);
2923         if (item->no_select)
2924                 return NULL;
2925         
2926         folder = item->folder;
2927
2928         if (folder->klass->fetch_msg_full == NULL)
2929                 return folder_item_fetch_msg(item, num);
2930
2931         if (item->prefs->offlinesync && prefs_common.real_time_sync)
2932                 msgfile = folder->klass->fetch_msg_full(folder, item, num, 
2933                                                 TRUE, TRUE);
2934         else
2935                 msgfile = folder->klass->fetch_msg_full(folder, item, num, 
2936                                                 headers, body);
2937
2938         if (msgfile != NULL) {
2939                 msginfo = folder_item_get_msginfo(item, num);
2940                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2941                         MimeInfo *mimeinfo;
2942
2943                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
2944                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2945                                 mimeinfo = procmime_scan_file(msgfile);
2946                         else
2947                                 mimeinfo = procmime_scan_queue_file(msgfile);
2948                         /* check for attachments */
2949                         if (mimeinfo != NULL) { 
2950                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2951                                 procmime_mimeinfo_free_all(&mimeinfo);
2952
2953                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2954                         }
2955                 }
2956                 procmsg_msginfo_free(&msginfo);
2957         }
2958
2959         return msgfile;
2960 }
2961
2962
2963 static gint folder_item_get_msg_num_by_file(FolderItem *dest, const gchar *file)
2964 {
2965         static HeaderEntry hentry[] = {{"Message-ID:",  NULL, TRUE},
2966                                        {NULL,           NULL, FALSE}};
2967         FILE *fp;
2968         MsgInfo *msginfo;
2969         gint msgnum = 0;
2970         gchar buf[BUFFSIZE];
2971
2972         if ((fp = g_fopen(file, "rb")) == NULL)
2973                 return 0;
2974
2975         if ((folder_has_parent_of_type(dest, F_QUEUE)) || 
2976             (folder_has_parent_of_type(dest, F_DRAFT)))
2977                 while (fgets(buf, sizeof(buf), fp) != NULL) {
2978                         /* new way */
2979                         if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2980                                 strlen("X-Claws-End-Special-Headers:"))) ||
2981                             (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2982                                 strlen("X-Sylpheed-End-Special-Headers:"))))
2983                                 break;
2984                         /* old way */
2985                         if (buf[0] == '\r' || buf[0] == '\n') break;
2986                         /* from other mailers */
2987                         if (!strncmp(buf, "Date: ", 6)
2988                         ||  !strncmp(buf, "To: ", 4)
2989                         ||  !strncmp(buf, "From: ", 6)
2990                         ||  !strncmp(buf, "Subject: ", 9)) {
2991                                 rewind(fp);
2992                                 break;
2993                         }
2994                 }
2995
2996         procheader_get_header_fields(fp, hentry);
2997         debug_print("looking for %s\n", hentry[0].body);
2998         if (hentry[0].body) {
2999                 extract_parenthesis(hentry[0].body, '<', '>');
3000                 remove_space(hentry[0].body);
3001                 if ((msginfo = msgcache_get_msg_by_id(dest->cache, hentry[0].body)) != NULL) {
3002                         msgnum = msginfo->msgnum;
3003                         procmsg_msginfo_free(&msginfo);
3004
3005                         debug_print("found message as uid %d\n", msgnum);
3006                 }
3007         }
3008         
3009         g_free(hentry[0].body);
3010         hentry[0].body = NULL;
3011         fclose(fp);
3012
3013         return msgnum;
3014 }
3015
3016 static void copy_msginfo_flags(MsgInfo *source, MsgInfo *dest)
3017 {
3018         MsgPermFlags perm_flags = 0;
3019         MsgTmpFlags tmp_flags = 0;
3020
3021         /* create new flags */
3022         if (source != NULL) {
3023                 /* copy original flags */
3024                 perm_flags = source->flags.perm_flags;
3025                 tmp_flags = source->flags.tmp_flags;
3026         } else {
3027                 perm_flags = dest->flags.perm_flags;
3028                 tmp_flags = dest->flags.tmp_flags;
3029         }
3030
3031         /* remove new, unread and deleted in special folders */
3032         if (folder_has_parent_of_type(dest->folder, F_OUTBOX) || 
3033             folder_has_parent_of_type(dest->folder, F_QUEUE) || 
3034             folder_has_parent_of_type(dest->folder, F_DRAFT) || 
3035             folder_has_parent_of_type(dest->folder, F_TRASH))
3036                 perm_flags &= ~(MSG_NEW | MSG_UNREAD | MSG_DELETED);
3037
3038         /* set ignore flag of ignored parent exists */
3039         if (procmsg_msg_has_flagged_parent(dest, MSG_IGNORE_THREAD))
3040                 perm_flags |= MSG_IGNORE_THREAD;
3041
3042         /* unset FULLY_CACHED flags */
3043         perm_flags &= ~MSG_FULLY_CACHED;
3044
3045         if (procmsg_msg_has_flagged_parent(dest, MSG_WATCH_THREAD))
3046                 perm_flags |= MSG_WATCH_THREAD;
3047
3048         /* Unset tmp flags that should not be copied */
3049         tmp_flags &= ~(MSG_MOVE | MSG_COPY | MSG_MOVE_DONE);
3050
3051         /* unset flags that are set but should not */
3052         /* and set new flags */
3053         procmsg_msginfo_change_flags(dest,
3054                                   ~dest->flags.perm_flags & perm_flags,
3055                                   ~dest->flags.tmp_flags  & tmp_flags,
3056                                    dest->flags.perm_flags & ~perm_flags,
3057                                    dest->flags.tmp_flags  & ~tmp_flags);
3058         
3059         if (source && source->tags) {
3060                 g_slist_free(dest->tags);
3061                 dest->tags = g_slist_copy(source->tags);
3062                 folder_item_commit_tags(dest->folder, dest, dest->tags, NULL);
3063         }
3064 }
3065
3066 static void add_msginfo_to_cache(FolderItem *item, MsgInfo *newmsginfo, MsgInfo *flagsource)
3067 {
3068         /* update folder stats */
3069         if (MSG_IS_NEW(newmsginfo->flags))
3070                 item->new_msgs++;
3071         if (MSG_IS_UNREAD(newmsginfo->flags))
3072                 item->unread_msgs++;
3073         if (MSG_IS_UNREAD(newmsginfo->flags) && procmsg_msg_has_marked_parent(newmsginfo))
3074                 item->unreadmarked_msgs++;
3075         if (MSG_IS_MARKED(newmsginfo->flags))
3076                 item->marked_msgs++;
3077         if (MSG_IS_REPLIED(newmsginfo->flags))
3078                 item->replied_msgs++;
3079         if (MSG_IS_FORWARDED(newmsginfo->flags))
3080                 item->forwarded_msgs++;
3081         if (MSG_IS_LOCKED(newmsginfo->flags))
3082                 item->locked_msgs++;
3083         if (MSG_IS_IGNORE_THREAD(newmsginfo->flags))
3084                 item->ignored_msgs++;
3085         if (MSG_IS_WATCH_THREAD(newmsginfo->flags))
3086                 item->watched_msgs++;
3087         item->total_msgs++;
3088
3089         folder_item_update_freeze();
3090
3091         if (!item->cache)
3092                 folder_item_read_cache(item);
3093
3094         msgcache_add_msg(item->cache, newmsginfo);
3095         copy_msginfo_flags(flagsource, newmsginfo);
3096         folder_item_update_with_msg(item,  F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_ADDMSG, newmsginfo);
3097         folder_item_update_thaw();
3098 }
3099
3100 static void remove_msginfo_from_cache(FolderItem *item, MsgInfo *msginfo)
3101 {
3102         MsgInfoUpdate msginfo_update;
3103
3104         if (!item->cache)
3105                 folder_item_read_cache(item);
3106
3107         if (MSG_IS_NEW(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
3108                 msginfo->folder->new_msgs--;
3109         if (MSG_IS_UNREAD(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
3110                 msginfo->folder->unread_msgs--;
3111         if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
3112                 msginfo->folder->unreadmarked_msgs--;
3113         if (MSG_IS_MARKED(msginfo->flags))
3114                 item->marked_msgs--;
3115         if (MSG_IS_REPLIED(msginfo->flags))
3116                 item->replied_msgs--;
3117         if (MSG_IS_FORWARDED(msginfo->flags))
3118                 item->forwarded_msgs--;
3119         if (MSG_IS_LOCKED(msginfo->flags))
3120                 item->locked_msgs--;
3121         if (MSG_IS_IGNORE_THREAD(msginfo->flags))
3122                 item->ignored_msgs--;
3123         if (MSG_IS_WATCH_THREAD(msginfo->flags))
3124                 item->watched_msgs--;
3125
3126         msginfo->folder->total_msgs--;
3127
3128         msginfo_update.msginfo = msginfo;
3129         msginfo_update.flags = MSGINFO_UPDATE_DELETED;
3130         hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
3131
3132         msgcache_remove_msg(item->cache, msginfo->msgnum);
3133         folder_item_update_with_msg(msginfo->folder, F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_REMOVEMSG, msginfo);
3134 }
3135
3136 gint folder_item_add_msg(FolderItem *dest, const gchar *file,
3137                          MsgFlags *flags, gboolean remove_source)
3138 {
3139         GSList file_list;
3140         MsgFileInfo fileinfo;
3141
3142         cm_return_val_if_fail(dest != NULL, -1);
3143         cm_return_val_if_fail(file != NULL, -1);
3144  
3145         fileinfo.msginfo = NULL;
3146         fileinfo.file = (gchar *)file;
3147         fileinfo.flags = flags;
3148         file_list.data = &fileinfo;
3149         file_list.next = NULL;
3150
3151         return folder_item_add_msgs(dest, &file_list, remove_source);
3152 }
3153
3154 gint folder_item_add_msgs(FolderItem *dest, GSList *file_list,
3155                           gboolean remove_source)
3156 {
3157         Folder *folder;
3158         gint ret, num, lastnum = -1;
3159         GSList *file_cur;
3160         GHashTable *relation;
3161         MsgFileInfo *fileinfo = NULL;
3162         gboolean folderscan = FALSE;
3163
3164         cm_return_val_if_fail(dest != NULL, -1);
3165         cm_return_val_if_fail(file_list != NULL, -1);
3166         cm_return_val_if_fail(dest->folder != NULL, -1);
3167         if (dest->no_select)
3168                 return -1;
3169
3170         folder = dest->folder;
3171
3172         relation = g_hash_table_new(g_direct_hash, g_direct_equal);
3173
3174         if (folder->klass->add_msgs != NULL) {
3175                 ret = folder->klass->add_msgs(folder, dest, file_list, relation);
3176                 if (ret < 0) {
3177                         g_hash_table_destroy(relation);
3178                         return ret;
3179                 }
3180         } else {
3181                 for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
3182                         fileinfo = (MsgFileInfo *) file_cur->data;
3183
3184                         ret = folder->klass->add_msg(folder, dest, fileinfo->file, fileinfo->flags);
3185                         if (ret < 0) {
3186                                 g_hash_table_destroy(relation);
3187                                 return ret;
3188                         }
3189                         g_hash_table_insert(relation, fileinfo, GINT_TO_POINTER(ret));
3190                 }
3191         }
3192
3193         for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
3194                 gpointer data, old_key;
3195
3196                 fileinfo = (MsgFileInfo *) file_cur->data;
3197                 if (g_hash_table_lookup_extended(relation, fileinfo, &old_key, &data))
3198                         num = GPOINTER_TO_INT(data);
3199                 else
3200                         num = -1;
3201
3202                 if (num >= 0) {
3203                         MsgInfo *newmsginfo;
3204
3205                         if (num == 0) {
3206                                 if (!folderscan) {
3207                                         folder_item_scan_full(dest, FALSE);
3208                                         folderscan = TRUE;
3209                                 }
3210                                 num = folder_item_get_msg_num_by_file(dest, fileinfo->file);
3211                                 debug_print("got num %d\n", num);
3212                         }
3213
3214                         if (num > lastnum)
3215                                 lastnum = num;
3216
3217                         if (num >= 0 && remove_source) {
3218                                 if (claws_unlink(fileinfo->file) < 0)
3219                                         FILE_OP_ERROR(fileinfo->file, "unlink");
3220                         }
3221
3222                         if (num == 0)
3223                                 continue;
3224
3225                         if (!folderscan && 
3226                             ((newmsginfo = get_msginfo(dest, num)) != NULL)) {
3227                                 add_msginfo_to_cache(dest, newmsginfo, NULL);
3228                                 procmsg_msginfo_free(&newmsginfo);
3229                         } else if ((newmsginfo = msgcache_get_msg(dest->cache, num)) != NULL) {
3230                                 /* TODO: set default flags */
3231                                 procmsg_msginfo_free(&newmsginfo);
3232                         }
3233                 }
3234         }
3235
3236         g_hash_table_destroy(relation);
3237
3238         return lastnum;
3239 }
3240
3241 static FolderItem *folder_item_move_recursive(FolderItem *src, FolderItem *dest, gboolean copy) 
3242 {
3243         GSList *mlist;
3244         FolderItem *new_item;
3245         FolderItem *next_item;
3246         GNode *srcnode;
3247         gchar *old_id, *new_id;
3248         FolderUpdateData hookdata;
3249
3250         /* move messages */
3251         debug_print("%s %s to %s\n", copy?"Copying":"Moving", src->path, dest->path);
3252         new_item = folder_create_folder(dest, src->name);
3253         if (new_item == NULL) {
3254                 g_print("Can't create folder\n");
3255                 return NULL;
3256         }
3257         
3258         if (new_item->folder == NULL)
3259                 new_item->folder = dest->folder;
3260
3261         /* move messages */
3262         log_message(LOG_PROTOCOL, copy ?_("Copying %s to %s...\n"):_("Moving %s to %s...\n"), 
3263                         src->name, new_item->path);
3264
3265         /*copy prefs*/
3266         folder_item_prefs_copy_prefs(src, new_item);
3267         
3268         /* copy internal data */
3269         if (src->folder->klass == new_item->folder->klass &&
3270             src->folder->klass->copy_private_data != NULL)
3271                 src->folder->klass->copy_private_data(src->folder,
3272                                         src, new_item);
3273         new_item->collapsed = src->collapsed;
3274         new_item->thread_collapsed = src->thread_collapsed;
3275         new_item->threaded  = src->threaded;
3276         new_item->ret_rcpt  = src->ret_rcpt;
3277         new_item->hide_read_msgs = src->hide_read_msgs;
3278         new_item->hide_del_msgs = src->hide_del_msgs;
3279         new_item->hide_read_threads = src->hide_read_threads;
3280         new_item->sort_key  = src->sort_key;
3281         new_item->sort_type = src->sort_type;
3282
3283         mlist = folder_item_get_msg_list(src);
3284
3285         if (mlist != NULL) {
3286                 if (copy)
3287                         folder_item_copy_msgs(new_item, mlist);
3288                 else
3289                         folder_item_move_msgs(new_item, mlist);
3290                 procmsg_msg_list_free(mlist);
3291         }
3292
3293         prefs_matcher_write_config();
3294         
3295         /* recurse */
3296         srcnode = src->folder->node;    
3297         srcnode = g_node_find(srcnode, G_PRE_ORDER, G_TRAVERSE_ALL, src);
3298         srcnode = srcnode->children;
3299         while (srcnode != NULL) {
3300                 if (srcnode && srcnode->data) {
3301                         next_item = (FolderItem*) srcnode->data;
3302                         srcnode = srcnode->next;
3303                         if (folder_item_move_recursive(next_item, new_item, copy) == NULL) {
3304                                 return NULL;
3305                         }
3306                 }
3307         }
3308         old_id = folder_item_get_identifier(src);
3309         new_id = folder_item_get_identifier(new_item);
3310
3311         hookdata.folder = src->folder;
3312         hookdata.update_flags = FOLDER_TREE_CHANGED | FOLDER_MOVE_FOLDERITEM;
3313         hookdata.item = src;
3314         hookdata.item2 = new_item;
3315         hooks_invoke(FOLDER_UPDATE_HOOKLIST, &hookdata);
3316
3317         /* if src supports removing, otherwise only copy folder */
3318         if (src->folder->klass->remove_folder != NULL && !copy) 
3319                 src->folder->klass->remove_folder(src->folder, src);
3320         folder_write_list();
3321
3322         if (!copy) {
3323                 debug_print("updating rules : %s => %s\n", old_id, new_id);
3324                 if (old_id != NULL && new_id != NULL) {
3325                         prefs_filtering_rename_path(old_id, new_id);
3326                         account_rename_path(old_id, new_id);
3327                 }
3328         }
3329         g_free(old_id);
3330         g_free(new_id);
3331         
3332         return new_item;
3333 }
3334
3335 gint folder_item_move_to(FolderItem *src, FolderItem *dest, FolderItem **new_item, gboolean copy)
3336 {
3337         FolderItem *tmp = folder_item_parent(dest);
3338         gchar * src_identifier, * dst_identifier;
3339         gchar * phys_srcpath, * phys_dstpath, *tmppath;
3340
3341         while (tmp) {
3342                 if (tmp == src) {
3343                         return F_MOVE_FAILED_DEST_IS_CHILD;
3344                 }
3345                 tmp = folder_item_parent(tmp);
3346         }
3347
3348         /* both dst and src can be root folders */
3349         src_identifier = folder_item_get_identifier(src);
3350         if (src_identifier == NULL && src->folder && folder_item_parent(src) == NULL) {
3351                 src_identifier = folder_get_identifier(src->folder);
3352         }
3353
3354         dst_identifier = folder_item_get_identifier(dest);
3355         if(dst_identifier == NULL && dest->folder && folder_item_parent(dest) == NULL) {
3356                 dst_identifier = folder_get_identifier(dest->folder);
3357         }
3358
3359         if (src_identifier == NULL || dst_identifier == NULL) {
3360                 debug_print("Can't get identifiers\n");
3361                 return F_MOVE_FAILED;
3362         }
3363
3364         if (src->folder != dest->folder && !copy) {
3365                 return F_MOVE_FAILED_DEST_OUTSIDE_MAILBOX;
3366         }
3367
3368         phys_srcpath = folder_item_get_path(src);
3369         tmppath = folder_item_get_path(dest);
3370         phys_dstpath = g_strconcat(tmppath,
3371                        G_DIR_SEPARATOR_S,
3372                        g_path_get_basename(phys_srcpath),
3373                        NULL);
3374         g_free(tmppath);
3375
3376         if (folder_item_parent(src) == dest || src == dest) {
3377                 g_free(src_identifier);
3378                 g_free(dst_identifier);
3379                 g_free(phys_srcpath);
3380                 g_free(phys_dstpath);
3381                 return F_MOVE_FAILED_DEST_IS_PARENT;
3382         }
3383         debug_print("moving \"%s\" to \"%s\"\n", phys_srcpath, phys_dstpath);
3384         if ((tmp = folder_item_move_recursive(src, dest, copy)) == NULL) {
3385                 return F_MOVE_FAILED;
3386         }
3387         
3388         g_free(src_identifier);
3389         g_free(dst_identifier);
3390         g_free(phys_srcpath);
3391         g_free(phys_dstpath);
3392
3393         *new_item = tmp;
3394
3395         return F_MOVE_OK;
3396 }
3397
3398 struct find_data
3399 {
3400         gboolean found;
3401 };      
3402 static void find_num(gpointer key, gpointer value, gpointer data)
3403 {
3404         struct find_data *fdata = (struct find_data *)data;
3405         if (GPOINTER_TO_INT(value) == 0)
3406                 fdata->found = TRUE;
3407 }
3408
3409 static gboolean some_msgs_have_zero_num(GHashTable *hashtable)
3410 {
3411         struct find_data fdata;
3412         
3413         fdata.found = FALSE;
3414         g_hash_table_foreach(hashtable, find_num, &fdata);
3415         
3416         return fdata.found;
3417 }
3418
3419 /**
3420  * Copy a list of message to a new folder and remove
3421  * source messages if wanted
3422  */
3423 static gint do_copy_msgs(FolderItem *dest, GSList *msglist, gboolean remove_source)
3424 {
3425         Folder *folder;
3426         GSList *l;
3427         gint num, lastnum = -1;
3428         gboolean folderscan = FALSE;
3429         GHashTable *relation;
3430         GSList *not_moved = NULL;
3431         gint total = 0, curmsg = 0;
3432         MsgInfo *msginfo = NULL;
3433
3434         cm_return_val_if_fail(dest != NULL, -1);
3435         cm_return_val_if_fail(msglist != NULL, -1);
3436
3437         folder = dest->folder;
3438
3439         cm_return_val_if_fail(folder->klass->copy_msg != NULL, -1);
3440         if (dest->no_select)
3441                 return -1;
3442
3443         msginfo = (MsgInfo *)msglist->data;
3444         
3445         if (!msginfo)
3446                 return -1;
3447         
3448         if (!MSG_IS_QUEUED(msginfo->flags) && 
3449             MSG_IS_DRAFT(msginfo->flags) && 
3450             folder_has_parent_of_type(dest, F_QUEUE)) {
3451                 GSList *cur = msglist;
3452                 gboolean queue_err = FALSE;
3453                 for (; cur; cur = cur->next) {
3454                         Compose *compose = NULL;
3455                         FolderItem *queue = dest;
3456                         int val = 0;
3457                         
3458                         msginfo = (MsgInfo *)cur->data;
3459                         compose = compose_reedit(msginfo, TRUE);
3460                         if (compose == NULL) {
3461                                 queue_err = TRUE;
3462                                 continue;
3463                         }
3464                         val = compose_queue(compose, NULL, &queue, NULL,
3465                                         FALSE);
3466                         if (val < 0) {
3467                                 queue_err = TRUE;
3468                         } else if (remove_source) {
3469                                 folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
3470                         }
3471                         if (val == 0)
3472                                 compose_close(compose);
3473                 }
3474                 return queue_err ? -1:0;
3475         }
3476
3477         relation = g_hash_table_new(g_direct_hash, g_direct_equal);
3478
3479         for (l = msglist ; l != NULL ; l = g_slist_next(l)) {
3480                 MsgInfo * msginfo = (MsgInfo *) l->data;
3481
3482                 if (msginfo->planned_download != 0) {
3483                         int old_planned = msginfo->planned_download;
3484                         partial_unmark(msginfo);
3485                         /* little hack to reenable after */
3486                         msginfo->planned_download = old_planned;
3487                 }
3488         }
3489
3490         /* 
3491          * Copy messages to destination folder and 
3492          * store new message numbers in newmsgnums
3493          */
3494         if (folder->klass->copy_msgs != NULL) {
3495                 if (folder->klass->copy_msgs(folder, dest, msglist, relation) < 0) {
3496                         g_hash_table_destroy(relation);
3497                         return -1;
3498                 }
3499         } else {
3500                 MsgInfo * msginfo;
3501                 l = msglist;
3502
3503                 /* immediately stop if src and dest folders are identical */
3504                 if (l != NULL) {
3505                         msginfo = (MsgInfo *) l->data;
3506                         if (msginfo != NULL && msginfo->folder == dest) {
3507                                 g_hash_table_destroy(relation);
3508                                 return -1;
3509                         }
3510                 }
3511
3512                 for (; l != NULL ; l = g_slist_next(l)) {
3513                         msginfo = (MsgInfo *) l->data;
3514
3515                         num = folder->klass->copy_msg(folder, dest, msginfo);
3516                         if (num > 0)
3517