2012-09-05 [colin] 3.8.1cvs44
[claws.git] / src / mh.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 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 #include "claws-features.h"
23 #endif
24
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <dirent.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <time.h>
35
36 #include "folder.h"
37 #include "mh.h"
38 #include "procmsg.h"
39 #include "procheader.h"
40 #include "utils.h"
41 #include "codeconv.h"
42 #include "statusbar.h"
43 #include "gtkutils.h"
44 #include "timing.h"
45
46 /* Define possible missing constants for Windows. */
47 #ifdef G_OS_WIN32
48 # ifndef S_IRGRP
49 # define S_IRGRP 0
50 # define S_IWGRP 0
51 # endif
52 # ifndef S_IROTH
53 # define S_IROTH 0
54 # define S_IWOTH 0
55 # endif
56 #endif
57
58
59 static void     mh_folder_init          (Folder         *folder,
60                                          const gchar    *name,
61                                          const gchar    *path);
62
63 static Folder   *mh_folder_new          (const gchar    *name,
64                                          const gchar    *path);
65 static void     mh_folder_destroy       (Folder         *folder);
66 static gchar   *mh_fetch_msg            (Folder         *folder,
67                                          FolderItem     *item,
68                                          gint            num);
69 static MsgInfo *mh_get_msginfo          (Folder         *folder,
70                                          FolderItem     *item,
71                                          gint            num);
72 static gint     mh_add_msg              (Folder         *folder,
73                                          FolderItem     *dest,
74                                          const gchar    *file,
75                                          MsgFlags       *flags);
76 static gint     mh_add_msgs             (Folder         *folder,
77                                          FolderItem     *dest,
78                                          GSList         *file_list,
79                                          GHashTable     *relation);
80 static gint     mh_copy_msg             (Folder         *folder,
81                                          FolderItem     *dest,
82                                          MsgInfo        *msginfo);
83 static gint     mh_copy_msgs            (Folder         *folder, 
84                                          FolderItem     *dest, 
85                                          MsgInfoList    *msglist, 
86                                          GHashTable     *relation);
87 static gint     mh_remove_msg           (Folder         *folder,
88                                          FolderItem     *item,
89                                          gint            num);
90 static gint     mh_remove_msgs          (Folder         *folder, 
91                                          FolderItem     *item, 
92                                          MsgInfoList    *msglist, 
93                                          GHashTable     *relation);
94 static gint     mh_remove_all_msg       (Folder         *folder,
95                                          FolderItem     *item);
96 static gboolean mh_is_msg_changed       (Folder         *folder,
97                                          FolderItem     *item,
98                                          MsgInfo        *msginfo);
99
100 static gint     mh_get_num_list         (Folder         *folder,
101                                          FolderItem     *item, 
102                                          GSList         **list, 
103                                          gboolean       *old_uids_valid);
104 static gint     mh_scan_tree            (Folder         *folder);
105
106 static gint    mh_create_tree           (Folder         *folder);
107 static FolderItem *mh_create_folder     (Folder         *folder,
108                                          FolderItem     *parent,
109                                          const gchar    *name);
110 static gint    mh_rename_folder         (Folder         *folder,
111                                          FolderItem     *item,
112                                          const gchar    *name);
113 static gint    mh_remove_folder         (Folder         *folder,
114                                          FolderItem     *item);
115
116 static gchar   *mh_get_new_msg_filename         (FolderItem     *dest);
117
118 static MsgInfo *mh_parse_msg                    (const gchar    *file,
119                                                  FolderItem     *item);
120 static void     mh_remove_missing_folder_items  (Folder         *folder);
121 static gchar    *mh_filename_from_utf8          (const gchar    *path);
122 static gchar    *mh_filename_to_utf8            (const gchar    *path);
123 static void     mh_scan_tree_recursive          (FolderItem     *item);
124
125 static gboolean mh_rename_folder_func           (GNode          *node,
126                                                  gpointer        data);
127 static gchar   *mh_item_get_path                (Folder *folder, 
128                                                  FolderItem *item);
129
130 static gboolean mh_scan_required        (Folder         *folder,
131                                          FolderItem     *item);
132 static void mh_set_mtime                (Folder         *folder,
133                                          FolderItem *item);
134 static int mh_item_close                (Folder         *folder,
135                                          FolderItem     *item);
136 #if 0
137 static gint mh_get_flags                (Folder *folder, FolderItem *item,
138                                          MsgInfoList *msginfo_list, GHashTable *msgflags);
139 #endif
140 static void mh_write_sequences          (FolderItem     *item, gboolean remove_unseen);
141
142 static FolderClass mh_class;
143
144 FolderClass *mh_get_class(void)
145 {
146         if (mh_class.idstr == NULL) {
147                 mh_class.type = F_MH;
148                 mh_class.idstr = "mh";
149                 mh_class.uistr = "MH";
150                 
151                 /* Folder functions */
152                 mh_class.new_folder = mh_folder_new;
153                 mh_class.destroy_folder = mh_folder_destroy;
154                 mh_class.set_xml = folder_local_set_xml;
155                 mh_class.get_xml = folder_local_get_xml;
156                 mh_class.scan_tree = mh_scan_tree;
157                 mh_class.create_tree = mh_create_tree;
158
159                 /* FolderItem functions */
160                 mh_class.item_get_path = mh_item_get_path;
161                 mh_class.create_folder = mh_create_folder;
162                 mh_class.rename_folder = mh_rename_folder;
163                 mh_class.remove_folder = mh_remove_folder;
164                 mh_class.get_num_list = mh_get_num_list;
165                 mh_class.scan_required = mh_scan_required;
166                 mh_class.set_mtime = mh_set_mtime;
167                 mh_class.close = mh_item_close;
168                 mh_class.get_flags = NULL; /*mh_get_flags */;
169
170                 /* Message functions */
171                 mh_class.get_msginfo = mh_get_msginfo;
172                 mh_class.fetch_msg = mh_fetch_msg;
173                 mh_class.add_msg = mh_add_msg;
174                 mh_class.add_msgs = mh_add_msgs;
175                 mh_class.copy_msg = mh_copy_msg;
176                 mh_class.copy_msgs = mh_copy_msgs;
177                 mh_class.remove_msg = mh_remove_msg;
178                 mh_class.remove_msgs = mh_remove_msgs;
179                 mh_class.remove_all_msg = mh_remove_all_msg;
180                 mh_class.is_msg_changed = mh_is_msg_changed;
181         }
182
183         return &mh_class;
184 }
185
186 static Folder *mh_folder_new(const gchar *name, const gchar *path)
187 {
188         Folder *folder;
189
190         folder = (Folder *)g_new0(MHFolder, 1);
191         folder->klass = &mh_class;
192         mh_folder_init(folder, name, path);
193
194         return folder;
195 }
196
197 static void mh_folder_destroy(Folder *folder)
198 {
199         folder_local_folder_destroy(LOCAL_FOLDER(folder));
200 }
201
202 static void mh_folder_init(Folder *folder, const gchar *name, const gchar *path)
203 {
204         folder_local_folder_init(folder, name, path);
205
206 }
207
208 gboolean mh_scan_required(Folder *folder, FolderItem *item)
209 {
210         gchar *path;
211         struct stat s;
212
213         path = folder_item_get_path(item);
214         cm_return_val_if_fail(path != NULL, FALSE);
215
216         if (g_stat(path, &s) < 0) {
217                 FILE_OP_ERROR(path, "stat");
218                 g_free(path);
219                 return FALSE;
220         }
221
222         if ((s.st_mtime > item->mtime) &&
223                 (s.st_mtime - 3600 != item->mtime)) {
224                 debug_print("MH scan required, folder updated: %s (%ld > %ld)\n",
225                             path?path:"(null)",
226                             (long int) s.st_mtime,
227                             (long int) item->mtime);
228                 g_free(path);
229                 return TRUE;
230         }
231
232         debug_print("MH scan not required: %s (%ld <= %ld)\n",
233                     path?path:"(null)",
234                     (long int) s.st_mtime,
235                     (long int) item->mtime);
236         g_free(path);
237         return FALSE;
238 }
239
240 static void mh_get_last_num(Folder *folder, FolderItem *item)
241 {
242         gchar *path;
243         DIR *dp;
244         struct dirent *d;
245         gint max = 0;
246         gint num;
247
248         cm_return_if_fail(item != NULL);
249
250         debug_print("mh_get_last_num(): Scanning %s ...\n", item->path?item->path:"(null)");
251
252         path = folder_item_get_path(item);
253         cm_return_if_fail(path != NULL);
254         if (change_dir(path) < 0) {
255                 g_free(path);
256                 return;
257         }
258         g_free(path);
259
260         if ((dp = opendir(".")) == NULL) {
261                 FILE_OP_ERROR(item->path, "opendir");
262                 return;
263         }
264
265         while ((d = readdir(dp)) != NULL) {
266                 if ((num = to_number(d->d_name)) > 0 &&
267                     dirent_is_regular_file(d)) {
268                         if (max < num)
269                                 max = num;
270                 }
271                 if (num % 2000 == 0)
272                         GTK_EVENTS_FLUSH();
273         }
274         closedir(dp);
275
276         debug_print("Last number in dir %s = %d\n", item->path?item->path:"(null)", max);
277         item->last_num = max;
278 }
279
280 gint mh_get_num_list(Folder *folder, FolderItem *item, GSList **list, gboolean *old_uids_valid)
281 {
282
283         gchar *path;
284         DIR *dp;
285         struct dirent *d;
286         gint num, nummsgs = 0;
287
288         cm_return_val_if_fail(item != NULL, -1);
289
290         debug_print("mh_get_num_list(): Scanning %s ...\n", item->path?item->path:"(null)");
291
292         *old_uids_valid = TRUE;
293
294         path = folder_item_get_path(item);
295         cm_return_val_if_fail(path != NULL, -1);
296         if (change_dir(path) < 0) {
297                 g_free(path);
298                 return -1;
299         }
300         g_free(path);
301
302         if ((dp = opendir(".")) == NULL) {
303                 FILE_OP_ERROR(item->path, "opendir");
304                 return -1;
305         }
306
307         while ((d = readdir(dp)) != NULL) {
308                 if ((num = to_number(d->d_name)) > 0) {
309                         *list = g_slist_prepend(*list, GINT_TO_POINTER(num));
310                         nummsgs++;
311                 }
312         }
313         closedir(dp);
314
315         mh_set_mtime(folder, item);
316         return nummsgs;
317 }
318
319 static gchar *mh_fetch_msg(Folder *folder, FolderItem *item, gint num)
320 {
321         gchar *path;
322         gchar *file;
323
324         cm_return_val_if_fail(item != NULL, NULL);
325         cm_return_val_if_fail(num > 0, NULL);
326
327         path = folder_item_get_path(item);
328         file = g_strconcat(path, G_DIR_SEPARATOR_S, itos(num), NULL);
329
330         if (!is_file_exist(file)) {
331                 g_free(file);
332                 g_free(path);
333                 return NULL;
334         }
335         g_free(path);
336         return file;
337 }
338
339 static MsgInfo *mh_get_msginfo(Folder *folder, FolderItem *item, gint num)
340 {
341         MsgInfo *msginfo;
342         gchar *file;
343
344         cm_return_val_if_fail(item != NULL, NULL);
345         if (num <= 0)
346                 return NULL;
347
348         file = mh_fetch_msg(folder, item, num);
349         if (!file) return NULL;
350
351         msginfo = mh_parse_msg(file, item);
352         if (msginfo)
353                 msginfo->msgnum = num;
354
355         g_free(file);
356
357         return msginfo;
358 }
359
360 static gchar *mh_get_new_msg_filename(FolderItem *dest)
361 {
362         gchar *destfile;
363         gchar *destpath;
364
365         destpath = folder_item_get_path(dest);
366         cm_return_val_if_fail(destpath != NULL, NULL);
367
368         if (!is_dir_exist(destpath))
369                 make_dir_hier(destpath);
370
371         for (;;) {
372                 destfile = g_strdup_printf("%s%c%d", destpath, G_DIR_SEPARATOR,
373                                            dest->last_num + 1);
374                 if (is_file_entry_exist(destfile)) {
375                         dest->last_num++;
376                         g_free(destfile);
377                 } else
378                         break;
379         }
380
381         g_free(destpath);
382
383         return destfile;
384 }
385
386 static gint mh_add_msg(Folder *folder, FolderItem *dest, const gchar *file, MsgFlags *flags)
387 {
388         gint ret;
389         GSList file_list;
390         MsgFileInfo fileinfo;
391
392         cm_return_val_if_fail(file != NULL, -1);
393
394         fileinfo.msginfo = NULL;
395         fileinfo.file = (gchar *)file;
396         fileinfo.flags = flags;
397         file_list.data = &fileinfo;
398         file_list.next = NULL;
399
400         ret = mh_add_msgs(folder, dest, &file_list, NULL);
401         return ret;
402
403  
404 static gint mh_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list, 
405                  GHashTable *relation)
406
407         gchar *destfile;
408         GSList *cur;
409         MsgFileInfo *fileinfo;
410
411         cm_return_val_if_fail(dest != NULL, -1);
412         cm_return_val_if_fail(file_list != NULL, -1);
413
414         if (dest->last_num < 0) {
415                 mh_get_last_num(folder, dest);
416                 if (dest->last_num < 0) return -1;
417         }
418
419         for (cur = file_list; cur != NULL; cur = cur->next) {
420                 fileinfo = (MsgFileInfo *)cur->data;
421
422                 destfile = mh_get_new_msg_filename(dest);
423                 if (destfile == NULL) return -1;
424
425 #ifdef G_OS_UNIX
426                 if (link(fileinfo->file, destfile) < 0) {
427 #endif
428                         if (copy_file(fileinfo->file, destfile, TRUE) < 0) {
429                                 g_warning(_("can't copy message %s to %s\n"),
430                                           fileinfo->file, destfile);
431                                 g_free(destfile);
432                                 return -1;
433                         }
434 #ifdef G_OS_UNIX
435                 }
436 #endif
437
438                 if (relation != NULL)
439                         g_hash_table_insert(relation, fileinfo, GINT_TO_POINTER(dest->last_num + 1));
440                 g_free(destfile);
441                 dest->last_num++;
442         }
443         mh_write_sequences(dest, TRUE);
444         return dest->last_num;
445 }
446
447 static gint mh_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
448 {
449         GSList msglist;
450
451         cm_return_val_if_fail(msginfo != NULL, -1);
452
453         msglist.data = msginfo;
454         msglist.next = NULL;
455
456         return mh_copy_msgs(folder, dest, &msglist, NULL);      
457 }
458
459 static gint mh_copy_msgs(Folder *folder, FolderItem *dest, MsgInfoList *msglist, 
460                          GHashTable *relation)
461 {
462         gboolean dest_need_scan = FALSE;
463         gboolean src_need_scan = FALSE;
464         FolderItem *src = NULL;
465         gchar *srcfile;
466         gchar *destfile;
467         gint filemode = 0;
468         FolderItemPrefs *prefs;
469         MsgInfo *msginfo = NULL;
470         MsgInfoList *cur = NULL;
471         gint curnum = 0, total = 0;
472         gchar *srcpath = NULL;
473         gboolean full_fetch = FALSE;
474         time_t last_dest_mtime = (time_t)0;
475         time_t last_src_mtime = (time_t)0;
476
477         cm_return_val_if_fail(dest != NULL, -1);
478         cm_return_val_if_fail(msglist != NULL, -1);
479         
480         msginfo = (MsgInfo *)msglist->data;
481
482         cm_return_val_if_fail(msginfo != NULL, -1);
483
484         if (msginfo->folder == dest) {
485                 g_warning("the src folder is identical to the dest.\n");
486                 return -1;
487         }
488
489         if (msginfo->folder->folder != dest->folder)
490                 full_fetch = TRUE;
491         
492         if (FOLDER_TYPE(msginfo->folder->folder) == F_MH) {
493                 src = msginfo->folder;
494         }
495
496         if (dest->last_num < 0) {
497                 mh_get_last_num(folder, dest);
498                 if (dest->last_num < 0) return -1;
499         }
500
501         prefs = dest->prefs;
502
503         srcpath = folder_item_get_path(msginfo->folder);
504
505         dest_need_scan = mh_scan_required(dest->folder, dest);
506         last_dest_mtime = dest->mtime;
507
508         if (src) {
509                 src_need_scan = mh_scan_required(src->folder, src);
510                 last_src_mtime = src->mtime;
511         }
512
513         total = g_slist_length(msglist);
514         if (total > 100) {
515                 if (MSG_IS_MOVE(msginfo->flags))
516                         statusbar_print_all(_("Moving messages..."));
517                 else
518                         statusbar_print_all(_("Copying messages..."));
519         }
520         for (cur = msglist; cur; cur = cur->next) {
521                 msginfo = (MsgInfo *)cur->data;
522                 if (!msginfo) {
523                         goto err_reset_status;
524                 }
525                 if (!full_fetch) {
526                         srcfile = g_strconcat(srcpath, 
527                                 G_DIR_SEPARATOR_S, 
528                                 itos(msginfo->msgnum), NULL);
529                 } else {
530                         srcfile = procmsg_get_message_file(msginfo);
531                 }
532                 if (!srcfile) {
533                         goto err_reset_status;
534                 }
535                 destfile = mh_get_new_msg_filename(dest);
536                 if (!destfile) {
537                         g_free(srcfile);
538                         goto err_reset_status;
539                 }
540
541                 if (total > 100) {
542                         statusbar_progress_all(curnum, total, 100);
543                         if (curnum % 100 == 0)
544                                 GTK_EVENTS_FLUSH();
545                         curnum++;
546                 }
547
548                 debug_print("Copying message %s%c%d to %s ...\n",
549                             msginfo->folder->path, G_DIR_SEPARATOR,
550                             msginfo->msgnum, dest->path);
551
552
553                 if (MSG_IS_MOVE(msginfo->flags)) {
554                         msginfo->flags.tmp_flags &= ~MSG_MOVE_DONE;
555                         if (move_file(srcfile, destfile, TRUE) < 0) {
556                                 FILE_OP_ERROR(srcfile, "move");
557                                 if (copy_file(srcfile, destfile, TRUE) < 0) {
558                                         FILE_OP_ERROR(srcfile, "copy");
559                                         g_free(srcfile);
560                                         g_free(destfile);
561                                         goto err_reset_status;
562                                 }
563                         } else {
564                                 /* say unlinking's not necessary */
565                                 msginfo->flags.tmp_flags |= MSG_MOVE_DONE;
566                         }
567                 } else if (copy_file(srcfile, destfile, TRUE) < 0) {
568                         FILE_OP_ERROR(srcfile, "copy");
569                         g_free(srcfile);
570                         g_free(destfile);
571                         goto err_reset_status;
572                 } 
573                 if (prefs && prefs->enable_folder_chmod && prefs->folder_chmod) {
574                         if (chmod(destfile, prefs->folder_chmod) < 0)
575                                 FILE_OP_ERROR(destfile, "chmod");
576
577                         /* for mark file */
578                         filemode = prefs->folder_chmod;
579                         if (filemode & S_IRGRP) filemode |= S_IWGRP;
580                         if (filemode & S_IROTH) filemode |= S_IWOTH;
581                 }
582                 if (relation) {
583                         if (g_hash_table_lookup(relation, msginfo) != NULL)
584                                 g_warning("already in : %p", msginfo);
585                         
586                         g_hash_table_insert(relation, msginfo, GINT_TO_POINTER(dest->last_num+1));
587                 }
588                 g_free(srcfile);
589                 g_free(destfile);
590                 dest->last_num++;
591         }
592
593         g_free(srcpath);
594         mh_write_sequences(dest, TRUE);
595
596         if (dest->mtime == last_dest_mtime && !dest_need_scan) {
597                 mh_set_mtime(folder, dest);
598         }
599
600         if (src && src->mtime == last_src_mtime && !src_need_scan) {
601                 mh_set_mtime(folder, src);
602         }
603
604         if (total > 100) {
605                 statusbar_progress_all(0,0,0);
606                 statusbar_pop_all();
607         }
608         return dest->last_num;
609 err_reset_status:
610         g_free(srcpath);
611         mh_write_sequences(dest, TRUE);
612         if (total > 100) {
613                 statusbar_progress_all(0,0,0);
614                 statusbar_pop_all();
615         }
616         return -1;
617
618 }
619
620 static gint mh_remove_msg(Folder *folder, FolderItem *item, gint num)
621 {
622         gboolean need_scan = FALSE;
623         time_t last_mtime = (time_t)0;
624         gchar *file;
625
626         cm_return_val_if_fail(item != NULL, -1);
627
628         file = mh_fetch_msg(folder, item, num);
629         cm_return_val_if_fail(file != NULL, -1);
630
631         need_scan = mh_scan_required(folder, item);
632         last_mtime = item->mtime;
633
634         if (claws_unlink(file) < 0) {
635                 FILE_OP_ERROR(file, "unlink");
636                 g_free(file);
637                 return -1;
638         }
639
640         if (item->mtime == last_mtime && !need_scan) {
641                 mh_set_mtime(folder, item);
642         }
643         g_free(file);
644         return 0;
645 }
646
647 static gint mh_remove_msgs(Folder *folder, FolderItem *item, 
648                     MsgInfoList *msglist, GHashTable *relation)
649 {
650         gboolean need_scan = FALSE;
651         gchar *path, *file;
652         time_t last_mtime = (time_t)0;
653         MsgInfoList *cur;
654         gint total = 0, curnum = 0;
655
656         cm_return_val_if_fail(item != NULL, -1);
657
658         path = folder_item_get_path(item);
659         
660         need_scan = mh_scan_required(folder, item);
661         last_mtime = item->mtime;
662
663         total = g_slist_length(msglist);
664         if (total > 100) {
665                 statusbar_print_all(_("Deleting messages..."));
666         }
667
668         for (cur = msglist; cur; cur = cur->next) {
669                 MsgInfo *msginfo = (MsgInfo *)cur->data;
670                 if (msginfo == NULL)
671                         continue;
672                 if (MSG_IS_MOVE(msginfo->flags) && MSG_IS_MOVE_DONE(msginfo->flags)) {
673                         msginfo->flags.tmp_flags &= ~MSG_MOVE_DONE;
674                         continue;
675                 }
676                 if (total > 100) {
677                         statusbar_progress_all(curnum, total, 100);
678                         if (curnum % 100 == 0)
679                                 GTK_EVENTS_FLUSH();
680                         curnum++;
681                 }
682
683                 file = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
684                 if (file == NULL)
685                         continue;
686                 
687                 if (claws_unlink(file) < 0) {
688                         g_free(file);
689                         continue;
690                 }
691                 
692                 g_free(file);
693         }
694
695         if (total > 100) {
696                 statusbar_progress_all(0,0,0);
697                 statusbar_pop_all();
698         }
699         if (item->mtime == last_mtime && !need_scan) {
700                 mh_set_mtime(folder, item);
701         }
702
703         g_free(path);
704         return 0;
705 }
706
707 static gint mh_remove_all_msg(Folder *folder, FolderItem *item)
708 {
709         gchar *path;
710         gint val;
711
712         cm_return_val_if_fail(item != NULL, -1);
713
714         path = folder_item_get_path(item);
715         cm_return_val_if_fail(path != NULL, -1);
716         val = remove_all_numbered_files(path);
717         g_free(path);
718
719         mh_write_sequences(item, TRUE);
720
721         return val;
722 }
723
724 static gboolean mh_is_msg_changed(Folder *folder, FolderItem *item,
725                                   MsgInfo *msginfo)
726 {
727         struct stat s;
728
729         if (g_stat(itos(msginfo->msgnum), &s) < 0 ||
730             msginfo->size  != s.st_size || (
731                 (msginfo->mtime - s.st_mtime != 0) &&
732                 (msginfo->mtime - s.st_mtime != 3600) &&
733                 (msginfo->mtime - s.st_mtime != -3600)))
734                 return TRUE;
735
736         return FALSE;
737 }
738
739 static gint mh_scan_tree(Folder *folder)
740 {
741         FolderItem *item;
742         gchar *rootpath;
743
744         cm_return_val_if_fail(folder != NULL, -1);
745
746         if (!folder->node) {
747                 item = folder_item_new(folder, folder->name, NULL);
748                 item->folder = folder;
749                 folder->node = item->node = g_node_new(item);
750         } else
751                 item = FOLDER_ITEM(folder->node->data);
752
753         rootpath = folder_item_get_path(item);
754         if (change_dir(rootpath) < 0) {
755                 g_free(rootpath);
756                 return -1;
757         }
758         g_free(rootpath);
759
760         mh_create_tree(folder);
761         mh_remove_missing_folder_items(folder);
762         mh_scan_tree_recursive(item);
763
764         return 0;
765 }
766
767 #define MAKE_DIR_IF_NOT_EXIST(dir) \
768 { \
769         if (!is_dir_exist(dir)) { \
770                 if (is_file_exist(dir)) { \
771                         g_warning("File `%s' already exists.\n" \
772                                     "Can't create folder.", dir); \
773                         return -1; \
774                 } \
775                 if (make_dir_hier(dir) < 0) \
776                         return -1; \
777         } \
778 }
779
780 static gint mh_create_tree(Folder *folder)
781 {
782         gchar *rootpath, *f;
783
784         cm_return_val_if_fail(folder != NULL, -1);
785
786         CHDIR_RETURN_VAL_IF_FAIL(get_mail_base_dir(), -1);
787         rootpath = LOCAL_FOLDER(folder)->rootpath;
788         MAKE_DIR_IF_NOT_EXIST(rootpath);
789         CHDIR_RETURN_VAL_IF_FAIL(rootpath, -1);
790
791         /* Create special directories as needed */
792         if (folder->inbox != NULL &&
793                         folder->inbox->path != NULL)
794                 f = folder->inbox->path;
795         else
796                 f = INBOX_DIR;
797         MAKE_DIR_IF_NOT_EXIST(f);
798
799         if (folder->outbox != NULL &&
800                         folder->outbox->path != NULL)
801                 f = folder->outbox->path;
802         else
803                 f = OUTBOX_DIR;
804         MAKE_DIR_IF_NOT_EXIST(f);
805
806         if (folder->draft != NULL &&
807                         folder->draft->path != NULL)
808                 f = folder->draft->path;
809         else
810                 f = DRAFT_DIR;
811         MAKE_DIR_IF_NOT_EXIST(f);
812
813         if (folder->queue != NULL &&
814                         folder->queue->path != NULL)
815                 f = folder->queue->path;
816         else
817                 f = QUEUE_DIR;
818         MAKE_DIR_IF_NOT_EXIST(f);
819
820         if (folder->trash != NULL &&
821                         folder->trash->path != NULL)
822                 f = folder->trash->path;
823         else
824                 f = TRASH_DIR;
825         MAKE_DIR_IF_NOT_EXIST(f);
826
827         return 0;
828 }
829
830 #undef MAKE_DIR_IF_NOT_EXIST
831
832 static gchar *mh_item_get_path(Folder *folder, FolderItem *item)
833 {
834         gchar *folder_path, *path;
835         gchar *real_path;
836         cm_return_val_if_fail(folder != NULL, NULL);
837         cm_return_val_if_fail(item != NULL, NULL);
838
839         folder_path = g_strdup(LOCAL_FOLDER(folder)->rootpath);
840         cm_return_val_if_fail(folder_path != NULL, NULL);
841
842         /* FIXME: [W32] The code below does not correctly merge
843            relative filenames; there should be a function to handle
844            this.  */
845         if ( !is_relative_filename (folder_path) ) {
846                 if (item->path)
847                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
848                                            item->path, NULL);
849                 else
850                         path = g_strdup(folder_path);
851         } else {
852                 if (item->path)
853                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
854                                            folder_path, G_DIR_SEPARATOR_S,
855                                            item->path, NULL);
856                 else
857                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
858                                            folder_path, NULL);
859         }
860         g_free(folder_path);
861         real_path = mh_filename_from_utf8(path);
862         if (!is_dir_exist(real_path) && is_dir_exist(path)) {
863                 /* mmh, older version did put utf8 filenames instead of
864                  * the correct encoding */
865                 g_rename(path, real_path);
866                 folder_item_scan(item);
867         }
868
869         g_free(path);
870         return real_path;
871 }
872
873 static FolderItem *mh_create_folder(Folder *folder, FolderItem *parent,
874                                     const gchar *name)
875 {
876         gchar *path, *real_name;
877         gchar *fullpath;
878         FolderItem *new_item;
879         gchar *mh_sequences_filename;
880         FILE *mh_sequences_file;
881
882         cm_return_val_if_fail(folder != NULL, NULL);
883         cm_return_val_if_fail(parent != NULL, NULL);
884         cm_return_val_if_fail(name != NULL, NULL);
885
886         path = folder_item_get_path(parent);
887         if (!is_dir_exist(path)) 
888                 if (make_dir_hier(path) != 0)
889                         return NULL;
890                 
891         real_name = mh_filename_from_utf8(name);
892         fullpath = g_strconcat(path, G_DIR_SEPARATOR_S, real_name, NULL);
893         g_free(real_name);
894         g_free(path);
895
896         if (make_dir(fullpath) < 0) {
897                 g_free(fullpath);
898                 return NULL;
899         }
900
901         g_free(fullpath);
902
903         if (parent->path)
904                 path = g_strconcat(parent->path, G_DIR_SEPARATOR_S, name,
905                                    NULL);
906         else
907                 path = g_strdup(name);
908         new_item = folder_item_new(folder, name, path);
909         folder_item_append(parent, new_item);
910
911         g_free(path);
912
913         path = folder_item_get_path(new_item);
914         mh_sequences_filename = g_strconcat(path, G_DIR_SEPARATOR_S,
915                                             ".mh_sequences", NULL);
916         if ((mh_sequences_file = g_fopen(mh_sequences_filename, "a+b")) != NULL) {
917                 fclose(mh_sequences_file);
918         }
919         g_free(mh_sequences_filename);
920         g_free(path);
921
922         return new_item;
923 }
924
925 static gint mh_rename_folder(Folder *folder, FolderItem *item,
926                              const gchar *name)
927 {
928         gchar *real_name;
929         gchar *oldpath;
930         gchar *dirname;
931         gchar *newpath, *utf8newpath;
932         gchar *paths[2];
933
934         cm_return_val_if_fail(folder != NULL, -1);
935         cm_return_val_if_fail(item != NULL, -1);
936         cm_return_val_if_fail(item->path != NULL, -1);
937         cm_return_val_if_fail(name != NULL, -1);
938
939         oldpath = folder_item_get_path(item);
940         if (!is_dir_exist(oldpath))
941                 make_dir_hier(oldpath);
942
943         dirname = g_path_get_dirname(oldpath);
944         real_name = mh_filename_from_utf8(name);
945         newpath = g_strconcat(dirname, G_DIR_SEPARATOR_S, real_name, NULL);
946         g_free(real_name);
947
948         if (g_rename(oldpath, newpath) < 0) {
949                 FILE_OP_ERROR(oldpath, "rename");
950                 g_free(oldpath);
951                 g_free(newpath);
952                 return -1;
953         }
954
955         g_free(oldpath);
956         g_free(newpath);
957
958         if (strchr(item->path, G_DIR_SEPARATOR) != NULL) {
959                 dirname = g_path_get_dirname(item->path);
960                 utf8newpath = g_strconcat(dirname, G_DIR_SEPARATOR_S,
961                                           name, NULL);
962                 g_free(dirname);
963         } else
964                 utf8newpath = g_strdup(name);
965
966         g_free(item->name);
967         item->name = g_strdup(name);
968
969         paths[0] = g_strdup(item->path);
970         paths[1] = utf8newpath;
971         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
972                         mh_rename_folder_func, paths);
973
974         g_free(paths[0]);
975         g_free(paths[1]);
976         return 0;
977 }
978
979 static gint mh_remove_folder(Folder *folder, FolderItem *item)
980 {
981         gchar *path;
982
983         cm_return_val_if_fail(folder != NULL, -1);
984         cm_return_val_if_fail(item != NULL, -1);
985         cm_return_val_if_fail(item->path != NULL, -1);
986
987         path = folder_item_get_path(item);
988         if (remove_dir_recursive(path) < 0) {
989                 g_warning("can't remove directory `%s'\n", path);
990                 g_free(path);
991                 return -1;
992         }
993
994         g_free(path);
995         folder_item_remove(item);
996         return 0;
997 }
998
999 static MsgInfo *mh_parse_msg(const gchar *file, FolderItem *item)
1000 {
1001         MsgInfo *msginfo;
1002         MsgFlags flags;
1003
1004         cm_return_val_if_fail(item != NULL, NULL);
1005         cm_return_val_if_fail(file != NULL, NULL);
1006
1007         flags.perm_flags = MSG_NEW|MSG_UNREAD;
1008         flags.tmp_flags = 0;
1009
1010         if (folder_has_parent_of_type(item, F_QUEUE)) {
1011                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
1012         } else if (folder_has_parent_of_type(item, F_DRAFT)) {
1013                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
1014         }
1015
1016         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
1017         if (!msginfo) return NULL;
1018
1019         msginfo->msgnum = atoi(file);
1020         msginfo->folder = item;
1021
1022         return msginfo;
1023 }
1024
1025 static gboolean mh_remove_missing_folder_items_func(GNode *node, gpointer data)
1026 {
1027         FolderItem *item;
1028         gchar *path;
1029
1030         cm_return_val_if_fail(node->data != NULL, FALSE);
1031
1032         if (G_NODE_IS_ROOT(node))
1033                 return FALSE;
1034
1035         item = FOLDER_ITEM(node->data);
1036
1037         path = folder_item_get_path(item);
1038         if (!is_dir_exist(path)) {
1039                 debug_print("folder '%s' not found. removing...\n", path?path:"(null)");
1040                 folder_item_remove(item);
1041         }
1042         g_free(path);
1043
1044         return FALSE;
1045 }
1046
1047 static void mh_remove_missing_folder_items(Folder *folder)
1048 {
1049         cm_return_if_fail(folder != NULL);
1050
1051         debug_print("searching missing folders...\n");
1052
1053         g_node_traverse(folder->node, G_POST_ORDER, G_TRAVERSE_ALL, -1,
1054                         mh_remove_missing_folder_items_func, folder);
1055 }
1056
1057 static void mh_scan_tree_recursive(FolderItem *item)
1058 {
1059         Folder *folder;
1060 #ifdef G_OS_WIN32
1061         GDir *dir;
1062 #else
1063         DIR *dp;
1064         struct dirent *d;
1065 #endif
1066         const gchar *dir_name;
1067         struct stat s;
1068         gchar *real_path, *entry, *utf8entry, *utf8name;
1069         gint n_msg = 0;
1070
1071         cm_return_if_fail(item != NULL);
1072         cm_return_if_fail(item->folder != NULL);
1073
1074         folder = item->folder;
1075
1076         real_path = item->path ? mh_filename_from_utf8(item->path) : g_strdup(".");
1077 #ifdef G_OS_WIN32
1078         dir = g_dir_open(real_path, 0, NULL);
1079         if (!dir) {
1080                 g_warning("failed to open directory: %s\n", real_path);
1081                 g_free(real_path);
1082                 return;
1083         }
1084 #else
1085         dp = opendir(real_path);
1086         if (!dp) {
1087                 FILE_OP_ERROR(real_path, "opendir");
1088                 return;
1089         }
1090 #endif
1091         g_free(real_path);
1092
1093         debug_print("scanning %s ...\n",
1094                     item->path ? item->path
1095                     : LOCAL_FOLDER(item->folder)->rootpath);
1096         if (folder->ui_func)
1097                 folder->ui_func(folder, item, folder->ui_func_data);
1098
1099 #ifdef G_OS_WIN32
1100         while ((dir_name = g_dir_read_name(dir)) != NULL) {
1101 #else
1102         while ((d = readdir(dp)) != NULL) {
1103                 dir_name = d->d_name;
1104 #endif
1105                 if (dir_name[0] == '.') continue;
1106
1107                 utf8name = mh_filename_to_utf8(dir_name);
1108                 if (item->path)
1109                         utf8entry = g_strconcat(item->path, G_DIR_SEPARATOR_S,
1110                                                 utf8name, NULL);
1111                 else
1112                         utf8entry = g_strdup(utf8name);
1113                 entry = mh_filename_from_utf8(utf8entry);
1114
1115                 if (
1116 #if !defined(G_OS_WIN32) && !defined(MAEMO) && defined(HAVE_DIRENT_D_TYPE)
1117                         d->d_type == DT_DIR ||
1118                         (d->d_type == DT_UNKNOWN &&
1119 #endif
1120                         g_stat(entry, &s) == 0 && S_ISDIR(s.st_mode)
1121 #if !defined(G_OS_WIN32) && !defined(MAEMO) && defined(HAVE_DIRENT_D_TYPE)
1122                         )
1123 #endif
1124                    ) {
1125                         FolderItem *new_item = NULL;
1126                         GNode *node;
1127
1128                         node = item->node;
1129                         for (node = node->children; node != NULL; node = node->next) {
1130                                 FolderItem *cur_item = FOLDER_ITEM(node->data);
1131                                 gchar *curpath = mh_filename_from_utf8(cur_item->path);
1132                                 if (!strcmp2(curpath, entry)) {
1133                                         new_item = cur_item;
1134                                         g_free(curpath);
1135                                         break;
1136                                 }
1137                                 g_free(curpath);
1138                         }
1139                         if (!new_item) {
1140                                 debug_print("new folder '%s' found.\n", entry);
1141                                 new_item = folder_item_new(folder, utf8name, utf8entry);
1142                                 folder_item_append(item, new_item);
1143                         }
1144
1145                         if (!item->path) {
1146                                 if (!folder->inbox &&
1147                                     !strcmp(dir_name, INBOX_DIR)) {
1148                                         new_item->stype = F_INBOX;
1149                                         folder->inbox = new_item;
1150                                 } else if (!folder->outbox &&
1151                                            !strcmp(dir_name, OUTBOX_DIR)) {
1152                                         new_item->stype = F_OUTBOX;
1153                                         folder->outbox = new_item;
1154                                 } else if (!folder->draft &&
1155                                            !strcmp(dir_name, DRAFT_DIR)) {
1156                                         new_item->stype = F_DRAFT;
1157                                         folder->draft = new_item;
1158                                 } else if (!folder->queue &&
1159                                            !strcmp(dir_name, QUEUE_DIR)) {
1160                                         new_item->stype = F_QUEUE;
1161                                         folder->queue = new_item;
1162                                 } else if (!folder->trash &&
1163                                            !strcmp(dir_name, TRASH_DIR)) {
1164                                         new_item->stype = F_TRASH;
1165                                         folder->trash = new_item;
1166                                 }
1167                         }
1168
1169                         mh_scan_tree_recursive(new_item);
1170                 } else if (to_number(dir_name) > 0) n_msg++;
1171
1172                 g_free(entry);
1173                 g_free(utf8entry);
1174                 g_free(utf8name);
1175         }
1176
1177 #ifdef G_OS_WIN32
1178         g_dir_close(dir);
1179 #else
1180         closedir(dp);
1181 #endif
1182
1183         mh_set_mtime(folder, item);
1184 }
1185
1186 static gboolean mh_rename_folder_func(GNode *node, gpointer data)
1187 {
1188         FolderItem *item = node->data;
1189         gchar **paths = data;
1190         const gchar *oldpath = paths[0];
1191         const gchar *newpath = paths[1];
1192         gchar *base;
1193         gchar *new_itempath;
1194         gint oldpathlen;
1195
1196         oldpathlen = strlen(oldpath);
1197         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
1198                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
1199                 return TRUE;
1200         }
1201
1202         base = item->path + oldpathlen;
1203         while (*base == G_DIR_SEPARATOR) base++;
1204         if (*base == '\0')
1205                 new_itempath = g_strdup(newpath);
1206         else
1207                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
1208                                            NULL);
1209         g_free(item->path);
1210         item->path = new_itempath;
1211
1212         return FALSE;
1213 }
1214
1215 static gchar *mh_filename_from_utf8(const gchar *path)
1216 {
1217         gchar *real_path = g_filename_from_utf8(path, -1, NULL, NULL, NULL);
1218
1219         if (!real_path) {
1220                 g_warning("mh_filename_from_utf8: failed to convert character set\n");
1221                 real_path = g_strdup(path);
1222         }
1223
1224         return real_path;
1225 }
1226
1227 static gchar *mh_filename_to_utf8(const gchar *path)
1228 {
1229         gchar *utf8path = g_filename_to_utf8(path, -1, NULL, NULL, NULL);
1230         if (!utf8path) {
1231                 g_warning("mh_filename_to_utf8: failed to convert character set\n");
1232                 utf8path = g_strdup(path);
1233         }
1234
1235         return utf8path;
1236 }
1237
1238 static gint sort_cache_list_by_msgnum(gconstpointer a, gconstpointer b)
1239 {
1240         MsgInfo *msginfo_a = (MsgInfo *) a;
1241         MsgInfo *msginfo_b = (MsgInfo *) b;
1242
1243         return (msginfo_a->msgnum - msginfo_b->msgnum);
1244 }
1245
1246 static gchar *get_unseen_seq_name(void)
1247 {
1248         static gchar *seq_name = NULL;
1249         if (!seq_name) {
1250                 gchar buf[BUFFSIZE];
1251                 gchar *tmp;
1252                 gchar *profile_path = g_strconcat(
1253                         get_home_dir(), G_DIR_SEPARATOR_S,
1254                         ".mh_profile", NULL);
1255                 FILE *fp = g_fopen(profile_path, "r");
1256                 if (fp) {
1257                         while (fgets(buf, sizeof(buf), fp) != NULL) {
1258                                 if (!strncmp(buf, "Unseen-Sequence:", strlen("Unseen-Sequence:"))) {
1259                                         gchar *seq_tmp = buf+strlen("Unseen-Sequence:");
1260                                         while (*seq_tmp == ' ')
1261                                                 seq_tmp++;
1262                                         seq_name = g_strdup(seq_tmp);
1263                                         seq_name = strretchomp(seq_name);
1264                                         break;
1265                                 }
1266                         }
1267                         fclose(fp);
1268                 }
1269                 if (!seq_name)
1270                         seq_name = g_strdup("unseen");
1271                 tmp = g_strdup_printf("%s:", seq_name);
1272                 g_free(seq_name);
1273                 seq_name = tmp;
1274         }
1275         return seq_name;        
1276 }
1277
1278 static void mh_write_sequences(FolderItem *item, gboolean remove_unseen)
1279 {
1280         gchar *mh_sequences_old, *mh_sequences_new;
1281         FILE *mh_sequences_old_fp, *mh_sequences_new_fp;
1282         gchar buf[BUFFSIZE];
1283         gchar *path = NULL;
1284         gboolean err = FALSE;
1285         START_TIMING("");
1286
1287         if (!item)
1288                 return;
1289         
1290         path = folder_item_get_path(item);
1291
1292         mh_sequences_old = g_strconcat(path, G_DIR_SEPARATOR_S,
1293                                             ".mh_sequences", NULL);
1294         mh_sequences_new = g_strconcat(path, G_DIR_SEPARATOR_S,
1295                                             ".mh_sequences.new", NULL);
1296         if ((mh_sequences_new_fp = g_fopen(mh_sequences_new, "w+b")) != NULL) {
1297                 GSList *msglist = folder_item_get_msg_list(item);
1298                 GSList *cur;
1299                 MsgInfo *info = NULL;
1300                 gint start = -1, end = -1;
1301                 gchar *sequence = g_strdup("");
1302                 gint seq_len = 0;
1303                 msglist = g_slist_sort(msglist, sort_cache_list_by_msgnum);
1304                 cur = msglist;
1305                 
1306                 /* write the unseen sequence if we don't have to scrap it */
1307                 if (!remove_unseen) do {
1308                         info = (MsgInfo *)(cur ? cur->data:NULL);
1309                         if (info && (MSG_IS_UNREAD(info->flags) || MSG_IS_NEW(info->flags))) {
1310                                 if (start < 0)
1311                                         start = end = info->msgnum;
1312                                 else
1313                                         end = info->msgnum;
1314                         } else {
1315                                 if (start > 0 && end > 0) {
1316                                         gchar tmp[32];
1317                                         gint tmp_len = 0;
1318                                         if (start != end)
1319                                                 snprintf(tmp, 31, " %d-%d", start, end);
1320                                         else
1321                                                 snprintf(tmp, 31, " %d", start);
1322                                         
1323                                         tmp_len = strlen(tmp);
1324                                         sequence = g_realloc(sequence, seq_len+tmp_len+1);
1325                                         strcpy(sequence+seq_len, tmp);
1326                                         seq_len += tmp_len;
1327
1328                                         start = end = -1;
1329                                 }
1330                         }
1331                         cur = cur ? cur->next:NULL;
1332                 } while (cur || (start > 0 && end > 0));
1333                 if (sequence && *sequence) {
1334                         if (fprintf(mh_sequences_new_fp, "%s%s\n", 
1335                                         get_unseen_seq_name(), sequence) < 0)
1336                                 err = TRUE;
1337                         else
1338                                 debug_print("wrote unseen sequence: '%s%s'\n", 
1339                                         get_unseen_seq_name(), sequence);
1340                 }
1341                 /* rewrite the rest of the file */
1342                 if ((mh_sequences_old_fp = g_fopen(mh_sequences_old, "r+b")) != NULL) {
1343                         while (fgets(buf, sizeof(buf), mh_sequences_old_fp) != NULL) {
1344                                 if (strncmp(buf, get_unseen_seq_name(), strlen(get_unseen_seq_name())))
1345                                         if (fprintf(mh_sequences_new_fp, "%s", buf) < 0) {
1346                                                 err = TRUE;
1347                                                 break;
1348                                         }
1349                         }
1350                         fclose(mh_sequences_old_fp);
1351                 }
1352                 
1353                 fflush(mh_sequences_new_fp);
1354 #if 0
1355                 fsync(fileno(mh_sequences_new_fp));
1356 #endif
1357                 if (fclose(mh_sequences_new_fp) == EOF)
1358                         err = TRUE;
1359
1360                 if (!err)
1361                         g_rename(mh_sequences_new, mh_sequences_old);
1362                 g_free(sequence);
1363                 procmsg_msg_list_free(msglist);
1364         }
1365         g_free(mh_sequences_old);
1366         g_free(mh_sequences_new);
1367         g_free(path);
1368
1369         END_TIMING();
1370 }
1371
1372 static int mh_item_close(Folder *folder, FolderItem *item)
1373 {
1374         time_t last_mtime = (time_t)0;
1375         gboolean need_scan = mh_scan_required(item->folder, item);
1376         last_mtime = item->mtime;
1377
1378         mh_write_sequences(item, FALSE);
1379
1380         if (item->mtime == last_mtime && !need_scan) {
1381                 mh_set_mtime(folder, item);
1382         }
1383
1384         return 0;
1385 }
1386
1387 static void mh_set_mtime(Folder *folder, FolderItem *item)
1388 {
1389         struct stat s;
1390         gchar *path = folder_item_get_path(item);
1391
1392         cm_return_if_fail(path != NULL);
1393
1394         if (g_stat(path, &s) < 0) {
1395                 FILE_OP_ERROR(path, "stat");
1396                 g_free(path);
1397                 return;
1398         }
1399
1400         item->mtime = s.st_mtime;
1401         debug_print("MH: forced mtime of %s to %ld\n", item->name?item->name:"(null)", item->mtime);
1402         g_free(path);
1403 }