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