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