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