a55dcace55b78c1ef323a941f153850670e32777
[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         g_return_val_if_fail(item->path != NULL, NULL);
1206
1207         folder_id = folder_get_identifier(item->folder);
1208         id = g_strconcat(folder_id, "/", item->path, NULL);
1209         g_free(folder_id);
1210
1211         return id;
1212 }
1213
1214 FolderItem *folder_find_item_from_identifier(const gchar *identifier)
1215 {
1216         Folder *folder;
1217         gpointer d[2];
1218         gchar *str;
1219         gchar *p;
1220         gchar *name;
1221         gchar *path;
1222         FolderClass *class;
1223
1224         g_return_val_if_fail(identifier != NULL, NULL);
1225
1226         if (*identifier != '#')
1227                 return folder_find_item_from_path(identifier);
1228
1229         Xstrdup_a(str, identifier, return NULL);
1230
1231         p = strchr(str, '/');
1232         if (!p)
1233                 return folder_find_item_from_path(identifier);
1234         *p = '\0';
1235         p++;
1236         class = folder_get_class_from_string(&str[1]);
1237         if (class == NULL)
1238                 return folder_find_item_from_path(identifier);
1239
1240         name = p;
1241         p = strchr(p, '/');
1242         if (!p)
1243                 return folder_find_item_from_path(identifier);
1244         *p = '\0';
1245         p++;
1246
1247         folder = folder_find_from_name(name, class);
1248         if (!folder)
1249                 return folder_find_item_from_path(identifier);
1250
1251         path = p;
1252
1253         d[0] = (gpointer)path;
1254         d[1] = NULL;
1255         g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1256                         folder_item_find_func, d);
1257         return d[1];
1258 }
1259
1260 /**
1261  * Get a displayable name for a FolderItem
1262  *
1263  * \param item FolderItem for that a name should be created
1264  * \return Displayable name for item, returned string has to
1265  *         be freed
1266  */
1267 gchar *folder_item_get_name(FolderItem *item)
1268 {
1269         gchar *name = NULL;
1270
1271         g_return_val_if_fail(item != NULL, g_strdup(""));
1272
1273         switch (item->stype) {
1274         case F_INBOX:
1275                 name = g_strdup(!strcmp2(item->name, INBOX_DIR) ? _("Inbox") :
1276                                 item->name);
1277                 break;
1278         case F_OUTBOX:
1279                 name = g_strdup(!strcmp2(item->name, OUTBOX_DIR) ? _("Sent") :
1280                                 item->name);
1281                 break;
1282         case F_QUEUE:
1283                 name = g_strdup(!strcmp2(item->name, QUEUE_DIR) ? _("Queue") :
1284                                 item->name);
1285                 break;
1286         case F_TRASH:
1287                 name = g_strdup(!strcmp2(item->name, TRASH_DIR) ? _("Trash") :
1288                                 item->name);
1289                 break;
1290         case F_DRAFT:
1291                 name = g_strdup(!strcmp2(item->name, DRAFT_DIR) ? _("Drafts") :
1292                                 item->name);
1293                 break;
1294         default:
1295                 break;
1296         }
1297
1298         if (name == NULL) {
1299                 /*
1300                  * should probably be done by a virtual function,
1301                  * the folder knows the ui string and how to abbrev
1302                 */
1303                 if (folder_item_parent(item) == NULL) {
1304                         name = g_strconcat(item->name, " (", item->folder->klass->uistr, ")", NULL);
1305                 } else {
1306                         if (FOLDER_CLASS(item->folder) == news_get_class() &&
1307                             item->path && !strcmp2(item->name, item->path))
1308                                 name = get_abbrev_newsgroup_name
1309                                         (item->path,
1310                                          prefs_common.ng_abbrev_len);
1311                         else
1312                                 name = g_strdup(item->name);
1313                 }
1314         }
1315
1316         if (name == NULL)
1317                 name = g_strdup("");
1318
1319         return name;
1320 }
1321
1322 Folder *folder_get_default_folder(void)
1323 {
1324         return folder_list ? FOLDER(folder_list->data) : NULL;
1325 }
1326
1327 gboolean folder_have_mailbox (void)
1328 {
1329         GList *cur;
1330         for (cur = folder_list; cur != NULL; cur = g_list_next(cur)) {
1331                 Folder *folder = FOLDER(cur->data);
1332                 if (folder->inbox && folder->outbox)
1333                         return TRUE;
1334         }
1335         return FALSE;
1336 }
1337
1338 FolderItem *folder_get_default_inbox(void)
1339 {
1340         GList *flist;
1341
1342         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1343                 Folder * folder = FOLDER(flist->data);
1344
1345                 if (folder == NULL)
1346                         continue;
1347                 if (folder->inbox == NULL)
1348                         continue;
1349                 if (folder->klass->type == F_UNKNOWN)
1350                         continue;
1351
1352                 return folder->inbox;
1353         }
1354
1355         return NULL;
1356 }
1357
1358 FolderItem *folder_get_default_outbox(void)
1359 {
1360         GList *flist;
1361
1362         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1363                 Folder * folder = FOLDER(flist->data);
1364
1365                 if (folder == NULL)
1366                         continue;
1367                 if (folder->outbox == NULL)
1368                         continue;
1369                 if (folder->klass->type == F_UNKNOWN)
1370                         continue;
1371
1372                 return folder->outbox;
1373         }
1374
1375         return NULL;
1376 }
1377
1378 FolderItem *folder_get_default_draft(void)
1379 {
1380         GList *flist;
1381
1382         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1383                 Folder * folder = FOLDER(flist->data);
1384
1385                 if (folder == NULL)
1386                         continue;
1387                 if (folder->draft == NULL)
1388                         continue;
1389                 if (folder->klass->type == F_UNKNOWN)
1390                         continue;
1391
1392                 return folder->draft;
1393         }
1394
1395         return NULL;
1396 }
1397
1398 FolderItem *folder_get_default_queue(void)
1399 {
1400         GList *flist;
1401
1402         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1403                 Folder * folder = FOLDER(flist->data);
1404
1405                 if (folder == NULL)
1406                         continue;
1407                 if (folder->queue == NULL)
1408                         continue;
1409                 if (folder->klass->type == F_UNKNOWN)
1410                         continue;
1411
1412                 return folder->queue;
1413         }
1414
1415         return NULL;
1416 }
1417
1418 FolderItem *folder_get_default_trash(void)
1419 {
1420         GList *flist;
1421
1422         for (flist = folder_list; flist != NULL; flist = g_list_next(flist)) {
1423                 Folder * folder = FOLDER(flist->data);
1424
1425                 if (folder == NULL)
1426                         continue;
1427                 if (folder->trash == NULL)
1428                         continue;
1429                 if (folder->klass->type == F_UNKNOWN)
1430                         continue;
1431
1432                 return folder->trash;
1433         }
1434
1435         return NULL;
1436 }
1437
1438 #define CREATE_FOLDER_IF_NOT_EXIST(member, dir, type)           \
1439 {                                                               \
1440         if (!folder->member) {                                  \
1441                 item = folder_item_new(folder, dir, dir);       \
1442                 item->stype = type;                             \
1443                 folder_item_append(rootitem, item);             \
1444                 folder->member = item;                          \
1445         }                                                       \
1446 }
1447
1448 void folder_set_missing_folders(void)
1449 {
1450         Folder *folder;
1451         FolderItem *rootitem;
1452         FolderItem *item;
1453         GList *list;
1454
1455         for (list = folder_list; list != NULL; list = list->next) {
1456                 folder = list->data;
1457                 if (FOLDER_TYPE(folder) != F_MH) continue;
1458                 rootitem = FOLDER_ITEM(folder->node->data);
1459                 g_return_if_fail(rootitem != NULL);
1460
1461                 if (folder->inbox && folder->outbox && folder->draft &&
1462                     folder->queue && folder->trash)
1463                         continue;
1464
1465                 if (folder->klass->create_tree(folder) < 0) {
1466                         g_warning("%s: can't create the folder tree.\n",
1467                                   LOCAL_FOLDER(folder)->rootpath);
1468                         continue;
1469                 }
1470
1471                 CREATE_FOLDER_IF_NOT_EXIST(inbox,  INBOX_DIR,  F_INBOX);
1472                 CREATE_FOLDER_IF_NOT_EXIST(outbox, OUTBOX_DIR, F_OUTBOX);
1473                 CREATE_FOLDER_IF_NOT_EXIST(draft,  DRAFT_DIR,  F_DRAFT);
1474                 CREATE_FOLDER_IF_NOT_EXIST(queue,  QUEUE_DIR,  F_QUEUE);
1475                 CREATE_FOLDER_IF_NOT_EXIST(trash,  TRASH_DIR,  F_TRASH);
1476         }
1477 }
1478
1479 static gboolean folder_unref_account_func(GNode *node, gpointer data)
1480 {
1481         FolderItem *item = node->data;
1482         PrefsAccount *account = data;
1483
1484         if (item->account == account)
1485                 item->account = NULL;
1486
1487         return FALSE;
1488 }
1489
1490 void folder_unref_account_all(PrefsAccount *account)
1491 {
1492         Folder *folder;
1493         GList *list;
1494
1495         if (!account) return;
1496
1497         for (list = folder_list; list != NULL; list = list->next) {
1498                 folder = list->data;
1499                 if (folder->account == account)
1500                         folder->account = NULL;
1501                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1502                                 folder_unref_account_func, account);
1503         }
1504 }
1505
1506 #undef CREATE_FOLDER_IF_NOT_EXIST
1507
1508 gchar *folder_item_get_path(FolderItem *item)
1509 {
1510         Folder *folder;
1511
1512         g_return_val_if_fail(item != NULL, NULL);
1513         folder = item->folder;
1514         g_return_val_if_fail(folder != NULL, NULL);
1515
1516         return folder->klass->item_get_path(folder, item);
1517 }
1518
1519 void folder_item_set_default_flags(FolderItem *dest, MsgFlags *flags)
1520 {
1521         if (!(folder_has_parent_of_type(dest, F_OUTBOX) ||
1522               folder_has_parent_of_type(dest, F_QUEUE)  ||
1523               folder_has_parent_of_type(dest, F_DRAFT) ||
1524               folder_has_parent_of_type(dest, F_TRASH))) {
1525                 flags->perm_flags = MSG_NEW|MSG_UNREAD;
1526         } else {
1527                 flags->perm_flags = 0;
1528         }
1529         if (FOLDER_TYPE(dest->folder) == F_MH) {
1530                 if (folder_has_parent_of_type(dest, F_QUEUE)) {
1531                         MSG_SET_TMP_FLAGS(*flags, MSG_QUEUED);
1532                 } else if (folder_has_parent_of_type(dest, F_DRAFT)) {
1533                         MSG_SET_TMP_FLAGS(*flags, MSG_DRAFT);
1534                 }
1535         }
1536 }
1537
1538 static gint folder_sort_cache_list_by_msgnum(gconstpointer a, gconstpointer b)
1539 {
1540         MsgInfo *msginfo_a = (MsgInfo *) a;
1541         MsgInfo *msginfo_b = (MsgInfo *) b;
1542
1543         return (msginfo_a->msgnum - msginfo_b->msgnum);
1544 }
1545
1546 static gint folder_sort_folder_list(gconstpointer a, gconstpointer b)
1547 {
1548         guint gint_a = GPOINTER_TO_INT(a);
1549         guint gint_b = GPOINTER_TO_INT(b);
1550         
1551         return (gint_a - gint_b);
1552 }
1553
1554 void folder_item_process_open (FolderItem *item,
1555                                  void (*before_proc_func)(gpointer data),
1556                                  void (*after_proc_func)(gpointer data),
1557                                  gpointer data)
1558 {
1559         gchar *buf;
1560         if (item == NULL)
1561                 return;
1562         if((item->folder->klass->scan_required != NULL) &&
1563            (item->folder->klass->scan_required(item->folder, item))) {
1564                 folder_item_scan_full(item, TRUE);
1565         } else {
1566                 folder_item_syncronize_flags(item);
1567         }
1568         
1569         /* Processing */
1570         buf = g_strdup_printf(_("Processing (%s)...\n"), 
1571                               item->path ? item->path : item->name);
1572         debug_print("%s\n", buf);
1573         g_free(buf);
1574
1575         if (before_proc_func)
1576                 before_proc_func(data);
1577
1578         folder_item_apply_processing(item);
1579
1580         if (after_proc_func)
1581                 after_proc_func(data);
1582
1583         debug_print("done.\n");
1584         item->processing_pending = FALSE;
1585         return; 
1586 }
1587
1588 gint folder_item_open(FolderItem *item)
1589 {
1590         START_TIMING("folder_item_open"); 
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                 int total = g_slist_length(newmsg_list), cur = 0;
1938                 
1939                 if ((filtering == TRUE) &&
1940                     (item->stype == F_INBOX) &&
1941                     (item->folder->account != NULL) && 
1942                     (item->folder->account->filter_on_recv)) 
1943                         statusbar_print_all(_("Filtering messages...\n"));
1944                 
1945                 for (elem = newmsg_list; elem != NULL; elem = g_slist_next(elem)) {
1946                         MsgInfo *msginfo = (MsgInfo *) elem->data;
1947
1948                         statusbar_progress_all(cur++,total, 10);
1949
1950                         msgcache_add_msg(item->cache, msginfo);
1951                         if ((filtering == TRUE) &&
1952                             (item->stype == F_INBOX) &&
1953                             (item->folder->account != NULL) && 
1954                             (item->folder->account->filter_on_recv) &&
1955                             procmsg_msginfo_filter(msginfo,  item->folder->account))
1956                                 to_filter = g_slist_prepend(to_filter, msginfo);
1957                         else {
1958                                 exists_list = g_slist_prepend(exists_list, msginfo);
1959                                 
1960                                 if(prefs_common.thread_by_subject &&
1961                                         MSG_IS_IGNORE_THREAD(msginfo->flags) &&
1962                                         !subject_table_lookup(subject_table, msginfo->subject)) {
1963                                         subject_table_insert(subject_table, msginfo->subject, msginfo);
1964                                 }
1965                         }
1966                 }
1967                 filtering_move_and_copy_msgs(to_filter);
1968                 for (elem = to_filter; elem; elem = g_slist_next(elem)) {
1969                         MsgInfo *msginfo = (MsgInfo *)elem->data;
1970                         procmsg_msginfo_free(msginfo);
1971                 }
1972
1973                 g_slist_free(to_filter);
1974                 g_slist_free(newmsg_list);
1975
1976                 statusbar_progress_all(0,0,0);
1977                 statusbar_pop_all();
1978                 update_flags |= F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT;
1979         }
1980
1981         folder_item_set_batch(item, TRUE);
1982         for (elem = exists_list; elem != NULL; elem = g_slist_next(elem)) {
1983                 MsgInfo *msginfo, *parent_msginfo;
1984
1985                 msginfo = elem->data;
1986                 if (MSG_IS_IGNORE_THREAD(msginfo->flags) && (MSG_IS_NEW(msginfo->flags) || MSG_IS_UNREAD(msginfo->flags)))
1987                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
1988                 if (!MSG_IS_IGNORE_THREAD(msginfo->flags) && procmsg_msg_has_flagged_parent(msginfo, MSG_IGNORE_THREAD)) {
1989                         procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0, MSG_NEW | MSG_UNREAD, 0);
1990                 }
1991                 if(prefs_common.thread_by_subject && !msginfo->inreplyto &&
1992                         !msginfo->references && !MSG_IS_IGNORE_THREAD(msginfo->flags) &&
1993                         (parent_msginfo = subject_table_lookup(subject_table, msginfo->subject)))
1994                 {
1995                         if(MSG_IS_IGNORE_THREAD(parent_msginfo->flags)) {
1996                                 procmsg_msginfo_change_flags(msginfo, MSG_IGNORE_THREAD, 0,
1997                                                 MSG_NEW | MSG_UNREAD, 0);
1998                         }
1999                 }
2000                 if ((folder_has_parent_of_type(item, F_OUTBOX) ||
2001                      folder_has_parent_of_type(item, F_QUEUE)  ||
2002                      folder_has_parent_of_type(item, F_DRAFT)  ||
2003                      folder_has_parent_of_type(item, F_TRASH)) &&
2004                     (MSG_IS_NEW(msginfo->flags) || MSG_IS_UNREAD(msginfo->flags)))
2005                         procmsg_msginfo_unset_flags(msginfo, MSG_NEW | MSG_UNREAD, 0);
2006                 if (MSG_IS_NEW(msginfo->flags))
2007                         newcnt++;
2008                 if (MSG_IS_UNREAD(msginfo->flags))
2009                         unreadcnt++;
2010                 if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2011                         unreadmarkedcnt++;
2012                 if (MSG_IS_MARKED(msginfo->flags))
2013                         markedcnt++;
2014
2015                 totalcnt++;
2016
2017                 procmsg_msginfo_free(msginfo);
2018         }
2019         folder_item_set_batch(item, FALSE);
2020         g_slist_free(exists_list);
2021         
2022         if(prefs_common.thread_by_subject) {
2023                 g_hash_table_destroy(subject_table);
2024         }
2025         
2026         if (item->new_msgs != newcnt || item->unread_msgs != unreadcnt
2027         ||  item->total_msgs != totalcnt || item->marked_msgs != markedcnt
2028         ||  item->unreadmarked_msgs != unreadmarkedcnt) {
2029                 update_flags |= F_ITEM_UPDATE_CONTENT;
2030         }
2031
2032         item->new_msgs = newcnt;
2033         item->unread_msgs = unreadcnt;
2034         item->total_msgs = totalcnt;
2035         item->unreadmarked_msgs = unreadmarkedcnt;
2036         item->marked_msgs = markedcnt;
2037
2038         update_flags |= F_ITEM_UPDATE_MSGCNT;
2039
2040         folder_item_update(item, update_flags);
2041         folder_item_update_thaw();
2042         
2043         item->scanning = FALSE;
2044
2045         return 0;
2046 }
2047
2048 gint folder_item_scan(FolderItem *item)
2049 {
2050         return folder_item_scan_full(item, TRUE);
2051 }
2052
2053 static gboolean folder_scan_all_items_func(GNode *node, gpointer data)
2054 {
2055         FolderItem *item = node->data;
2056
2057         folder_item_scan(item);
2058
2059         return FALSE;
2060 }
2061
2062 void folder_scan_all_items(Folder * folder)
2063 {
2064         g_node_traverse(folder->node, G_PRE_ORDER,
2065                         G_TRAVERSE_ALL, -1, folder_scan_all_items_func, NULL);
2066 }
2067
2068 static void folder_item_scan_foreach_func(gpointer key, gpointer val,
2069                                           gpointer data)
2070 {
2071         folder_item_scan(FOLDER_ITEM(key));
2072 }
2073
2074 void folder_item_scan_foreach(GHashTable *table)
2075 {
2076         g_hash_table_foreach(table, folder_item_scan_foreach_func, NULL);
2077 }
2078
2079 void folder_count_total_cache_memusage(FolderItem *item, gpointer data)
2080 {
2081         gint *memusage = (gint *)data;
2082
2083         if (item->cache == NULL)
2084                 return;
2085         
2086         *memusage += msgcache_get_memory_usage(item->cache);
2087 }
2088
2089 gint folder_item_syncronize_flags(FolderItem *item)
2090 {
2091         MsgInfoList *msglist = NULL;
2092         GSList *cur;
2093         gint ret = 0;
2094         
2095         g_return_val_if_fail(item != NULL, -1);
2096         g_return_val_if_fail(item->folder != NULL, -1);
2097         g_return_val_if_fail(item->folder->klass != NULL, -1);
2098         if (item->no_select)
2099                 return -1;
2100
2101         item->scanning = TRUE;
2102
2103         if (item->cache == NULL)
2104                 folder_item_read_cache(item);
2105         
2106         msglist = msgcache_get_msg_list(item->cache);
2107         
2108         ret = syncronize_flags(item, msglist);
2109
2110         for (cur = msglist; cur != NULL; cur = g_slist_next(cur))
2111                 procmsg_msginfo_free((MsgInfo *) cur->data);
2112         
2113         g_slist_free(msglist);
2114
2115         item->scanning = FALSE;
2116
2117         return ret;
2118 }
2119
2120 gint folder_cache_time_compare_func(gconstpointer a, gconstpointer b)
2121 {
2122         FolderItem *fa = (FolderItem *)a;
2123         FolderItem *fb = (FolderItem *)b;
2124         
2125         return (gint) (msgcache_get_last_access_time(fa->cache) - msgcache_get_last_access_time(fb->cache));
2126 }
2127
2128 void folder_find_expired_caches(FolderItem *item, gpointer data)
2129 {
2130         GSList **folder_item_list = (GSList **)data;
2131         gint difftime, expiretime;
2132         
2133         if (item->cache == NULL)
2134                 return;
2135
2136         if (item->opened > 0)
2137                 return;
2138
2139         difftime = (gint) (time(NULL) - msgcache_get_last_access_time(item->cache));
2140         expiretime = prefs_common.cache_min_keep_time * 60;
2141         debug_print("Cache unused time: %d (Expire time: %d)\n", difftime, expiretime);
2142
2143         if (difftime > expiretime && !item->opened && !item->processing_pending) {
2144                 *folder_item_list = g_slist_insert_sorted(*folder_item_list, item, folder_cache_time_compare_func);
2145         }
2146 }
2147
2148 gboolean folder_item_free_cache(FolderItem *item, gboolean force)
2149 {
2150         g_return_val_if_fail(item != NULL, TRUE);
2151         
2152         if (item->cache == NULL)
2153                 return TRUE;
2154         
2155         if (item->opened > 0 && !force)
2156                 return FALSE;
2157
2158         folder_item_write_cache(item);
2159         msgcache_destroy(item->cache);
2160         item->cache = NULL;
2161         return TRUE;
2162 }
2163
2164 void folder_clean_cache_memory_force(void)
2165 {
2166         int old_cache_max_mem_usage = prefs_common.cache_max_mem_usage;
2167         int old_cache_min_keep_time = prefs_common.cache_min_keep_time;
2168
2169         prefs_common.cache_max_mem_usage = 0;
2170         prefs_common.cache_min_keep_time = 0;
2171
2172         folder_clean_cache_memory(NULL);
2173
2174         prefs_common.cache_max_mem_usage = old_cache_max_mem_usage;
2175         prefs_common.cache_min_keep_time = old_cache_min_keep_time;
2176 }
2177
2178 void folder_clean_cache_memory(FolderItem *protected_item)
2179 {
2180         gint memusage = 0;
2181
2182         folder_func_to_all_folders(folder_count_total_cache_memusage, &memusage);       
2183         debug_print("Total cache memory usage: %d\n", memusage);
2184         
2185         if (memusage > (prefs_common.cache_max_mem_usage * 1024)) {
2186                 GSList *folder_item_list = NULL, *listitem;
2187                 
2188                 debug_print("Trying to free cache memory\n");
2189
2190                 folder_func_to_all_folders(folder_find_expired_caches, &folder_item_list);      
2191                 listitem = folder_item_list;
2192                 while((listitem != NULL) && (memusage > (prefs_common.cache_max_mem_usage * 1024))) {
2193                         FolderItem *item = (FolderItem *)(listitem->data);
2194                         gint cache_size = 0;
2195                         if (item == protected_item) {
2196                                 listitem = listitem->next;
2197                                 continue;
2198                         }
2199                         debug_print("Freeing cache memory for %s\n", item->path ? item->path : item->name);
2200                         cache_size = msgcache_get_memory_usage(item->cache);
2201                         if (folder_item_free_cache(item, FALSE))
2202                                 memusage -= cache_size;
2203
2204                         listitem = listitem->next;
2205                 }
2206                 g_slist_free(folder_item_list);
2207         }
2208 }
2209
2210 void folder_item_read_cache(FolderItem *item)
2211 {
2212         gchar *cache_file, *mark_file;
2213         START_TIMING("folder_item_read_cache");
2214         g_return_if_fail(item != NULL);
2215
2216         if (item->path != NULL) {
2217                 cache_file = folder_item_get_cache_file(item);
2218                 mark_file = folder_item_get_mark_file(item);
2219                 item->cache = msgcache_read_cache(item, cache_file);
2220                 if (!item->cache) {
2221                         MsgInfoList *list, *cur;
2222                         guint newcnt = 0, unreadcnt = 0;
2223                         guint markedcnt = 0, unreadmarkedcnt = 0;
2224                         MsgInfo *msginfo;
2225
2226                         item->cache = msgcache_new();
2227                         folder_item_scan_full(item, TRUE);
2228
2229                         msgcache_read_mark(item->cache, mark_file);
2230
2231                         list = msgcache_get_msg_list(item->cache);
2232                         for (cur = list; cur != NULL; cur = g_slist_next(cur)) {
2233                                 msginfo = cur->data;
2234
2235                                 if (MSG_IS_NEW(msginfo->flags))
2236                                         newcnt++;
2237                                 if (MSG_IS_UNREAD(msginfo->flags))
2238                                         unreadcnt++;
2239                                 if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2240                                         unreadmarkedcnt++;
2241                                 if (MSG_IS_MARKED(msginfo->flags))
2242                                         markedcnt++;
2243                         }
2244                         item->new_msgs = newcnt;
2245                         item->unread_msgs = unreadcnt;
2246                         item->unreadmarked_msgs = unreadmarkedcnt;
2247                         item->marked_msgs = markedcnt;
2248                         procmsg_msg_list_free(list);
2249                 } else
2250                         msgcache_read_mark(item->cache, mark_file);
2251
2252                 g_free(cache_file);
2253                 g_free(mark_file);
2254         } else {
2255                 item->cache = msgcache_new();
2256         }
2257         END_TIMING();
2258         folder_clean_cache_memory(item);
2259 }
2260
2261 void folder_item_write_cache(FolderItem *item)
2262 {
2263         gchar *cache_file, *mark_file;
2264         FolderItemPrefs *prefs;
2265         gint filemode = 0;
2266         gchar *id;
2267         time_t last_mtime = (time_t)0;
2268         gboolean need_scan = FALSE;
2269         
2270         if (!item || !item->path || !item->cache)
2271                 return;
2272
2273         if (FOLDER_TYPE(item->folder) == F_MH) {
2274                 last_mtime = item->mtime;
2275                 need_scan = item->folder->klass->scan_required(item->folder, item);
2276         }
2277
2278         id = folder_item_get_identifier(item);
2279         debug_print("Save cache for folder %s\n", id);
2280         g_free(id);
2281
2282         cache_file = folder_item_get_cache_file(item);
2283         mark_file = folder_item_get_mark_file(item);
2284         if (msgcache_write(cache_file, mark_file, item->cache) < 0) {
2285                 prefs = item->prefs;
2286                 if (prefs && prefs->enable_folder_chmod && prefs->folder_chmod) {
2287                         /* for cache file */
2288                         filemode = prefs->folder_chmod;
2289                         if (filemode & S_IRGRP) filemode |= S_IWGRP;
2290                         if (filemode & S_IROTH) filemode |= S_IWOTH;
2291                         chmod(cache_file, filemode);
2292                 }
2293         }
2294
2295         if (!need_scan && FOLDER_TYPE(item->folder) == F_MH) {
2296                 if (item->mtime == last_mtime)
2297                         item->mtime = time(NULL);
2298         }
2299
2300         g_free(cache_file);
2301         g_free(mark_file);
2302 }
2303
2304 MsgInfo *folder_item_get_msginfo(FolderItem *item, gint num)
2305 {
2306         Folder *folder;
2307         MsgInfo *msginfo = NULL;
2308         
2309         g_return_val_if_fail(item != NULL, NULL);
2310         if (item->no_select)
2311                 return NULL;
2312         folder = item->folder;
2313         if (!item->cache)
2314                 folder_item_read_cache(item);
2315         
2316         if ((msginfo = msgcache_get_msg(item->cache, num)) != NULL)
2317                 return msginfo;
2318         
2319         msginfo = get_msginfo(item, num);
2320         if (msginfo != NULL) {
2321                 msgcache_add_msg(item->cache, msginfo);
2322                 return msginfo;
2323         }
2324         
2325         return NULL;
2326 }
2327
2328 MsgInfo *folder_item_get_msginfo_by_msgid(FolderItem *item, const gchar *msgid)
2329 {
2330         Folder *folder;
2331         MsgInfo *msginfo;
2332         
2333         g_return_val_if_fail(item != NULL, NULL);
2334         g_return_val_if_fail(msgid != NULL, NULL);
2335         if (item->no_select)
2336                 return FALSE;
2337         
2338         folder = item->folder;
2339         if (!item->cache)
2340                 folder_item_read_cache(item);
2341         
2342         if ((msginfo = msgcache_get_msg_by_id(item->cache, msgid)) != NULL)
2343                 return msginfo;
2344
2345         return NULL;
2346 }
2347
2348 GSList *folder_item_get_msg_list(FolderItem *item)
2349 {
2350         g_return_val_if_fail(item != NULL, NULL);
2351         if (item->no_select)
2352                 return FALSE;
2353         
2354         if (item->cache == 0)
2355                 folder_item_read_cache(item);
2356
2357         g_return_val_if_fail(item->cache != NULL, NULL);
2358         
2359         return msgcache_get_msg_list(item->cache);
2360 }
2361
2362 void msginfo_set_mime_flags(GNode *node, gpointer data)
2363 {
2364         MsgInfo *msginfo = data;
2365         MimeInfo *mimeinfo = node->data;
2366         
2367         if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT
2368          && (!mimeinfo->subtype ||  strcmp(mimeinfo->subtype, "pgp-signature"))) {
2369                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2370         } else if (mimeinfo->disposition == DISPOSITIONTYPE_UNKNOWN && 
2371                  mimeinfo->type != MIMETYPE_TEXT &&
2372                  mimeinfo->type != MIMETYPE_MULTIPART) {
2373                 if (!mimeinfo->subtype 
2374                 ||  strcmp(mimeinfo->subtype, "pgp-signature"))
2375                         procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2376         } else if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE &&
2377                 strcmp(mimeinfo->subtype, "pgp-signature") && 
2378                 (procmime_mimeinfo_get_parameter(mimeinfo, "name") != NULL ||
2379                  procmime_mimeinfo_get_parameter(mimeinfo, "filename") != NULL)) {
2380                 procmsg_msginfo_set_flags(msginfo, 0, MSG_HAS_ATTACHMENT);
2381         } 
2382
2383         /* don't descend below top level message for signed and encrypted info */
2384         if (mimeinfo->type == MIMETYPE_MESSAGE)
2385                 return;
2386
2387         if (privacy_mimeinfo_is_signed(mimeinfo)) {
2388                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
2389         }
2390
2391         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
2392                 procmsg_msginfo_set_flags(msginfo, 0, MSG_ENCRYPTED);
2393         } else {
2394                 /* searching inside encrypted parts doesn't really make sense */
2395                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2396         }
2397 }
2398
2399 gchar *folder_item_fetch_msg(FolderItem *item, gint num)
2400 {
2401         Folder *folder;
2402         gchar *msgfile;
2403         MsgInfo *msginfo;
2404
2405         g_return_val_if_fail(item != NULL, NULL);
2406
2407         folder = item->folder;
2408
2409         g_return_val_if_fail(folder->klass->fetch_msg != NULL, NULL);
2410         if (item->no_select)
2411                 return NULL;
2412
2413         msgfile = folder->klass->fetch_msg(folder, item, num);
2414
2415         if (msgfile != NULL) {
2416                 msginfo = folder_item_get_msginfo(item, num);
2417                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2418                         MimeInfo *mimeinfo;
2419
2420                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) && 
2421                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2422                                 mimeinfo = procmime_scan_file(msgfile);
2423                         else
2424                                 mimeinfo = procmime_scan_queue_file(msgfile);
2425                         /* check for attachments */
2426                         if (mimeinfo != NULL) { 
2427                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2428                                 procmime_mimeinfo_free_all(mimeinfo);
2429
2430                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2431                         }
2432                 }
2433                 procmsg_msginfo_free(msginfo);
2434         }
2435
2436         return msgfile;
2437 }
2438
2439 gchar *folder_item_fetch_msg_full(FolderItem *item, gint num, gboolean headers,
2440                                   gboolean body)
2441 {
2442         Folder *folder;
2443         gchar *msgfile;
2444         MsgInfo *msginfo;
2445
2446         g_return_val_if_fail(item != NULL, NULL);
2447         if (item->no_select)
2448                 return NULL;
2449         
2450         folder = item->folder;
2451
2452         if (folder->klass->fetch_msg_full == NULL)
2453                 return folder_item_fetch_msg(item, num);
2454
2455         msgfile = folder->klass->fetch_msg_full(folder, item, num, 
2456                                                 headers, body);
2457
2458         if (msgfile != NULL) {
2459                 msginfo = folder_item_get_msginfo(item, num);
2460                 if ((msginfo != NULL) && !MSG_IS_SCANNED(msginfo->flags)) {
2461                         MimeInfo *mimeinfo;
2462
2463                         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
2464                             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
2465                                 mimeinfo = procmime_scan_file(msgfile);
2466                         else
2467                                 mimeinfo = procmime_scan_queue_file(msgfile);
2468                         /* check for attachments */
2469                         if (mimeinfo != NULL) { 
2470                                 g_node_children_foreach(mimeinfo->node, G_TRAVERSE_ALL, msginfo_set_mime_flags, msginfo);
2471                                 procmime_mimeinfo_free_all(mimeinfo);
2472
2473                                 procmsg_msginfo_set_flags(msginfo, 0, MSG_SCANNED);
2474                         }
2475                 }
2476                 procmsg_msginfo_free(msginfo);
2477         }
2478
2479         return msgfile;
2480 }
2481
2482
2483 gint folder_item_fetch_all_msg(FolderItem *item)
2484 {
2485         Folder *folder;
2486         GSList *mlist;
2487         GSList *cur;
2488         gint num = 0;
2489         gint ret = 0;
2490         gint total = 0;
2491
2492         g_return_val_if_fail(item != NULL, -1);
2493         if (item->no_select)
2494                 return -1;
2495
2496         debug_print("fetching all messages in %s ...\n", item->path ? item->path : "(null)");
2497         statusbar_print_all(_("Fetching all messages in %s ...\n"), item->path ? item->path : "(null)");
2498
2499         folder = item->folder;
2500
2501         if (folder->ui_func)
2502                 folder->ui_func(folder, item, folder->ui_func_data ?
2503                                 folder->ui_func_data : GINT_TO_POINTER(num));
2504
2505         mlist = folder_item_get_msg_list(item);
2506
2507         total = g_slist_length(mlist);
2508
2509         for (cur = mlist; cur != NULL; cur = cur->next) {
2510                 MsgInfo *msginfo = (MsgInfo *)cur->data;
2511                 gchar *msg;
2512
2513                 statusbar_progress_all(num++,total, 10);
2514
2515                 if (folder->ui_func)
2516                         folder->ui_func(folder, item,
2517                                         folder->ui_func_data ?
2518                                         folder->ui_func_data :
2519                                         GINT_TO_POINTER(num));
2520
2521                 msg = folder_item_fetch_msg(item, msginfo->msgnum);
2522                 if (!msg) {
2523                         g_warning("Can't fetch message %d. Aborting.\n",
2524                                   msginfo->msgnum);
2525                         ret = -1;
2526                         break;
2527                 }
2528                 g_free(msg);
2529         }
2530         
2531         statusbar_progress_all(0,0,0);
2532         statusbar_pop_all();
2533         procmsg_msg_list_free(mlist);
2534
2535         return ret;
2536 }
2537
2538 static gint folder_item_get_msg_num_by_file(FolderItem *dest, const gchar *file)
2539 {
2540         static HeaderEntry hentry[] = {{"Message-ID:",  NULL, TRUE},
2541                                        {NULL,           NULL, FALSE}};
2542         FILE *fp;
2543         MsgInfo *msginfo;
2544         gint msgnum = 0;
2545         gchar buf[BUFFSIZE];
2546
2547         if ((fp = g_fopen(file, "rb")) == NULL)
2548                 return 0;
2549
2550         if ((folder_has_parent_of_type(dest, F_QUEUE)) || 
2551             (folder_has_parent_of_type(dest, F_DRAFT)))
2552                 while (fgets(buf, sizeof(buf), fp) != NULL)
2553                         if (buf[0] == '\r' || buf[0] == '\n') break;
2554
2555         procheader_get_header_fields(fp, hentry);
2556         if (hentry[0].body) {
2557                 extract_parenthesis(hentry[0].body, '<', '>');
2558                 remove_space(hentry[0].body);
2559                 if ((msginfo = msgcache_get_msg_by_id(dest->cache, hentry[0].body)) != NULL) {
2560                         msgnum = msginfo->msgnum;
2561                         procmsg_msginfo_free(msginfo);
2562
2563                         debug_print("found message as uid %d\n", msgnum);
2564                 }
2565         }
2566         
2567         g_free(hentry[0].body);
2568         hentry[0].body = NULL;
2569         fclose(fp);
2570
2571         return msgnum;
2572 }
2573
2574 static void copy_msginfo_flags(MsgInfo *source, MsgInfo *dest)
2575 {
2576         MsgPermFlags perm_flags = 0;
2577         MsgTmpFlags tmp_flags = 0;
2578
2579         /* create new flags */
2580         if (source != NULL) {
2581                 /* copy original flags */
2582                 perm_flags = source->flags.perm_flags;
2583                 tmp_flags = source->flags.tmp_flags;
2584         } else {
2585                 perm_flags = dest->flags.perm_flags;
2586                 tmp_flags = dest->flags.tmp_flags;
2587         }
2588
2589         /* remove new, unread and deleted in special folders */
2590         if (folder_has_parent_of_type(dest->folder, F_OUTBOX) || 
2591             folder_has_parent_of_type(dest->folder, F_QUEUE) || 
2592             folder_has_parent_of_type(dest->folder, F_DRAFT) || 
2593             folder_has_parent_of_type(dest->folder, F_TRASH))
2594                 perm_flags &= ~(MSG_NEW | MSG_UNREAD | MSG_DELETED);
2595
2596         /* set ignore flag of ignored parent exists */
2597         if (procmsg_msg_has_flagged_parent(dest, MSG_IGNORE_THREAD))
2598                 perm_flags |= MSG_IGNORE_THREAD;
2599
2600         /* Unset tmp flags that should not be copied */
2601         tmp_flags &= ~(MSG_MOVE | MSG_COPY | MSG_MOVE_DONE);
2602
2603         /* unset flags that are set but should not */
2604         /* and set new flags */
2605         procmsg_msginfo_change_flags(dest,
2606                                   ~dest->flags.perm_flags & perm_flags,
2607                                   ~dest->flags.tmp_flags  & tmp_flags,
2608                                    dest->flags.perm_flags & ~perm_flags,
2609                                    dest->flags.tmp_flags  & ~tmp_flags);
2610 }
2611
2612 static void add_msginfo_to_cache(FolderItem *item, MsgInfo *newmsginfo, MsgInfo *flagsource)
2613 {
2614         /* update folder stats */
2615         if (MSG_IS_NEW(newmsginfo->flags))
2616                 item->new_msgs++;
2617         if (MSG_IS_UNREAD(newmsginfo->flags))
2618                 item->unread_msgs++;
2619         if (MSG_IS_UNREAD(newmsginfo->flags) && procmsg_msg_has_marked_parent(newmsginfo))
2620                 item->unreadmarked_msgs++;
2621         if (MSG_IS_MARKED(newmsginfo->flags))
2622                 item->marked_msgs++;
2623         item->total_msgs++;
2624
2625         folder_item_update_freeze();
2626
2627         if (!item->cache)
2628                 folder_item_read_cache(item);
2629
2630         msgcache_add_msg(item->cache, newmsginfo);
2631         copy_msginfo_flags(flagsource, newmsginfo);
2632         folder_item_update_with_msg(item,  F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_ADDMSG, newmsginfo);
2633         folder_item_update_thaw();
2634 }
2635
2636 static void remove_msginfo_from_cache(FolderItem *item, MsgInfo *msginfo)
2637 {
2638         MsgInfoUpdate msginfo_update;
2639
2640         if (!item->cache)
2641                 folder_item_read_cache(item);
2642
2643         if (MSG_IS_NEW(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
2644                 msginfo->folder->new_msgs--;
2645         if (MSG_IS_UNREAD(msginfo->flags) && !MSG_IS_IGNORE_THREAD(msginfo->flags))
2646                 msginfo->folder->unread_msgs--;
2647         if (MSG_IS_UNREAD(msginfo->flags) && procmsg_msg_has_marked_parent(msginfo))
2648                 msginfo->folder->unreadmarked_msgs--;
2649         if (MSG_IS_MARKED(msginfo->flags))
2650                 item->marked_msgs--;
2651
2652         msginfo->folder->total_msgs--;
2653
2654         msginfo_update.msginfo = msginfo;
2655         msginfo_update.flags = MSGINFO_UPDATE_DELETED;
2656         hooks_invoke(MSGINFO_UPDATE_HOOKLIST, &msginfo_update);
2657
2658         msgcache_remove_msg(item->cache, msginfo->msgnum);
2659         folder_item_update_with_msg(msginfo->folder, F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT | F_ITEM_UPDATE_REMOVEMSG, msginfo);
2660 }
2661
2662 gint folder_item_add_msg(FolderItem *dest, const gchar *file,
2663                          MsgFlags *flags, gboolean remove_source)
2664 {
2665         GSList file_list;
2666         MsgFileInfo fileinfo;
2667
2668         g_return_val_if_fail(dest != NULL, -1);
2669         g_return_val_if_fail(file != NULL, -1);
2670  
2671         fileinfo.msginfo = NULL;
2672         fileinfo.file = (gchar *)file;
2673         fileinfo.flags = flags;
2674         file_list.data = &fileinfo;
2675         file_list.next = NULL;
2676
2677         return folder_item_add_msgs(dest, &file_list, remove_source);
2678 }
2679
2680 gint folder_item_add_msgs(FolderItem *dest, GSList *file_list,
2681                           gboolean remove_source)
2682 {
2683         Folder *folder;
2684         gint ret, num, lastnum = -1;
2685         GSList *file_cur;
2686         GRelation *relation;
2687         MsgFileInfo *fileinfo = NULL;
2688         gboolean folderscan = FALSE;
2689
2690         g_return_val_if_fail(dest != NULL, -1);
2691         g_return_val_if_fail(file_list != NULL, -1);
2692         g_return_val_if_fail(dest->folder != NULL, -1);
2693         if (dest->no_select)
2694                 return -1;
2695
2696         folder = dest->folder;
2697
2698         relation = g_relation_new(2);
2699         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
2700
2701         if (folder->klass->add_msgs != NULL) {
2702                 ret = folder->klass->add_msgs(folder, dest, file_list, relation);
2703                 if (ret < 0) {
2704                         g_relation_destroy(relation);
2705                         return ret;
2706                 }
2707         } else {
2708                 for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
2709                         fileinfo = (MsgFileInfo *) file_cur->data;
2710
2711                         ret = folder->klass->add_msg(folder, dest, fileinfo->file, fileinfo->flags);
2712                         if (ret < 0) {
2713                                 g_relation_destroy(relation);
2714                                 return ret;
2715                         }
2716                         g_relation_insert(relation, fileinfo, GINT_TO_POINTER(ret));
2717                 }
2718         }
2719
2720         for (file_cur = file_list; file_cur != NULL; file_cur = g_slist_next(file_cur)) {
2721                 GTuples *tuples;
2722
2723                 fileinfo = (MsgFileInfo *) file_cur->data;
2724                 tuples = g_relation_select(relation, fileinfo, 0);
2725                 num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
2726                 g_tuples_destroy(tuples);
2727
2728                 if (num >= 0) {
2729                         MsgInfo *newmsginfo;
2730
2731                         if (num == 0) {
2732                                 if (!folderscan) {
2733                                         folder_item_scan_full(dest, FALSE);
2734                                         folderscan = TRUE;
2735                                 }
2736                                 num = folder_item_get_msg_num_by_file(dest, fileinfo->file);
2737                         }
2738
2739                         if (num > lastnum)
2740                                 lastnum = num;
2741
2742                         if (num >= 0 && remove_source) {
2743                                 if (g_unlink(fileinfo->file) < 0)
2744                                         FILE_OP_ERROR(fileinfo->file, "unlink");
2745                         }
2746
2747                         if (num == 0)
2748                                 continue;
2749
2750                         if (!folderscan && 
2751                             ((newmsginfo = get_msginfo(dest, num)) != NULL)) {
2752                                 add_msginfo_to_cache(dest, newmsginfo, NULL);
2753                                 procmsg_msginfo_free(newmsginfo);
2754                         } else if ((newmsginfo = msgcache_get_msg(dest->cache, num)) != NULL) {
2755                                 /* TODO: set default flags */
2756                                 procmsg_msginfo_free(newmsginfo);
2757                         }
2758                 }
2759         }
2760
2761         g_relation_destroy(relation);
2762
2763         return lastnum;
2764 }
2765                 
2766 FolderItem *folder_item_move_recursive(FolderItem *src, FolderItem *dest) 
2767 {
2768         GSList *mlist;
2769         FolderItem *new_item;
2770         FolderItem *next_item;
2771         GNode *srcnode;
2772         gchar *old_id, *new_id;
2773
2774         /* move messages */
2775         debug_print("Moving %s to %s\n", src->path, dest->path);
2776         new_item = folder_create_folder(dest, src->name);
2777         if (new_item == NULL) {
2778                 printf("Can't create folder\n");
2779                 return NULL;
2780         }
2781         
2782         if (new_item->folder == NULL)
2783                 new_item->folder = dest->folder;
2784
2785         /* move messages */
2786         log_message(_("Moving %s to %s...\n"), 
2787                         src->name, new_item->path);
2788
2789         mlist = folder_item_get_msg_list(src);
2790         
2791         if (mlist != NULL) {
2792                 folder_item_move_msgs(new_item, mlist);
2793                 procmsg_msg_list_free(mlist);
2794         }
2795         
2796         /*copy prefs*/
2797         folder_item_prefs_copy_prefs(src, new_item);
2798         new_item->collapsed = src->collapsed;
2799         new_item->thread_collapsed = src->thread_collapsed;
2800         new_item->threaded  = src->threaded;
2801         new_item->ret_rcpt  = src->ret_rcpt;
2802         new_item->hide_read_msgs = src->hide_read_msgs;
2803         new_item->sort_key  = src->sort_key;
2804         new_item->sort_type = src->sort_type;
2805
2806         prefs_matcher_write_config();
2807         
2808         /* recurse */
2809         srcnode = src->folder->node;    
2810         srcnode = g_node_find(srcnode, G_PRE_ORDER, G_TRAVERSE_ALL, src);
2811         srcnode = srcnode->children;
2812         while (srcnode != NULL) {
2813                 if (srcnode && srcnode->data) {
2814                         next_item = (FolderItem*) srcnode->data;
2815                         srcnode = srcnode->next;
2816                         if (folder_item_move_recursive(next_item, new_item) == NULL) {
2817                                 return NULL;
2818                         }
2819                 }
2820         }
2821         old_id = folder_item_get_identifier(src);
2822         new_id = folder_item_get_identifier(new_item);
2823         debug_print("updating rules : %s => %s\n", old_id, new_id);
2824
2825         /* if src supports removing, otherwise only copy folder */
2826         if (src->folder->klass->remove_folder != NULL)  
2827                 src->folder->klass->remove_folder(src->folder, src);
2828         folder_write_list();
2829
2830         if (old_id != NULL && new_id != NULL) {
2831                 prefs_filtering_rename_path(old_id, new_id);
2832                 account_rename_path(old_id, new_id);
2833         }
2834         g_free(old_id);
2835         g_free(new_id);
2836         
2837         return new_item;
2838 }
2839
2840 gint folder_item_move_to(FolderItem *src, FolderItem *dest, FolderItem **new_item)
2841 {
2842         FolderItem *tmp = folder_item_parent(dest);
2843         gchar * src_identifier, * dst_identifier;
2844         gchar * phys_srcpath, * phys_dstpath, *tmppath;
2845         
2846         while (tmp) {
2847                 if (tmp == src) {
2848                         return F_MOVE_FAILED_DEST_IS_CHILD;
2849                 }
2850                 tmp = folder_item_parent(tmp);
2851         }
2852         
2853         tmp = folder_item_parent(src);
2854         
2855         src_identifier = folder_item_get_identifier(src);
2856         dst_identifier = folder_item_get_identifier(dest);
2857         
2858         if(dst_identifier == NULL && dest->folder && folder_item_parent(dest) == NULL) {
2859                 /* dest can be a root folder */
2860                 dst_identifier = folder_get_identifier(dest->folder);
2861         }
2862         if (src_identifier == NULL || dst_identifier == NULL) {
2863                 debug_print("Can't get identifiers\n");
2864                 return F_MOVE_FAILED;
2865         }
2866
2867         if (src->folder != dest->folder) {
2868                 return F_MOVE_FAILED_DEST_OUTSIDE_MAILBOX;
2869         }
2870
2871         phys_srcpath = folder_item_get_path(src);
2872         tmppath = folder_item_get_path(dest);
2873         phys_dstpath = g_strconcat(tmppath,
2874                        G_DIR_SEPARATOR_S,
2875                        g_path_get_basename(phys_srcpath),
2876                        NULL);
2877         g_free(tmppath);
2878
2879         if (folder_item_parent(src) == dest || src == dest) {
2880                 g_free(src_identifier);
2881                 g_free(dst_identifier);
2882                 g_free(phys_srcpath);
2883                 g_free(phys_dstpath);
2884                 return F_MOVE_FAILED_DEST_IS_PARENT;
2885         }
2886         debug_print("moving \"%s\" to \"%s\"\n", phys_srcpath, phys_dstpath);
2887         if ((tmp = folder_item_move_recursive(src, dest)) == NULL) {
2888                 return F_MOVE_FAILED;
2889         }
2890         
2891         g_free(src_identifier);
2892         g_free(dst_identifier);
2893         g_free(phys_srcpath);
2894         g_free(phys_dstpath);
2895
2896         *new_item = tmp;
2897
2898         return F_MOVE_OK;
2899 }
2900
2901 /**
2902  * Copy a list of message to a new folder and remove
2903  * source messages if wanted
2904  */
2905 static gint do_copy_msgs(FolderItem *dest, GSList *msglist, gboolean remove_source)
2906 {
2907         Folder *folder;
2908         GSList *l;
2909         gint num, lastnum = -1;
2910         gboolean folderscan = FALSE;
2911         GRelation *relation;
2912         GSList *not_moved = NULL;
2913         gint total = 0, curmsg = 0;
2914         MsgInfo *msginfo = NULL;
2915
2916         g_return_val_if_fail(dest != NULL, -1);
2917         g_return_val_if_fail(msglist != NULL, -1);
2918
2919         folder = dest->folder;
2920
2921         g_return_val_if_fail(folder->klass->copy_msg != NULL, -1);
2922         if (dest->no_select)
2923                 return -1;
2924
2925         msginfo = (MsgInfo *)msglist->data;
2926         
2927         if (!msginfo)
2928                 return -1;
2929         
2930         if (!MSG_IS_QUEUED(msginfo->flags) && 
2931             MSG_IS_DRAFT(msginfo->flags) && 
2932             folder_has_parent_of_type(dest, F_QUEUE)) {
2933                 GSList *cur = msglist;
2934                 gboolean queue_err = FALSE;
2935                 for (; cur; cur = cur->next) {
2936                         Compose *compose = NULL;
2937                         FolderItem *queue = dest;
2938                         int val = 0;
2939                         
2940                         msginfo = (MsgInfo *)cur->data;
2941                         compose = compose_reedit(msginfo, TRUE);
2942                         if (compose == NULL) {
2943                                 queue_err = TRUE;
2944                                 continue;
2945                         }
2946                         val = compose_queue(compose, NULL, &queue, NULL,
2947                                         FALSE);
2948                         if (val < 0) {
2949                                 queue_err = TRUE;
2950                         } else if (remove_source) {
2951                                 folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
2952                         }
2953                         if (val == 0)
2954                                 compose_close(compose);
2955                 }
2956                 return queue_err ? -1:0;
2957         }
2958
2959         relation = g_relation_new(2);
2960         g_relation_index(relation, 0, g_direct_hash, g_direct_equal);
2961         g_relation_index(relation, 1, g_direct_hash, g_direct_equal);
2962
2963         for (l = msglist ; l != NULL ; l = g_slist_next(l)) {
2964                 MsgInfo * msginfo = (MsgInfo *) l->data;
2965
2966                 if (msginfo->planned_download != 0) {
2967                         int old_planned = msginfo->planned_download;
2968                         partial_unmark(msginfo);
2969                         /* little hack to reenable after */
2970                         msginfo->planned_download = old_planned;
2971                 }
2972         }
2973
2974         /* 
2975          * Copy messages to destination folder and 
2976          * store new message numbers in newmsgnums
2977          */
2978         if (folder->klass->copy_msgs != NULL) {
2979                 if (folder->klass->copy_msgs(folder, dest, msglist, relation) < 0) {
2980                         g_relation_destroy(relation);
2981                         return -1;
2982                 }
2983         } else {
2984                 MsgInfo * msginfo;
2985                 l = msglist;
2986
2987                 /* immediately stop if src and dest folders are identical */
2988                 if (l != NULL) {
2989                         msginfo = (MsgInfo *) l->data;
2990                         if (msginfo != NULL && msginfo->folder == dest) {
2991                                 g_relation_destroy(relation);
2992                                 return -1;
2993                         }
2994                 }
2995
2996                 for (; l != NULL ; l = g_slist_next(l)) {
2997                         msginfo = (MsgInfo *) l->data;
2998
2999                         num = folder->klass->copy_msg(folder, dest, msginfo);
3000                         if (num > 0)
3001                                 g_relation_insert(relation, msginfo, GINT_TO_POINTER(num));
3002                         else
3003                                 not_moved = g_slist_prepend(not_moved, msginfo);
3004                 }
3005         }
3006
3007         if (remove_source) {
3008                 MsgInfo *msginfo = (MsgInfo *) msglist->data;
3009                 FolderItem *item = msginfo->folder;
3010                 /*
3011                  * Remove source messages from their folders if
3012                  * copying was successfull and update folder
3013                  * message counts
3014                  */
3015                 if (item->folder->klass->remove_msgs) {
3016                         item->folder->klass->remove_msgs(item->folder,
3017                                                                 msginfo->folder,
3018                                                                 msglist,
3019                                                                 relation);
3020                 }
3021                 for (l = msglist; l != NULL; l = g_slist_next(l)) {
3022                         GTuples *tuples;
3023                         msginfo = (MsgInfo *) l->data;
3024                         item = msginfo->folder;
3025
3026                         tuples = g_relation_select(relation, msginfo, 0);
3027                         num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
3028                         g_tuples_destroy(tuples);
3029
3030                         if (g_slist_find(not_moved, msginfo))
3031                                 continue;
3032
3033                         if ((num >= 0) && (item->folder->klass->remove_msg != NULL)) {
3034                                 if (!item->folder->klass->remove_msgs)
3035                                         item->folder->klass->remove_msg(item->folder,
3036                                                                 msginfo->folder,
3037                                                                 msginfo->msgnum);
3038                                 remove_msginfo_from_cache(item, msginfo);
3039                         }
3040                 }
3041         }
3042
3043         /* Read cache for dest folder */
3044         if (!dest->cache) folder_item_read_cache(dest);
3045
3046         /* 
3047          * Fetch new MsgInfos for new messages in dest folder,
3048          * add them to the msgcache and update folder message counts
3049          */
3050         if (g_relation_count(relation, GINT_TO_POINTER(0), 1) > 0) {
3051                 folder_item_scan_full(dest, FALSE);
3052                 folderscan = TRUE;
3053         }
3054
3055         statusbar_print_all(_("Updating cache for %s..."), dest->path ? dest->path : "(null)");
3056         total = g_slist_length(msglist);
3057         for (l = msglist; l != NULL; l = g_slist_next(l)) {
3058                 MsgInfo *msginfo = (MsgInfo *) l->data;
3059                 GTuples *tuples;
3060
3061                 tuples = g_relation_select(relation, msginfo, 0);
3062                 num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
3063                 g_tuples_destroy(tuples);
3064
3065                 statusbar_progress_all(curmsg++,total, 100);
3066                 if (curmsg % 100 == 0)
3067                         GTK_EVENTS_FLUSH();
3068
3069                 if (num >= 0) {
3070                         MsgInfo *newmsginfo = NULL;
3071
3072                         if (folderscan) {
3073                                 if (msginfo->msgid != NULL) {
3074                                         newmsginfo = folder_item_get_msginfo_by_msgid(dest, msginfo->msgid);
3075                                         if (newmsginfo != NULL) {
3076                                                 copy_msginfo_flags(msginfo, newmsginfo);
3077                                                 num = newmsginfo->msgnum;
3078                                         }
3079                                 }
3080                         } else {
3081                                 newmsginfo = get_msginfo(dest, num);
3082                                 if (newmsginfo != NULL) {
3083                                         add_msginfo_to_cache(dest, newmsginfo, msginfo);
3084                                 }
3085                         }
3086
3087                         if (msginfo->planned_download 
3088                             == POP3_PARTIAL_DLOAD_DELE) {
3089                                 partial_mark_for_delete(newmsginfo);
3090                         }
3091                         if (msginfo->planned_download 
3092                             == POP3_PARTIAL_DLOAD_DLOAD) {
3093                                 partial_mark_for_download(newmsginfo);
3094                         }
3095                         if (!MSG_IS_POSTFILTERED (msginfo->flags)) {
3096                             procmsg_msginfo_set_flags (   msginfo, MSG_POSTFILTERED, 0);
3097                             procmsg_msginfo_set_flags (newmsginfo, MSG_POSTFILTERED, 0);
3098                             hooks_invoke (MAIL_POSTFILTERING_HOOKLIST, newmsginfo);
3099                         }
3100                         procmsg_msginfo_free(newmsginfo);
3101
3102
3103                         if (num > lastnum)
3104                                 lastnum = num;
3105                 }
3106         }
3107         statusbar_progress_all(0,0,0);
3108         statusbar_pop_all();
3109
3110         g_relation_destroy(relation);
3111         if (not_moved != NULL) {
3112                 g_slist_free(not_moved);
3113                 return -1;
3114         } else
3115                 return lastnum;
3116 }
3117
3118 /**
3119  * Move a message to a new folder.
3120  *
3121  * \param dest Destination folder
3122  * \param msginfo The message
3123  */
3124 gint folder_item_move_msg(FolderItem *dest, MsgInfo *msginfo)
3125 {
3126         GSList list;
3127
3128         g_return_val_if_fail(dest != NULL, -1);
3129         g_return_val_if_fail(msginfo != NULL, -1);
3130
3131         list.data = msginfo;
3132         list.next = NULL;
3133
3134         return do_copy_msgs(dest, &list, TRUE);
3135 }
3136
3137 /**
3138  * Move a list of messages to a new folder.
3139  *
3140  * \param dest Destination folder
3141  * \param msglist List of messages
3142  */
3143 gint folder_item_move_msgs(FolderItem *dest, GSList *msglist)
3144 {
3145         gint result = -1;
3146         g_return_val_if_fail(dest != NULL, -1);
3147         g_return_val_if_fail(msglist != NULL, -1);
3148         inc_lock();
3149         result = do_copy_msgs(dest, msglist, TRUE);
3150         inc_unlock();
3151         return result;
3152 }
3153
3154 /**
3155  * Copy a message to a new folder.
3156  *
3157  * \param dest Destination folder
3158  * \param msginfo The message
3159  */
3160 gint folder_item_copy_msg(FolderItem *dest, MsgInfo *msginfo)
3161 {
3162         GSList list;
3163
3164         g_return_val_if_fail(dest != NULL, -1);
3165         g_return_val_if_fail(msginfo != NULL, -1);
3166     
3167         list.data = msginfo;
3168         list.next = NULL;
3169
3170         return do_copy_msgs(dest, &list, FALSE);
3171 }
3172
3173 /**
3174  * Copy a list of messages to a new folder.
3175  *
3176  * \param dest Destination folder
3177  * \param msglist List of messages
3178  */
3179 gint folder_item_copy_msgs(FolderItem *dest, GSList *msglist)
3180 {
3181         gint result;
3182         g_return_val_if_fail(dest != NULL, -1);
3183         g_return_val_if_fail(msglist != NULL, -1);
3184
3185         inc_lock();
3186         result = do_copy_msgs(dest, msglist, FALSE);
3187         inc_unlock();
3188         
3189         return result;
3190 }
3191
3192 gint folder_item_remove_msg(FolderItem *item, gint num)
3193 {
3194         Folder *folder;
3195         gint ret;
3196         MsgInfo *msginfo;
3197
3198         g_return_val_if_fail(item != NULL, -1);
3199         folder = item->folder;
3200         g_return_val_if_fail(folder->klass->remove_msg != NULL, -1);
3201         if (item->no_select)
3202                 return -1;
3203
3204         if (!item->cache) folder_item_read_cache(item);
3205
3206         ret = folder->klass->remove_msg(folder, item, num);
3207
3208         msginfo = msgcache_get_msg(item->cache, num);
3209         if (msginfo != NULL) {
3210                 remove_msginfo_from_cache(item, msginfo);
3211                 procmsg_msginfo_free(msginfo);
3212         }
3213
3214         return ret;
3215 }
3216
3217 gint folder_item_remove_msgs(FolderItem *item, GSList *msglist)
3218 {
3219         Folder *folder;
3220         gint ret = 0;
3221
3222         g_return_val_if_fail(item != NULL, -1);
3223         folder = item->folder;
3224         g_return_val_if_fail(folder != NULL, -1);
3225         if (item->no_select)
3226                 return -1;
3227         inc_lock();
3228         if (!item->cache) folder_item_read_cache(item);
3229
3230         folder_item_update_freeze();
3231         if (item->folder->klass->remove_msgs) {
3232                 ret = item->folder->klass->remove_msgs(item->folder,
3233                                                         item,
3234                                                         msglist,
3235                                                         NULL);
3236         }
3237         while (ret == 0 && msglist != NULL) {
3238                 MsgInfo *msginfo = (MsgInfo *)msglist->data;
3239                 if (MSG_IS_LOCKED(msginfo->flags)) {
3240                         msglist = msglist->next;
3241                         continue;
3242                 }
3243                 if (!item->folder->klass->remove_msgs)
3244                         ret = folder_item_remove_msg(item, msginfo->msgnum);
3245                 if (ret != 0) break;
3246                 msgcache_remove_msg(item->cache, msginfo->msgnum);
3247                 msglist = msglist->next;
3248         }
3249         folder_item_scan_full(item, FALSE);
3250         folder_item_update_thaw();
3251         inc_unlock();
3252         return ret;
3253 }
3254
3255 gint folder_item_remove_all_msg(FolderItem *item)
3256 {
3257         Folder *folder;
3258         gint result;
3259
3260         g_return_val_if_fail(item != NULL, -1);
3261         if (item->no_select)
3262                 return -1;
3263
3264         folder = item->folder;
3265
3266         inc_lock();
3267         if (folder->klass->remove_all_msg != NULL) {
3268                 result = folder->klass->remove_all_msg(folder, item);
3269
3270                 if (result == 0) {
3271                         folder_item_free_cache(item, TRUE);
3272                         item->cache = msgcache_new();
3273                 }
3274         } else {
3275                 MsgInfoList *msglist;
3276
3277                 msglist = folder_item_get_msg_list(item);
3278                 result = folder_item_remove_msgs(item, msglist);
3279                 procmsg_msg_list_free(msglist);
3280         }
3281
3282         if (result == 0) {
3283                 item->new_msgs = 0;
3284                 item->unread_msgs = 0;
3285                 item->unreadmarked_msgs = 0;
3286                 item->marked_msgs = 0;
3287                 item->total_msgs = 0;
3288                 folder_item_update(item, F_ITEM_UPDATE_MSGCNT | F_ITEM_UPDATE_CONTENT);
3289         }
3290
3291         inc_unlock();
3292         return result;
3293 }
3294
3295 void folder_item_change_msg_flags(FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
3296 {
3297         g_return_if_fail(item != NULL);
3298         g_return_if_fail(msginfo != NULL);
3299         if (item->no_select)
3300                 return;
3301         
3302         if (item->folder->klass->change_flags != NULL) {
3303                 item->folder->klass->change_flags(item->folder, item, msginfo, newflags);
3304         } else {
3305                 msginfo->flags.perm_flags = newflags;
3306         }
3307 }
3308
3309 gboolean folder_item_is_msg_changed(FolderItem *item, MsgInfo *msginfo)
3310 {
3311         Folder *folder;
3312
3313         g_return_val_if_fail(item != NULL, FALSE);
3314         if (item->no_select)
3315                 return FALSE;
3316
3317         folder = item->folder;
3318
3319         g_return_val_if_fail(folder->klass->is_msg_changed != NULL, -1);
3320
3321         return folder->klass->is_msg_changed(folder, item, msginfo);
3322 }
3323
3324 gchar *folder_item_get_cache_file(FolderItem *item)
3325 {
3326         gchar *path;
3327         gchar *file;
3328
3329         g_return_val_if_fail(item != NULL, NULL);
3330         g_return_val_if_fail(item->path != NULL, NULL);
3331
3332         path = folder_item_get_path(item);
3333         g_return_val_if_fail(path != NULL, NULL);
3334         if (!is_dir_exist(path))
3335                 make_dir_hier(path);
3336         file = g_strconcat(path, G_DIR_SEPARATOR_S, CACHE_FILE, NULL);
3337         g_free(path);
3338
3339         return file;
3340 }
3341
3342 gchar *folder_item_get_mark_file(FolderItem *item)
3343 {
3344         gchar *path;
3345         gchar *file;
3346
3347         g_return_val_if_fail(item != NULL, NULL);
3348         g_return_val_if_fail(item->path != NULL, NULL);
3349
3350         path = folder_item_get_path(item);
3351         g_return_val_if_fail(path != NULL, NULL);
3352         if (!is_dir_exist(path))
3353                 make_dir_hier(path);
3354         file = g_strconcat(path, G_DIR_SEPARATOR_S, MARK_FILE, NULL);
3355         g_free(path);
3356
3357         return file;
3358 }
3359
3360 static gpointer xml_to_folder_item(gpointer nodedata, gpointer data)
3361 {
3362         XMLNode *xmlnode = (XMLNode *) nodedata;
3363         Folder *folder = (Folder *) data;
3364         FolderItem *item;
3365
3366         g_return_val_if_fail(xmlnode != NULL, NULL);
3367         g_return_val_if_fail(folder != NULL, NULL);
3368
3369         if (strcmp2(xmlnode->tag->tag, "folderitem") != 0) {
3370                 g_warning("tag name != \"folderitem\"\n");
3371                 return NULL;
3372         }
3373
3374         item = folder_item_new(folder, "", "");
3375         if (folder->klass->item_set_xml != NULL)
3376                 folder->klass->item_set_xml(folder, item, xmlnode->tag);
3377         else
3378                 folder_item_set_xml(folder, item, xmlnode->tag);
3379
3380         item->folder = folder;
3381
3382         switch (item->stype) {
3383         case F_INBOX:  folder->inbox  = item; break;
3384         case F_OUTBOX: folder->outbox = item; break;
3385         case F_DRAFT:  folder->draft  = item; break;
3386         case F_QUEUE:  folder->queue  = item; break;
3387         case F_TRASH:  folder->trash  = item; break;
3388         default:       break;
3389         }
3390         folder_item_prefs_read_config(item);
3391
3392         return item;
3393 }
3394
3395 static gboolean folder_item_set_node(GNode *node, gpointer data)
3396 {
3397         FolderItem *item = (FolderItem *) node->data;
3398         item->node = node;
3399
3400         return FALSE;
3401 }
3402
3403 static Folder *folder_get_from_xml(GNode *node)
3404 {
3405         Folder *folder;
3406         XMLNode *xmlnode;
3407         GList *list;
3408         FolderClass *klass = NULL;
3409         GNode *cur;
3410
3411         g_return_val_if_fail(node->data != NULL, NULL);
3412
3413         xmlnode = node->data;
3414         if (strcmp2(xmlnode->tag->tag, "folder") != 0) {
3415                 g_warning("tag name != \"folder\"\n");
3416                 return NULL;
3417         }
3418         list = xmlnode->tag->attr;
3419         for (; list != NULL; list = list->next) {
3420                 XMLAttr *attr = list->data;
3421
3422                 if (!attr || !attr->name || !attr->value) continue;
3423                 if (!strcmp(attr->name, "type"))
3424                         klass = folder_get_class_from_string(attr->value);
3425         }
3426         if (klass == NULL)
3427                 return NULL;
3428
3429         folder = folder_new(klass, "", "");
3430         g_return_val_if_fail(folder != NULL, NULL);
3431
3432         if (klass->set_xml)
3433                 klass->set_xml(folder, xmlnode->tag);
3434         else
3435                 folder_set_xml(folder, xmlnode->tag);
3436
3437         cur = node->children;
3438         while (cur != NULL) {
3439                 GNode *itemnode;
3440
3441                 itemnode = g_node_map(cur, xml_to_folder_item, (gpointer) folder);
3442                 g_node_append(folder->node, itemnode);
3443                 cur = cur->next;
3444         }
3445         g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, folder_item_set_node, NULL);
3446         
3447         return folder;
3448 }
3449
3450 static gchar *folder_get_list_path(void)
3451 {
3452         static gchar *filename = NULL;
3453
3454         if (!filename)
3455                 filename =  g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
3456                                         FOLDER_LIST, NULL);
3457
3458         return filename;
3459 }
3460
3461 #define PUT_ESCAPE_STR(fp, attr, str)                   \
3462 {                                                       \
3463         fputs(" " attr "=\"", fp);                      \
3464         xml_file_put_escape_str(fp, str);               \
3465         fputs("\"", fp);                                \
3466 }
3467
3468 static gpointer folder_item_to_xml(gpointer nodedata, gpointer data)
3469 {
3470         FolderItem *item = (FolderItem *) nodedata;
3471         XMLTag *tag;
3472
3473         g_return_val_if_fail(item != NULL, NULL);
3474
3475         if (item->folder->klass->item_get_xml != NULL)
3476                 tag = item->folder->klass->item_get_xml(item->folder, item);
3477         else
3478                 tag = folder_item_get_xml(item->folder, item);
3479
3480         return xml_node_new(tag, NULL);
3481 }
3482
3483 static GNode *folder_get_xml_node(Folder *folder)
3484 {
3485         GNode *node;
3486         XMLNode *xmlnode;
3487         XMLTag *tag;
3488
3489         g_return_val_if_fail(folder != NULL, NULL);
3490
3491         if (folder->klass->get_xml != NULL)
3492                 tag = folder->klass->get_xml(folder);
3493         else
3494                 tag = folder_get_xml(folder);
3495
3496         xml_tag_add_attr(tag, xml_attr_new("type", folder->klass->idstr));
3497
3498         xmlnode = xml_node_new(tag, NULL);
3499
3500         node = g_node_new(xmlnode);
3501         
3502         g_return_val_if_fail (folder->node != NULL, NULL);
3503         
3504         if (folder->node->children) {
3505                 GNode *cur;
3506
3507                 cur = folder->node->children;
3508                 while (cur) {
3509                         GNode *xmlnode;
3510
3511                         xmlnode = g_node_map(cur, folder_item_to_xml, (gpointer) folder);
3512                         g_node_append(node, xmlnode);
3513                         cur = cur->next;
3514                 }
3515         }
3516
3517         return node;
3518 }
3519
3520 static void folder_update_op_count_rec(GNode *node)
3521 {
3522         FolderItem *fitem = FOLDER_ITEM(node->data);
3523
3524         if (g_node_depth(node) > 0) {
3525                 if (fitem->op_count > 0) {
3526                         fitem->op_count = 0;
3527                         folder_item_update(fitem, F_ITEM_UPDATE_MSGCNT);
3528                 }
3529                 if (node->children) {
3530                         GNode *child;
3531
3532                         child = node->children;
3533                         while (child) {
3534                                 GNode *cur;
3535
3536                                 cur = child;
3537                                 child = cur->next;
3538                                 folder_update_op_count_rec(cur);
3539                         }
3540                 }
3541         }
3542 }
3543
3544 void folder_update_op_count(void) 
3545 {
3546         GList *cur;
3547         Folder *folder;
3548
3549         for (cur = folder_list; cur != NULL; cur = cur->next) {
3550                 folder = cur->data;
3551                 folder_update_op_count_rec(folder->node);
3552         }
3553 }
3554
3555 typedef struct _type_str {
3556         gchar * str;
3557         gint type;
3558 } type_str;
3559
3560
3561 /*
3562 static gchar * folder_item_get_tree_identifier(FolderItem * item)
3563 {
3564         if (item->parent != NULL) {
3565                 gchar * path;
3566                 gchar * id;
3567
3568                 path = folder_item_get_tree_identifier(item->parent);
3569                 if (path == NULL)
3570                         return NULL;
3571
3572                 id = g_strconcat(path, "/", item->name, NULL);
3573                 g_free(path);
3574
3575                 return id;
3576         }
3577         else {
3578                 return g_strconcat("/", item->name, NULL);
3579         }
3580 }
3581 */
3582
3583 /* CLAWS: temporary local folder for filtering */
3584 #define TEMP_FOLDER "TEMP_FOLDER"
3585 #define PROCESSING_FOLDER_ITEM "processing"     
3586
3587 static FolderItem *processing_folder_item;
3588
3589 static void folder_create_processing_folder(void)
3590 {
3591         Folder *processing_folder;
3592         gchar      *tmpname;
3593
3594         if ((processing_folder = folder_find_from_name(TEMP_FOLDER, mh_get_class())) == NULL) {
3595                 gchar *tmppath;
3596
3597                 tmppath =
3598                     g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
3599                                 "tempfolder", NULL);
3600                 processing_folder =
3601                     folder_new(mh_get_class(), TEMP_FOLDER, tmppath);
3602                 g_free(tmppath);
3603         }
3604         g_assert(processing_folder != NULL);
3605
3606         debug_print("tmpparentroot %s\n", LOCAL_FOLDER(processing_folder)->rootpath);
3607         /* FIXME: [W32] The code below does not correctly merge
3608            relative filenames; there should be a function to handle
3609            this.  */
3610         if (!is_relative_filename(LOCAL_FOLDER(processing_folder)->rootpath))
3611                 tmpname = g_strconcat(LOCAL_FOLDER(processing_folder)->rootpath,
3612                                       G_DIR_SEPARATOR_S, PROCESSING_FOLDER_ITEM,
3613                                       NULL);
3614         else
3615                 tmpname = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3616                                       LOCAL_FOLDER(processing_folder)->rootpath,
3617                                       G_DIR_SEPARATOR_S, PROCESSING_FOLDER_ITEM,
3618                                       NULL);
3619
3620         if (!is_dir_exist(tmpname)) {
3621                 debug_print("*TMP* creating %s\n", tmpname);
3622                 processing_folder_item = processing_folder->klass->create_folder(processing_folder,
3623                                                                                  processing_folder->node->data,
3624                                                                                  PROCESSING_FOLDER_ITEM);
3625         } else {
3626                 debug_print("*TMP* already created\n");
3627                 processing_folder_item = folder_item_new(processing_folder, PROCESSING_FOLDER_ITEM, PROCESSING_FOLDER_ITEM);
3628                 g_assert(processing_folder_item);
3629                 folder_item_append(processing_folder->node->data, processing_folder_item);
3630         }
3631         g_assert(processing_folder_item != NULL);
3632         g_free(tmpname);
3633 }
3634
3635 FolderItem *folder_get_default_processing(void)
3636 {
3637         if (!processing_folder_item) {
3638                 folder_create_processing_folder();
3639         }
3640         return processing_folder_item;
3641 }
3642
3643 /* folder_persist_prefs_new() - return hash table with persistent
3644  * settings (and folder name as key). 
3645  * (note that in claws other options are in the folder_item_prefs_RC
3646  * file, so those don't need to be included in PersistPref yet) 
3647  */
3648 GHashTable *folder_persist_prefs_new(Folder *folder)
3649 {
3650         GHashTable *pptable;
3651
3652         g_return_val_if_fail(folder, NULL);
3653         pptable = g_hash_table_new(g_str_hash, g_str_equal);
3654         folder_get_persist_prefs_recursive(folder->node, pptable);
3655         return pptable;
3656 }
3657
3658 void folder_persist_prefs_free(GHashTable *pptable)
3659 {
3660         g_return_if_fail(pptable);
3661         g_hash_table_foreach_remove(pptable, persist_prefs_free, NULL);
3662         g_hash_table_destroy(pptable);
3663 }
3664
3665 const PersistPrefs *folder_get_persist_prefs(GHashTable *pptable, const char *name)
3666 {
3667         if (pptable == NULL || name == NULL) return NULL;
3668         return g_hash_table_lookup(pptable, name);
3669 }
3670
3671 void folder_item_restore_persist_prefs(FolderItem *item, GHashTable *pptable)
3672 {
3673         const PersistPrefs *pp;
3674         gchar *id = folder_item_get_identifier(item);
3675
3676         pp = folder_get_persist_prefs(pptable, id); 
3677         g_free(id);
3678
3679         if (!pp) return;
3680
3681         /* CLAWS: since not all folder properties have been migrated to 
3682          * folderlist.xml, we need to call the old stuff first before
3683          * setting things that apply both to Main and Claws. */
3684         folder_item_prefs_read_config(item); 
3685
3686         item->collapsed = pp->collapsed;
3687         item->thread_collapsed = pp->thread_collapsed;
3688         item->threaded  = pp->threaded;
3689         item->ret_rcpt  = pp->ret_rcpt;
3690         item->hide_read_msgs = pp->hide_read_msgs;
3691         item->sort_key  = pp->sort_key;
3692         item->sort_type = pp->sort_type;
3693 }
3694
3695 static void folder_get_persist_prefs_recursive(GNode *node, GHashTable *pptable)
3696 {
3697         FolderItem *item = FOLDER_ITEM(node->data);
3698         PersistPrefs *pp;
3699         GNode *child, *cur;
3700         gchar *id;
3701
3702         g_return_if_fail(node != NULL);
3703         g_return_if_fail(item != NULL);
3704
3705         /* NOTE: item->path == NULL means top level folder; not interesting
3706          * to store preferences of that one.  */
3707         if (item->path) {
3708                 id = folder_item_get_identifier(item);
3709                 pp = g_new0(PersistPrefs, 1);
3710                 g_return_if_fail(pp != NULL);
3711                 pp->collapsed = item->collapsed;
3712                 pp->thread_collapsed = item->thread_collapsed;
3713                 pp->threaded  = item->threaded;
3714                 pp->ret_rcpt  = item->ret_rcpt; 
3715                 pp->hide_read_msgs = item->hide_read_msgs;
3716                 pp->sort_key  = item->sort_key;
3717                 pp->sort_type = item->sort_type;
3718                 g_hash_table_insert(pptable, id, pp);
3719         }
3720
3721         if (node->children) {
3722                 child = node->children;
3723                 while (child) {
3724                         cur = child;
3725                         child = cur->next;
3726                         folder_get_persist_prefs_recursive(cur, pptable);
3727                 }
3728         }       
3729 }
3730
3731 static gboolean persist_prefs_free(gpointer key, gpointer val, gpointer data)
3732 {
3733         g_free(key);
3734         g_free(val);
3735         return TRUE;    
3736 }
3737
3738 void folder_item_apply_processing(FolderItem *item)
3739 {
3740         GSList *processing_list;
3741         GSList *mlist, *cur;
3742         guint total = 0, curmsg = 0;
3743
3744         g_return_if_fail(item != NULL);
3745
3746         if (item->no_select)
3747                return;
3748
3749         processing_list = item->prefs->processing;
3750
3751         if (!pre_global_processing && !processing_list
3752         &&  !post_global_processing)
3753                 return;
3754
3755         folder_item_update_freeze();
3756
3757         mlist = folder_item_get_msg_list(item);
3758         total = g_slist_length(mlist);
3759         statusbar_print_all(_("Processing messages..."));
3760         for (cur = mlist ; cur != NULL ; cur = cur->next) {
3761                 MsgInfo * msginfo;
3762
3763                 msginfo = (MsgInfo *) cur->data;
3764                 
3765                 /* reset parameters that can be modified by processing */
3766                 msginfo->hidden = 0;
3767                 msginfo->score = 0;
3768
3769                 statusbar_progress_all(curmsg++,total, 10);
3770
3771                 /* apply pre global rules */
3772                 filter_message_by_msginfo(pre_global_processing, msginfo, NULL);
3773                 
3774                 /* apply rules of the folder */
3775                 filter_message_by_msginfo(processing_list, msginfo, NULL);
3776
3777                 /* apply post global rules */
3778                 filter_message_by_msginfo(post_global_processing, msginfo, NULL);
3779                 
3780         }
3781         if (pre_global_processing || processing_list
3782             || post_global_processing)
3783                 filtering_move_and_copy_msgs(mlist);
3784         for (cur = mlist ; cur != NULL ; cur = cur->next) {
3785                 MsgInfo * msginfo = (MsgInfo *)cur->data;
3786                 procmsg_msginfo_free(msginfo);
3787         }
3788         g_slist_free(mlist);
3789         
3790         statusbar_progress_all(0,0,0);
3791         statusbar_pop_all();
3792
3793         folder_item_update_thaw();
3794 }
3795
3796 /*
3797  *  functions for handling FolderItem content changes
3798  */
3799 static gint folder_item_update_freeze_cnt = 0;
3800
3801 static void folder_item_update_with_msg(FolderItem *item, FolderItemUpdateFlags update_flags, MsgInfo *msg)
3802 {
3803         if (folder_item_update_freeze_cnt == 0 /* || (msg != NULL && item->opened) */) {
3804                 FolderItemUpdateData source;
3805         
3806                 source.item = item;
3807                 source.update_flags = update_flags;
3808                 source.msg = msg;
3809                 hooks_invoke(FOLDER_ITEM_UPDATE_HOOKLIST, &source);
3810         } else {
3811                 item->update_flags |= update_flags & ~(F_ITEM_UPDATE_ADDMSG | F_ITEM_UPDATE_REMOVEMSG);
3812         }
3813 }
3814
3815 /**
3816  * Notify the folder system about changes to a folder. If the
3817  * update system is not frozen the FOLDER_ITEM_UPDATE_HOOKLIST will
3818  * be invoked, otherwise the changes will be remebered until
3819  * the folder system is thawed.
3820  *
3821  * \param item The FolderItem that was changed
3822  * \param update_flags Type of changed that was made
3823  */
3824 void folder_item_update(FolderItem *item, FolderItemUpdateFlags update_flags)
3825 {
3826         folder_item_update_with_msg(item, update_flags, NULL);
3827 }
3828
3829 void folder_item_update_recursive(FolderItem *item, FolderItemUpdateFlags update_flags)
3830 {
3831         GNode *node = item->folder->node;       
3832
3833         node = g_node_find(node, G_PRE_ORDER, G_TRAVERSE_ALL, item);
3834         node = node->children;
3835
3836         folder_item_update(item, update_flags);
3837         while (node != NULL) {
3838                 if (node && node->data) {
3839                         FolderItem *next_item = (FolderItem*) node->data;
3840
3841                         folder_item_update(next_item, update_flags);
3842                 }
3843                 node = node->next;
3844         }
3845 }
3846
3847 void folder_item_update_freeze(void)
3848 {
3849         folder_item_update_freeze_cnt++;
3850 }
3851
3852 static void folder_item_update_func(FolderItem *item, gpointer data)
3853 {
3854         FolderItemUpdateData source;
3855     
3856         if (item->update_flags) {
3857                 source.item = item;
3858                 source.update_flags = item->update_flags;
3859                 source.msg = NULL;
3860                 hooks_invoke(FOLDER_ITEM_UPDATE_HOOKLIST, &source);                             
3861                 item->update_flags = 0;
3862         }
3863 }
3864
3865 void folder_item_update_thaw(void)
3866 {
3867         if (folder_item_update_freeze_cnt > 0)
3868                 folder_item_update_freeze_cnt--;
3869         if (folder_item_update_freeze_cnt == 0) {
3870                 /* Update all folders */
3871                 folder_func_to_all_folders(folder_item_update_func, NULL);
3872         }
3873 }
3874
3875 static void folder_item_synchronise_func(FolderItem *item, gpointer data)
3876 {
3877         Folder *folder = (Folder *)data;
3878         if (folder == NULL || item->folder == folder) {
3879                 if(item->prefs->offlinesync && item->folder->klass->synchronise)
3880                         item->folder->klass->synchronise(item);
3881         }
3882 }
3883
3884 void folder_synchronise(Folder *folder)
3885 {
3886         folder_func_to_all_folders(folder_item_synchronise_func, folder);
3887 }
3888
3889 typedef struct _WantSyncData {
3890         Folder *folder;
3891         gboolean want_sync;
3892 } WantSyncData;
3893
3894 static void folder_item_want_synchronise_func(FolderItem *item, gpointer data)
3895 {
3896         WantSyncData *want_sync_data = (WantSyncData *)data;
3897         
3898         if (want_sync_data->folder == NULL || item->folder == want_sync_data->folder) {
3899                 if (item->prefs->offlinesync && item->folder->klass->synchronise)
3900                         want_sync_data->want_sync |= TRUE;
3901         }
3902 }
3903
3904 gboolean folder_want_synchronise(Folder *folder)
3905 {
3906         WantSyncData *want_sync_data = g_new0(WantSyncData, 1);
3907         gboolean result;
3908         want_sync_data->folder = folder;
3909         want_sync_data->want_sync = FALSE;
3910         
3911         folder_func_to_all_folders(folder_item_want_synchronise_func, want_sync_data);
3912         result = want_sync_data->want_sync;
3913         g_free(want_sync_data);
3914         debug_print("Folder %s wants sync: %d\n", folder->name, result);
3915         return result;
3916 }
3917
3918 void folder_item_set_batch (FolderItem *item, gboolean batch)
3919 {
3920         if (item->folder->klass->set_batch) {
3921                 item->folder->klass->set_batch(item->folder, item, batch);
3922         }
3923 }
3924
3925 gboolean folder_has_parent_of_type(FolderItem *item, 
3926                                           SpecialFolderItemType type) 
3927 {
3928         FolderItem *cur = item;
3929
3930         /* if we already know it, make it short */
3931         if (item->parent_stype != -1) {
3932                 return (item->parent_stype == type);
3933         }
3934         
3935         /* if we don't, find the type from the first possible parent,
3936          * and set our parent type to be faster next time */
3937         while (cur) {
3938                 if (cur->stype == type || cur->parent_stype == type) {
3939                         item->parent_stype = type;
3940                         return TRUE;
3941                 }
3942                 cur = folder_item_parent(cur);
3943         }
3944         
3945         /* if we didn't match what was asked, we didn't return. If our
3946          * parent type is unknown, we may as well find it now to be faster
3947          * later. */
3948         if (item->parent_stype == -1) {
3949                 cur = item;
3950                 while (cur) {
3951                         /* here's an exception: Inbox subfolders are normal. */
3952                         if (item->parent_stype == -1 && cur->stype == F_INBOX 
3953                         && item != cur) {
3954                                 debug_print("set item %s parent type to %d "
3955                                         "even if %s is F_INBOX\n",
3956                                         item->path ? item->path : "(null)",
3957                                         0, cur->path);
3958                                 item->parent_stype = F_NORMAL;
3959                                 break;
3960                         }
3961                         /* ah, we know this parent's parent's type, we may as 
3962                          * well copy it instead of going up the full way */
3963                         if (cur->parent_stype != -1) {
3964                                 item->parent_stype = cur->parent_stype;
3965                                 debug_print("set item %s parent type to %d "
3966                                         "from %s's parent type\n",
3967                                         item->path ? item->path : "(null)",
3968                                         cur->parent_stype ? cur->parent_stype : 0, 
3969                                         cur->path ? cur->path : "(null)");
3970                                 break;
3971                         }
3972                         /* we found a parent that has a special type. That's 
3973                          * our parent type. */
3974                         if (cur->stype != F_NORMAL) {
3975                                 debug_print("set item %s parent type to %d "
3976                                         "from %s's type\n",
3977                                         item->path ? item->path : "(null)",
3978                                         cur->stype ? cur->stype : 0, 
3979                                         cur->path ? cur->path : "(null)");
3980                                 cur->parent_stype = cur->stype;
3981                                 item->parent_stype = cur->stype;
3982                                 break;
3983                         }
3984                         /* if we didn't find anything, go up once more */
3985                         cur = folder_item_parent(cur);
3986                 }
3987                 /* as we still didn't find anything, our parents must all be 
3988                  * normal. */
3989                 if (item->parent_stype == -1) {
3990                         debug_print("set item %s to 0 from default\n", 
3991                                 item->path ? item->path : "(null)");
3992                         item->parent_stype = F_NORMAL;
3993                 }
3994         }
3995         return FALSE;
3996 }
3997
3998 gboolean folder_subscribe (const gchar *uri)
3999 {
4000         GList *cur;
4001         for (cur = folder_get_list(); cur != NULL; cur = g_list_next(cur)) {
4002                 Folder *folder = (Folder *) cur->data;
4003
4004                 if (folder->klass->subscribe
4005                 &&  folder->klass->subscribe(folder, uri)) {
4006                         return TRUE;
4007                 }
4008         }
4009         return FALSE;
4010
4011 }
4012 #undef PUT_ESCAPE_STR