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