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