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