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