2006-05-29 [mones] 2.2.0cvs62
[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         gboolean remove_special_headers = FALSE;
465         MsgInfoList *cur = NULL;
466         gint curnum = 0, total = 0;
467         gchar *srcpath = NULL;
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 (dest->last_num < 0) {
482                 mh_get_last_num(folder, dest);
483                 if (dest->last_num < 0) return -1;
484         }
485
486         if ((MSG_IS_QUEUED(msginfo->flags) || MSG_IS_DRAFT(msginfo->flags))
487         && !folder_has_parent_of_type(dest, F_QUEUE)
488         && !folder_has_parent_of_type(dest, F_DRAFT)) {
489                 /* as every msginfo comes from the same folder, it is supposed they
490                  * will either match the preceding condition either all or none.
491                  */
492                 remove_special_headers = TRUE;
493         } else if (!(MSG_IS_QUEUED(msginfo->flags) || MSG_IS_DRAFT(msginfo->flags))
494         && (folder_has_parent_of_type(dest, F_QUEUE)
495          || folder_has_parent_of_type(dest, F_DRAFT))) {
496                 return -1;
497         } 
498
499         prefs = dest->prefs;
500
501         srcpath = folder_item_get_path(msginfo->folder);
502
503         total = g_slist_length(msglist);
504         if (total > 100) {
505                 if (MSG_IS_MOVE(msginfo->flags))
506                         statusbar_print_all(_("Moving messages..."));
507                 else
508                         statusbar_print_all(_("Copying messages..."));
509         }
510         for (cur = msglist; cur; cur = cur->next) {
511                 gboolean moved = FALSE;
512                 msginfo = (MsgInfo *)cur->data;
513                 if (!msginfo) {
514                         goto err_reset_status;
515                 }
516                 srcfile = g_strconcat(srcpath, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
517                 if (!srcfile) {
518                         goto err_reset_status;
519                 }
520                 destfile = mh_get_new_msg_filename(dest);
521                 if (!destfile) {
522                         g_free(srcfile);
523                         goto err_reset_status;
524                 }
525
526                 if (total > 100) {
527                         statusbar_progress_all(curnum, total, 100);
528                         if (curnum % 100 == 0)
529                                 GTK_EVENTS_FLUSH();
530                         curnum++;
531                 }
532
533                 debug_print("Copying message %s%c%d to %s ...\n",
534                             msginfo->folder->path, G_DIR_SEPARATOR,
535                             msginfo->msgnum, dest->path);
536
537
538                 if (remove_special_headers) {
539                         if (procmsg_remove_special_headers(srcfile, destfile) !=0) {
540                                 g_free(srcfile);
541                                 g_free(destfile);
542                                 goto err_reset_status;
543                         }
544                 } else if (MSG_IS_MOVE(msginfo->flags)) {
545                         if (move_file(srcfile, destfile, TRUE) < 0) {
546                                 FILE_OP_ERROR(srcfile, "move");
547                                 if (copy_file(srcfile, destfile, TRUE) < 0) {
548                                         FILE_OP_ERROR(srcfile, "copy");
549                                         g_free(srcfile);
550                                         g_free(destfile);
551                                         goto err_reset_status;
552                                 }
553                         }
554                 } else if (copy_file(srcfile, destfile, TRUE) < 0) {
555                         FILE_OP_ERROR(srcfile, "copy");
556                         g_free(srcfile);
557                         g_free(destfile);
558                         goto err_reset_status;
559                 } 
560                 if (prefs && prefs->enable_folder_chmod && prefs->folder_chmod) {
561                         if (chmod(destfile, prefs->folder_chmod) < 0)
562                                 FILE_OP_ERROR(destfile, "chmod");
563
564                         /* for mark file */
565                         filemode = prefs->folder_chmod;
566                         if (filemode & S_IRGRP) filemode |= S_IWGRP;
567                         if (filemode & S_IROTH) filemode |= S_IWOTH;
568                 }
569                 if (relation)
570                         g_relation_insert(relation, msginfo, GINT_TO_POINTER(dest->last_num+1));
571                 g_free(srcfile);
572                 g_free(destfile);
573                 dest->last_num++;
574         }
575
576         g_free(srcpath);
577         mh_write_sequences(dest, TRUE);
578
579         dest_need_scan = mh_scan_required(dest->folder, dest);
580         if (!dest_need_scan)
581                 dest->mtime = time(NULL);
582         
583         if (total > 100) {
584                 statusbar_progress_all(0,0,0);
585                 statusbar_pop_all();
586         }
587         return dest->last_num;
588 err_reset_status:
589         g_free(srcpath);
590         mh_write_sequences(dest, TRUE);
591         if (total > 100) {
592                 statusbar_progress_all(0,0,0);
593                 statusbar_pop_all();
594         }
595         return -1;
596
597 }
598
599 static gint mh_remove_msg(Folder *folder, FolderItem *item, gint num)
600 {
601         gboolean need_scan = FALSE;
602         gchar *file;
603
604         g_return_val_if_fail(item != NULL, -1);
605
606         file = mh_fetch_msg(folder, item, num);
607         g_return_val_if_fail(file != NULL, -1);
608
609         need_scan = mh_scan_required(folder, item);
610
611         if (g_unlink(file) < 0) {
612                 FILE_OP_ERROR(file, "unlink");
613                 g_free(file);
614                 return -1;
615         }
616
617         if (!need_scan)
618                 item->mtime = time(NULL);
619
620         g_free(file);
621         return 0;
622 }
623
624 static gint mh_remove_msgs(Folder *folder, FolderItem *item, 
625                     MsgInfoList *msglist, GRelation *relation)
626 {
627         gboolean need_scan = FALSE;
628         gchar *path, *file;
629         MsgInfoList *cur;
630
631         g_return_val_if_fail(item != NULL, -1);
632
633         path = folder_item_get_path(item);
634         
635         for (cur = msglist; cur; cur = cur->next) {
636                 MsgInfo *msginfo = (MsgInfo *)cur->data;
637                 if (msginfo == NULL)
638                         continue;
639                 file = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
640                 if (file == NULL)
641                         continue;
642                 
643                 if (g_unlink(file) < 0) {
644                         g_free(file);
645                         continue;
646                 }
647                 
648                 g_free(file);
649         }
650
651         need_scan = mh_scan_required(folder, item);
652
653         if (!need_scan)
654                 item->mtime = time(NULL);
655
656         g_free(path);
657         return 0;
658 }
659
660 static gint mh_remove_all_msg(Folder *folder, FolderItem *item)
661 {
662         gchar *path;
663         gint val;
664
665         g_return_val_if_fail(item != NULL, -1);
666
667         path = folder_item_get_path(item);
668         g_return_val_if_fail(path != NULL, -1);
669         val = remove_all_numbered_files(path);
670         g_free(path);
671
672         mh_write_sequences(item, TRUE);
673
674         return val;
675 }
676
677 static gboolean mh_is_msg_changed(Folder *folder, FolderItem *item,
678                                   MsgInfo *msginfo)
679 {
680         struct stat s;
681
682         if (g_stat(itos(msginfo->msgnum), &s) < 0 ||
683             msginfo->size  != s.st_size || (
684                 (msginfo->mtime - s.st_mtime != 0) &&
685                 (msginfo->mtime - s.st_mtime != 3600) &&
686                 (msginfo->mtime - s.st_mtime != -3600)))
687                 return TRUE;
688
689         return FALSE;
690 }
691
692 static gint mh_scan_tree(Folder *folder)
693 {
694         FolderItem *item;
695         gchar *rootpath;
696
697         g_return_val_if_fail(folder != NULL, -1);
698
699         if (!folder->node) {
700                 item = folder_item_new(folder, folder->name, NULL);
701                 item->folder = folder;
702                 folder->node = item->node = g_node_new(item);
703         } else
704                 item = FOLDER_ITEM(folder->node->data);
705
706         rootpath = folder_item_get_path(item);
707         if (change_dir(rootpath) < 0) {
708                 g_free(rootpath);
709                 return -1;
710         }
711         g_free(rootpath);
712
713         mh_create_tree(folder);
714         mh_remove_missing_folder_items(folder);
715         mh_scan_tree_recursive(item);
716
717         return 0;
718 }
719
720 #define MAKE_DIR_IF_NOT_EXIST(dir) \
721 { \
722         if (!is_dir_exist(dir)) { \
723                 if (is_file_exist(dir)) { \
724                         g_warning("File `%s' already exists.\n" \
725                                     "Can't create folder.", dir); \
726                         return -1; \
727                 } \
728                 if (make_dir(dir) < 0) \
729                         return -1; \
730         } \
731 }
732
733 static gint mh_create_tree(Folder *folder)
734 {
735         gchar *rootpath;
736
737         g_return_val_if_fail(folder != NULL, -1);
738
739         CHDIR_RETURN_VAL_IF_FAIL(get_mail_base_dir(), -1);
740         rootpath = LOCAL_FOLDER(folder)->rootpath;
741         MAKE_DIR_IF_NOT_EXIST(rootpath);
742         CHDIR_RETURN_VAL_IF_FAIL(rootpath, -1);
743         MAKE_DIR_IF_NOT_EXIST(INBOX_DIR);
744         MAKE_DIR_IF_NOT_EXIST(OUTBOX_DIR);
745         MAKE_DIR_IF_NOT_EXIST(QUEUE_DIR);
746         MAKE_DIR_IF_NOT_EXIST(DRAFT_DIR);
747         MAKE_DIR_IF_NOT_EXIST(TRASH_DIR);
748
749         return 0;
750 }
751
752 #undef MAKE_DIR_IF_NOT_EXIST
753
754 static gchar *mh_item_get_path(Folder *folder, FolderItem *item)
755 {
756         gchar *folder_path, *path;
757         gchar *real_path;
758         g_return_val_if_fail(folder != NULL, NULL);
759         g_return_val_if_fail(item != NULL, NULL);
760
761         folder_path = g_strdup(LOCAL_FOLDER(folder)->rootpath);
762         g_return_val_if_fail(folder_path != NULL, NULL);
763
764         /* FIXME: [W32] The code below does not correctly merge
765            relative filenames; there should be a function to handle
766            this.  */
767         if ( !is_relative_filename (folder_path) ) {
768                 if (item->path)
769                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
770                                            item->path, NULL);
771                 else
772                         path = g_strdup(folder_path);
773         } else {
774                 if (item->path)
775                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
776                                            folder_path, G_DIR_SEPARATOR_S,
777                                            item->path, NULL);
778                 else
779                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
780                                            folder_path, NULL);
781         }
782         g_free(folder_path);
783         real_path = mh_filename_from_utf8(path);
784         if (!is_dir_exist(real_path) && is_dir_exist(path)) {
785                 /* mmh, older version did put utf8 filenames instead of
786                  * the correct encoding */
787                 rename(path, real_path);
788                 folder_item_scan(item);
789         }
790
791         g_free(path);
792         return real_path;
793 }
794
795 static FolderItem *mh_create_folder(Folder *folder, FolderItem *parent,
796                                     const gchar *name)
797 {
798         gchar *path, *real_name;
799         gchar *fullpath;
800         FolderItem *new_item;
801         gchar *mh_sequences_filename;
802         FILE *mh_sequences_file;
803
804         g_return_val_if_fail(folder != NULL, NULL);
805         g_return_val_if_fail(parent != NULL, NULL);
806         g_return_val_if_fail(name != NULL, NULL);
807
808         path = folder_item_get_path(parent);
809         if (!is_dir_exist(path)) 
810                 if (make_dir_hier(path) != 0)
811                         return NULL;
812                 
813         real_name = mh_filename_from_utf8(name);
814         fullpath = g_strconcat(path, G_DIR_SEPARATOR_S, real_name, NULL);
815         g_free(real_name);
816         g_free(path);
817
818         if (make_dir(fullpath) < 0) {
819                 g_free(fullpath);
820                 return NULL;
821         }
822
823         g_free(fullpath);
824
825         if (parent->path)
826                 path = g_strconcat(parent->path, G_DIR_SEPARATOR_S, name,
827                                    NULL);
828         else
829                 path = g_strdup(name);
830         new_item = folder_item_new(folder, name, path);
831         folder_item_append(parent, new_item);
832
833         g_free(path);
834
835         path = folder_item_get_path(new_item);
836         mh_sequences_filename = g_strconcat(path, G_DIR_SEPARATOR_S,
837                                             ".mh_sequences", NULL);
838         if ((mh_sequences_file = g_fopen(mh_sequences_filename, "a+b")) != NULL) {
839                 fclose(mh_sequences_file);
840         }
841         g_free(mh_sequences_filename);
842         g_free(path);
843
844         return new_item;
845 }
846
847 static gint mh_rename_folder(Folder *folder, FolderItem *item,
848                              const gchar *name)
849 {
850         gchar *real_name;
851         gchar *oldpath;
852         gchar *dirname;
853         gchar *newpath, *utf8newpath;
854         gchar *paths[2];
855
856         g_return_val_if_fail(folder != NULL, -1);
857         g_return_val_if_fail(item != NULL, -1);
858         g_return_val_if_fail(item->path != NULL, -1);
859         g_return_val_if_fail(name != NULL, -1);
860
861         oldpath = folder_item_get_path(item);
862         if (!is_dir_exist(oldpath))
863                 make_dir_hier(oldpath);
864
865         dirname = g_path_get_dirname(oldpath);
866         real_name = mh_filename_from_utf8(name);
867         newpath = g_strconcat(dirname, G_DIR_SEPARATOR_S, real_name, NULL);
868         g_free(real_name);
869
870         if (g_rename(oldpath, newpath) < 0) {
871                 FILE_OP_ERROR(oldpath, "rename");
872                 g_free(oldpath);
873                 g_free(newpath);
874                 return -1;
875         }
876
877         g_free(oldpath);
878         g_free(newpath);
879
880         if (strchr(item->path, G_DIR_SEPARATOR) != NULL) {
881                 dirname = g_path_get_dirname(item->path);
882                 utf8newpath = g_strconcat(dirname, G_DIR_SEPARATOR_S,
883                                           name, NULL);
884                 g_free(dirname);
885         } else
886                 utf8newpath = g_strdup(name);
887
888         g_free(item->name);
889         item->name = g_strdup(name);
890
891         paths[0] = g_strdup(item->path);
892         paths[1] = utf8newpath;
893         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
894                         mh_rename_folder_func, paths);
895
896         g_free(paths[0]);
897         g_free(paths[1]);
898         return 0;
899 }
900
901 static gint mh_remove_folder(Folder *folder, FolderItem *item)
902 {
903         gchar *path;
904
905         g_return_val_if_fail(folder != NULL, -1);
906         g_return_val_if_fail(item != NULL, -1);
907         g_return_val_if_fail(item->path != NULL, -1);
908
909         path = folder_item_get_path(item);
910         if (remove_dir_recursive(path) < 0) {
911                 g_warning("can't remove directory `%s'\n", path);
912                 g_free(path);
913                 return -1;
914         }
915
916         g_free(path);
917         folder_item_remove(item);
918         return 0;
919 }
920
921 static MsgInfo *mh_parse_msg(const gchar *file, FolderItem *item)
922 {
923         MsgInfo *msginfo;
924         MsgFlags flags;
925
926         g_return_val_if_fail(item != NULL, NULL);
927         g_return_val_if_fail(file != NULL, NULL);
928
929         flags.perm_flags = MSG_NEW|MSG_UNREAD;
930         flags.tmp_flags = 0;
931
932         if (folder_has_parent_of_type(item, F_QUEUE)) {
933                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
934         } else if (folder_has_parent_of_type(item, F_DRAFT)) {
935                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
936         }
937
938         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
939         if (!msginfo) return NULL;
940
941         msginfo->msgnum = atoi(file);
942         msginfo->folder = item;
943
944         return msginfo;
945 }
946
947 static gboolean mh_remove_missing_folder_items_func(GNode *node, gpointer data)
948 {
949         FolderItem *item;
950         gchar *path;
951
952         g_return_val_if_fail(node->data != NULL, FALSE);
953
954         if (G_NODE_IS_ROOT(node))
955                 return FALSE;
956
957         item = FOLDER_ITEM(node->data);
958
959         path = folder_item_get_path(item);
960         if (!is_dir_exist(path)) {
961                 debug_print("folder '%s' not found. removing...\n", path);
962                 folder_item_remove(item);
963         }
964         g_free(path);
965
966         return FALSE;
967 }
968
969 static void mh_remove_missing_folder_items(Folder *folder)
970 {
971         g_return_if_fail(folder != NULL);
972
973         debug_print("searching missing folders...\n");
974
975         g_node_traverse(folder->node, G_POST_ORDER, G_TRAVERSE_ALL, -1,
976                         mh_remove_missing_folder_items_func, folder);
977 }
978
979 static void mh_scan_tree_recursive(FolderItem *item)
980 {
981         Folder *folder;
982 #ifdef G_OS_WIN32
983         GDir *dir;
984 #else
985         DIR *dp;
986         struct dirent *d;
987 #endif
988         const gchar *dir_name;
989         struct stat s;
990         gchar *real_path, *entry, *utf8entry, *utf8name;
991         gint n_msg = 0;
992
993         g_return_if_fail(item != NULL);
994         g_return_if_fail(item->folder != NULL);
995
996         folder = item->folder;
997
998         real_path = item->path ? mh_filename_from_utf8(item->path) : g_strdup(".");
999 #ifdef G_OS_WIN32
1000         dir = g_dir_open(real_path, 0, NULL);
1001         if (!dir) {
1002                 g_warning("failed to open directory: %s\n", real_path);
1003                 g_free(real_path);
1004                 return;
1005         }
1006 #else
1007         dp = opendir(real_path);
1008         if (!dp) {
1009                 FILE_OP_ERROR(real_path, "opendir");
1010                 return;
1011         }
1012 #endif
1013         g_free(real_path);
1014
1015         debug_print("scanning %s ...\n",
1016                     item->path ? item->path
1017                     : LOCAL_FOLDER(item->folder)->rootpath);
1018         if (folder->ui_func)
1019                 folder->ui_func(folder, item, folder->ui_func_data);
1020
1021 #ifdef G_OS_WIN32
1022         while ((dir_name = g_dir_read_name(dir)) != NULL) {
1023 #else
1024         while ((d = readdir(dp)) != NULL) {
1025                 dir_name = d->d_name;
1026 #endif
1027                 if (dir_name[0] == '.') continue;
1028
1029                 utf8name = mh_filename_to_utf8(dir_name);
1030                 if (item->path)
1031                         utf8entry = g_strconcat(item->path, G_DIR_SEPARATOR_S,
1032                                                 utf8name, NULL);
1033                 else
1034                         utf8entry = g_strdup(utf8name);
1035                 entry = mh_filename_from_utf8(utf8entry);
1036
1037                 if (
1038 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
1039                         d->d_type == DT_DIR ||
1040                         (d->d_type == DT_UNKNOWN &&
1041 #endif
1042                         g_stat(entry, &s) == 0 && S_ISDIR(s.st_mode)
1043 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
1044                         )
1045 #endif
1046                    ) {
1047                         FolderItem *new_item = NULL;
1048                         GNode *node;
1049
1050                         node = item->node;
1051                         for (node = node->children; node != NULL; node = node->next) {
1052                                 FolderItem *cur_item = FOLDER_ITEM(node->data);
1053                                 if (!strcmp2(cur_item->path, entry)) {
1054                                         new_item = cur_item;
1055                                         break;
1056                                 }
1057                         }
1058                         if (!new_item) {
1059                                 debug_print("new folder '%s' found.\n", entry);
1060                                 new_item = folder_item_new(folder, utf8name, utf8entry);
1061                                 folder_item_append(item, new_item);
1062                         }
1063
1064                         if (!item->path) {
1065                                 if (!folder->inbox &&
1066                                     !strcmp(dir_name, INBOX_DIR)) {
1067                                         new_item->stype = F_INBOX;
1068                                         folder->inbox = new_item;
1069                                 } else if (!folder->outbox &&
1070                                            !strcmp(dir_name, OUTBOX_DIR)) {
1071                                         new_item->stype = F_OUTBOX;
1072                                         folder->outbox = new_item;
1073                                 } else if (!folder->draft &&
1074                                            !strcmp(dir_name, DRAFT_DIR)) {
1075                                         new_item->stype = F_DRAFT;
1076                                         folder->draft = new_item;
1077                                 } else if (!folder->queue &&
1078                                            !strcmp(dir_name, QUEUE_DIR)) {
1079                                         new_item->stype = F_QUEUE;
1080                                         folder->queue = new_item;
1081                                 } else if (!folder->trash &&
1082                                            !strcmp(dir_name, TRASH_DIR)) {
1083                                         new_item->stype = F_TRASH;
1084                                         folder->trash = new_item;
1085                                 }
1086                         }
1087
1088                         mh_scan_tree_recursive(new_item);
1089                 } else if (to_number(dir_name) > 0) n_msg++;
1090
1091                 g_free(entry);
1092                 g_free(utf8entry);
1093                 g_free(utf8name);
1094         }
1095
1096 #ifdef G_OS_WIN32
1097         g_dir_close(dir);
1098 #else
1099         closedir(dp);
1100 #endif
1101
1102         item->mtime = time(NULL);
1103 }
1104
1105 static gboolean mh_rename_folder_func(GNode *node, gpointer data)
1106 {
1107         FolderItem *item = node->data;
1108         gchar **paths = data;
1109         const gchar *oldpath = paths[0];
1110         const gchar *newpath = paths[1];
1111         gchar *base;
1112         gchar *new_itempath;
1113         gint oldpathlen;
1114
1115         oldpathlen = strlen(oldpath);
1116         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
1117                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
1118                 return TRUE;
1119         }
1120
1121         base = item->path + oldpathlen;
1122         while (*base == G_DIR_SEPARATOR) base++;
1123         if (*base == '\0')
1124                 new_itempath = g_strdup(newpath);
1125         else
1126                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
1127                                            NULL);
1128         g_free(item->path);
1129         item->path = new_itempath;
1130
1131         return FALSE;
1132 }
1133
1134 static gchar *mh_filename_from_utf8(const gchar *path)
1135 {
1136         gchar *real_path = g_filename_from_utf8(path, -1, NULL, NULL, NULL);
1137
1138         if (!real_path) {
1139                 g_warning("mh_filename_from_utf8: faild to convert character set\n");
1140                 real_path = g_strdup(path);
1141         }
1142
1143         return real_path;
1144 }
1145
1146 static gchar *mh_filename_to_utf8(const gchar *path)
1147 {
1148         gchar *utf8path = g_filename_to_utf8(path, -1, NULL, NULL, NULL);
1149         if (!utf8path) {
1150                 g_warning("mh_filename_to_utf8: faild to convert character set\n");
1151                 utf8path = g_strdup(path);
1152         }
1153
1154         return utf8path;
1155 }
1156
1157 static gint sort_cache_list_by_msgnum(gconstpointer a, gconstpointer b)
1158 {
1159         MsgInfo *msginfo_a = (MsgInfo *) a;
1160         MsgInfo *msginfo_b = (MsgInfo *) b;
1161
1162         return (msginfo_a->msgnum - msginfo_b->msgnum);
1163 }
1164
1165 static gchar *get_unseen_seq_name(void)
1166 {
1167         static gchar *seq_name = NULL;
1168         if (!seq_name) {
1169                 gchar buf[BUFFSIZE];
1170                 gchar *tmp;
1171                 gchar *profile_path = g_strconcat(
1172                         g_get_home_dir(), G_DIR_SEPARATOR_S,
1173                         ".mh_profile", NULL);
1174                 FILE *fp = g_fopen(profile_path, "r");
1175                 if (fp) {
1176                         while (fgets(buf, sizeof(buf), fp) != NULL) {
1177                                 if (!strncmp(buf, "Unseen-Sequence:", strlen("Unseen-Sequence:"))) {
1178                                         gchar *seq_tmp = buf+strlen("Unseen-Sequence:");
1179                                         while (*seq_tmp == ' ')
1180                                                 seq_tmp++;
1181                                         seq_name = g_strdup(seq_tmp);
1182                                         seq_name = strretchomp(seq_name);
1183                                         break;
1184                                 }
1185                         }
1186                         fclose(fp);
1187                 }
1188                 if (!seq_name)
1189                         seq_name = g_strdup("unseen");
1190                 tmp = g_strdup_printf("%s:", seq_name);
1191                 g_free(seq_name);
1192                 seq_name = tmp;
1193         }
1194         return seq_name;        
1195 }
1196
1197 static gint mh_get_flags(Folder *folder, FolderItem *item,
1198                            MsgInfoList *msginfo_list, GRelation *msgflags)
1199 {
1200         gchar *mh_sequences_filename;
1201         FILE *mh_sequences_file;
1202         gchar buf[BUFFSIZE];
1203         gchar *unseen_list = NULL;
1204         gchar *path;
1205         MsgInfoList *mcur = NULL;
1206 /*
1207         GTimer *timer = g_timer_new();
1208         g_timer_start(timer);
1209 */
1210         if (!item)
1211                 return 0;
1212
1213         /* don't update from .mh_sequences if the item's opened: mails may have
1214          * been marked read/unread and it's not yet written in the file. */     
1215         if (item->opened)
1216                 return 0;
1217
1218         path = folder_item_get_path(item);
1219
1220         mh_sequences_filename = g_strconcat(path, G_DIR_SEPARATOR_S,
1221                                             ".mh_sequences", NULL);
1222         g_free(path);
1223         if ((mh_sequences_file = g_fopen(mh_sequences_filename, "r+b")) != NULL) {
1224                 while (fgets(buf, sizeof(buf), mh_sequences_file) != NULL) {
1225                         if (!strncmp(buf, get_unseen_seq_name(), strlen(get_unseen_seq_name()))) {
1226                                 unseen_list = g_strdup(buf+strlen(get_unseen_seq_name()));
1227                                 break;
1228                         }
1229                 }
1230                 fclose(mh_sequences_file);
1231         }
1232         
1233         g_free(mh_sequences_filename);
1234         
1235         if (unseen_list) {
1236                 gchar *cur = NULL;
1237                 gchar *token = NULL, *next = NULL, *boundary = NULL;
1238                 gint num = 0;
1239                 GHashTable *unseen_table = g_hash_table_new(g_direct_hash, g_direct_equal);
1240
1241                 cur = unseen_list = strretchomp(unseen_list);
1242                 debug_print("found unseen list in .mh_sequences: %s\n", unseen_list);
1243 next_token:
1244                 while (*cur && *cur == ' ')
1245                         cur++;
1246                 
1247                 if ((next = strchr(cur, ' ')) != NULL) {
1248                         token = cur;
1249                         cur = next+1;
1250                         *next = '\0';
1251                 } else {
1252                         token = cur;
1253                         cur = NULL;
1254                 }
1255                 
1256                 if ((boundary = strchr(token, '-')) != NULL) {
1257                         gchar *start, *end;
1258                         int i;
1259                         start = token;
1260                         end = boundary+1;
1261                         *boundary='\0';
1262                         for (i = atoi(start); i <= atoi(end); i++) {
1263                                 g_hash_table_insert(unseen_table, GINT_TO_POINTER(i), GINT_TO_POINTER(1));
1264                         }
1265                 } else if ((num = atoi(token)) > 0) {
1266                         g_hash_table_insert(unseen_table, GINT_TO_POINTER(num), GINT_TO_POINTER(1));
1267                 }
1268                 
1269                 if (cur)
1270                         goto next_token;
1271                 for (mcur = msginfo_list; mcur; mcur = mcur->next) {
1272                         MsgInfo *msginfo = (MsgInfo *)mcur->data;
1273                         MsgPermFlags flags = msginfo->flags.perm_flags;
1274                         if (g_hash_table_lookup(unseen_table, GINT_TO_POINTER(msginfo->msgnum))) {
1275                                 flags |= MSG_UNREAD;
1276                         } else if (!(flags & MSG_NEW)) { /* don't mark new msgs as read */
1277                                 flags &= ~(MSG_UNREAD);
1278                         }
1279                         if (flags != msginfo->flags.perm_flags)
1280                                 g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
1281                 }
1282                 g_hash_table_destroy(unseen_table);
1283                 g_free(unseen_list);
1284         }
1285 /*
1286         g_timer_stop(timer);
1287         printf("mh_get_flags: %f secs\n", g_timer_elapsed(timer, NULL));
1288         g_timer_destroy(timer);
1289 */
1290         return 0;
1291 }
1292
1293 static void mh_write_sequences(FolderItem *item, gboolean remove_unseen)
1294 {
1295         gchar *mh_sequences_old, *mh_sequences_new;
1296         FILE *mh_sequences_old_fp, *mh_sequences_new_fp;
1297         gchar buf[BUFFSIZE];
1298         gchar *path = NULL;
1299 /*
1300         GTimer *timer = g_timer_new();
1301         g_timer_start(timer);
1302 */
1303         if (!item)
1304                 return;
1305         
1306         path = folder_item_get_path(item);
1307
1308         mh_sequences_old = g_strconcat(path, G_DIR_SEPARATOR_S,
1309                                             ".mh_sequences", NULL);
1310         mh_sequences_new = g_strconcat(path, G_DIR_SEPARATOR_S,
1311                                             ".mh_sequences.new", NULL);
1312         if ((mh_sequences_new_fp = g_fopen(mh_sequences_new, "w+b")) != NULL) {
1313                 GSList *msglist = folder_item_get_msg_list(item);
1314                 GSList *cur;
1315                 MsgInfo *info = NULL;
1316                 gint start = -1, end = -1;
1317                 gchar *sequence = g_strdup("");
1318                 msglist = g_slist_sort(msglist, sort_cache_list_by_msgnum);
1319                 cur = msglist;
1320                 
1321                 /* write the unseen sequence if we don't have to scrap it */
1322                 if (!remove_unseen) do {
1323                         info = (MsgInfo *)(cur ? cur->data:NULL);
1324                         if (info && (MSG_IS_UNREAD(info->flags) || MSG_IS_NEW(info->flags))) {
1325                                 if (start < 0)
1326                                         start = end = info->msgnum;
1327                                 else
1328                                         end = info->msgnum;
1329                         } else {
1330                                 if (start > 0 && end > 0) {
1331                                         gchar *tmp = sequence;
1332                                         if (start != end)
1333                                                 sequence = g_strdup_printf("%s %d-%d ", tmp, start, end);
1334                                         else
1335                                                 sequence = g_strdup_printf("%s %d ", tmp, start);
1336                                         g_free(tmp);
1337                                         start = end = -1;
1338                                 }
1339                         }
1340                         cur = cur ? cur->next:NULL;
1341                 } while (cur || (start > 0 && end > 0));
1342                 if (sequence && strlen(sequence)) {
1343                         fprintf(mh_sequences_new_fp, "%s%s\n", 
1344                                         get_unseen_seq_name(), sequence);
1345                         debug_print("wrote unseen sequence: '%s%s'\n", 
1346                                         get_unseen_seq_name(), sequence);
1347                 }
1348                 /* rewrite the rest of the file */
1349                 if ((mh_sequences_old_fp = g_fopen(mh_sequences_old, "r+b")) != NULL) {
1350                         while (fgets(buf, sizeof(buf), mh_sequences_old_fp) != NULL) {
1351                                 if (strncmp(buf, get_unseen_seq_name(), strlen(get_unseen_seq_name())))
1352                                         fprintf(mh_sequences_new_fp, "%s", buf);
1353                         }
1354                         fclose(mh_sequences_old_fp);
1355                 }
1356                 
1357                 fclose(mh_sequences_new_fp);
1358                 g_rename(mh_sequences_new, mh_sequences_old);
1359                 g_free(sequence);
1360                 procmsg_msg_list_free(msglist);
1361         }
1362         g_free(mh_sequences_old);
1363         g_free(mh_sequences_new);
1364         g_free(path);
1365 /*
1366         g_timer_stop(timer);
1367         printf("mh_get_flags: %f secs\n", g_timer_elapsed(timer, NULL));
1368         g_timer_destroy(timer);
1369 */
1370 }
1371
1372 static int mh_item_close(Folder *folder, FolderItem *item)
1373 {
1374         mh_write_sequences(item, FALSE);
1375         return 0;
1376 }