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