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