06cb2805d8acbf4159eefdbb536010cd826ecdf3
[claws.git] / src / imap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include "imap.h"
31 #include "imap_gtk.h"
32 #include "inc.h"
33 #include "xml.h"
34 #include "alertpanel.h"
35
36 #ifdef HAVE_LIBETPAN
37
38 #include <stdlib.h>
39 #include <dirent.h>
40 #include <unistd.h>
41 #include <ctype.h>
42 #include <time.h>
43 #include <errno.h>
44 #if HAVE_ICONV
45 #  include <iconv.h>
46 #endif
47
48 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
49 #  include "ssl.h"
50 #endif
51
52 #include "folder.h"
53 #include "session.h"
54 #include "procmsg.h"
55 #include "socket.h"
56 #include "recv.h"
57 #include "procheader.h"
58 #include "prefs_account.h"
59 #include "codeconv.h"
60 #include "md5.h"
61 #include "base64.h"
62 #include "utils.h"
63 #include "prefs_common.h"
64 #include "inputdialog.h"
65 #include "log.h"
66 #include "remotefolder.h"
67 #include "claws.h"
68 #include "statusbar.h"
69 #include "msgcache.h"
70 #include "imap-thread.h"
71 #include "account.h"
72
73 typedef struct _IMAPFolder      IMAPFolder;
74 typedef struct _IMAPSession     IMAPSession;
75 typedef struct _IMAPNameSpace   IMAPNameSpace;
76 typedef struct _IMAPFolderItem  IMAPFolderItem;
77
78 #include "prefs_account.h"
79
80 #define IMAP_FOLDER(obj)        ((IMAPFolder *)obj)
81 #define IMAP_FOLDER_ITEM(obj)   ((IMAPFolderItem *)obj)
82 #define IMAP_SESSION(obj)       ((IMAPSession *)obj)
83
84 struct _IMAPFolder
85 {
86         RemoteFolder rfolder;
87
88         /* list of IMAPNameSpace */
89         GList *ns_personal;
90         GList *ns_others;
91         GList *ns_shared;
92         gchar last_seen_separator;
93         guint refcnt;
94         guint max_set_size;
95 };
96
97 struct _IMAPSession
98 {
99         Session session;
100
101         gboolean authenticated;
102
103         GSList *capability;
104         gboolean uidplus;
105
106         gchar *mbox;
107         guint cmd_count;
108
109         /* CLAWS */
110         gboolean folder_content_changed;
111         guint exists;
112         guint recent;
113         guint expunge;
114         guint unseen;
115         guint uid_validity;
116         guint uid_next;
117
118         Folder * folder;
119         gboolean busy;
120         gboolean cancelled;
121         gboolean sens_update_block;
122 };
123
124 struct _IMAPNameSpace
125 {
126         gchar *name;
127         gchar separator;
128 };
129
130 #define IMAPBUFSIZE     8192
131
132 typedef enum
133 {
134         IMAP_FLAG_SEEN          = 1 << 0,
135         IMAP_FLAG_ANSWERED      = 1 << 1,
136         IMAP_FLAG_FLAGGED       = 1 << 2,
137         IMAP_FLAG_DELETED       = 1 << 3,
138         IMAP_FLAG_DRAFT         = 1 << 4
139 } IMAPFlags;
140
141 #define IMAP_IS_SEEN(flags)     ((flags & IMAP_FLAG_SEEN) != 0)
142 #define IMAP_IS_ANSWERED(flags) ((flags & IMAP_FLAG_ANSWERED) != 0)
143 #define IMAP_IS_FLAGGED(flags)  ((flags & IMAP_FLAG_FLAGGED) != 0)
144 #define IMAP_IS_DELETED(flags)  ((flags & IMAP_FLAG_DELETED) != 0)
145 #define IMAP_IS_DRAFT(flags)    ((flags & IMAP_FLAG_DRAFT) != 0)
146
147
148 #define IMAP4_PORT      143
149 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
150 #define IMAPS_PORT      993
151 #endif
152
153 #define IMAP_CMD_LIMIT  1000
154
155 struct _IMAPFolderItem
156 {
157         FolderItem item;
158
159         guint lastuid;
160         guint uid_next;
161         GSList *uid_list;
162         gboolean batching;
163
164         GHashTable *flags_set_table;
165         GHashTable *flags_unset_table;
166         guint32 last_change;
167         guint32 last_sync;
168         gboolean should_update;
169         gboolean should_trash_cache;
170 };
171
172 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
173 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
174
175 static void imap_folder_init            (Folder         *folder,
176                                          const gchar    *name,
177                                          const gchar    *path);
178
179 static Folder   *imap_folder_new        (const gchar    *name,
180                                          const gchar    *path);
181 static void      imap_folder_destroy    (Folder         *folder);
182
183 static IMAPSession *imap_session_new    (Folder         *folder,
184                                          const PrefsAccount     *account);
185 static void     imap_session_authenticate(IMAPSession           *session,
186                                           const PrefsAccount    *account);
187 static void     imap_session_destroy    (Session        *session);
188
189 static gchar   *imap_fetch_msg          (Folder         *folder, 
190                                          FolderItem     *item, 
191                                          gint            uid);
192 static gchar   *imap_fetch_msg_full     (Folder         *folder, 
193                                          FolderItem     *item, 
194                                          gint            uid,
195                                          gboolean        headers,
196                                          gboolean        body);
197 static void     imap_remove_cached_msg  (Folder         *folder, 
198                                          FolderItem     *item, 
199                                          MsgInfo        *msginfo);
200 static gint     imap_add_msg            (Folder         *folder,
201                                          FolderItem     *dest,
202                                          const gchar    *file, 
203                                          MsgFlags       *flags);
204 static gint     imap_add_msgs           (Folder         *folder, 
205                                          FolderItem     *dest,
206                                          GSList         *file_list,
207                                          GRelation      *relation);
208
209 static gint     imap_copy_msg           (Folder         *folder,
210                                          FolderItem     *dest, 
211                                          MsgInfo        *msginfo);
212 static gint     imap_copy_msgs          (Folder         *folder, 
213                                          FolderItem     *dest, 
214                                          MsgInfoList    *msglist, 
215                                          GRelation      *relation);
216
217 static gint     imap_remove_msg         (Folder         *folder, 
218                                          FolderItem     *item, 
219                                          gint            uid);
220 static gint     imap_remove_msgs        (Folder         *folder, 
221                                          FolderItem     *dest, 
222                                          MsgInfoList    *msglist, 
223                                          GRelation      *relation);
224 static gint     imap_remove_all_msg     (Folder         *folder, 
225                                          FolderItem     *item);
226
227 static gboolean imap_is_msg_changed     (Folder         *folder,
228                                          FolderItem     *item, 
229                                          MsgInfo        *msginfo);
230
231 static gint     imap_close              (Folder         *folder, 
232                                          FolderItem     *item);
233
234 static gint     imap_scan_tree          (Folder         *folder);
235
236 static gint     imap_create_tree        (Folder         *folder);
237
238 static FolderItem *imap_create_folder   (Folder         *folder,
239                                          FolderItem     *parent,
240                                          const gchar    *name);
241 static gint     imap_rename_folder      (Folder         *folder,
242                                          FolderItem     *item, 
243                                          const gchar    *name);
244 static gint     imap_remove_folder      (Folder         *folder, 
245                                          FolderItem     *item);
246
247 static FolderItem *imap_folder_item_new (Folder         *folder);
248 static void imap_folder_item_destroy    (Folder         *folder,
249                                          FolderItem     *item);
250
251 static IMAPSession *imap_session_get    (Folder         *folder);
252
253 static gint imap_auth                   (IMAPSession    *session,
254                                          const gchar    *user,
255                                          const gchar    *pass,
256                                          IMAPAuthType    type);
257
258 static gint imap_scan_tree_recursive    (IMAPSession    *session,
259                                          FolderItem     *item,
260                                          gboolean        subs_only);
261
262 static void imap_create_missing_folders (Folder         *folder);
263 static FolderItem *imap_create_special_folder
264                                         (Folder                 *folder,
265                                          SpecialFolderItemType   stype,
266                                          const gchar            *name);
267
268 static gint imap_do_copy_msgs           (Folder         *folder,
269                                          FolderItem     *dest,
270                                          MsgInfoList    *msglist,
271                                          GRelation      *relation);
272
273 static void imap_delete_all_cached_messages     (FolderItem     *item);
274 static void imap_set_batch              (Folder         *folder,
275                                          FolderItem     *item,
276                                          gboolean        batch);
277 static gint imap_set_message_flags      (IMAPSession    *session,
278                                          MsgNumberList  *numlist,
279                                          IMAPFlags       flags,
280                                          gboolean        is_set);
281 static gint imap_select                 (IMAPSession    *session,
282                                          IMAPFolder     *folder,
283                                          const gchar    *path,
284                                          gint           *exists,
285                                          gint           *recent,
286                                          gint           *unseen,
287                                          guint32        *uid_validity,
288                                          gboolean        block);
289 static gint imap_status                 (IMAPSession    *session,
290                                          IMAPFolder     *folder,
291                                          const gchar    *path,
292                                          IMAPFolderItem *item,
293                                          gint           *messages,
294                                          guint32        *uid_next,
295                                          guint32        *uid_validity,
296                                          gint           *unseen,
297                                          gboolean        block);
298
299 static gchar imap_get_path_separator            (IMAPSession    *session,
300                                                  IMAPFolder     *folder,
301                                                  const gchar    *path);
302 static gchar *imap_get_real_path                (IMAPSession    *session,
303                                                  IMAPFolder     *folder,
304                                                  const gchar    *path);
305 #ifdef HAVE_LIBETPAN
306 static void imap_synchronise            (FolderItem     *item, gint days);
307 #endif
308 static gboolean imap_is_busy            (Folder *folder);
309
310 static void imap_free_capabilities      (IMAPSession    *session);
311
312 /* low-level IMAP4rev1 commands */
313 static gint imap_cmd_login      (IMAPSession    *session,
314                                  const gchar    *user,
315                                  const gchar    *pass,
316                                  const gchar    *type);
317 static gint imap_cmd_noop       (IMAPSession    *session);
318 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
319 static gint imap_cmd_starttls   (IMAPSession    *session);
320 #endif
321 static gint imap_cmd_select     (IMAPSession    *session,
322                                  const gchar    *folder,
323                                  gint           *exists,
324                                  gint           *recent,
325                                  gint           *unseen,
326                                  guint32        *uid_validity,
327                                  gboolean        block);
328 static gint imap_cmd_close      (IMAPSession    *session);
329 static gint imap_cmd_examine    (IMAPSession    *session,
330                                  const gchar    *folder,
331                                  gint           *exists,
332                                  gint           *recent,
333                                  gint           *unseen,
334                                  guint32        *uid_validity,
335                                  gboolean        block);
336 static gint imap_cmd_create     (IMAPSession    *sock,
337                                  const gchar    *folder);
338 static gint imap_cmd_rename     (IMAPSession    *sock,
339                                  const gchar    *oldfolder,
340                                  const gchar    *newfolder);
341 static gint imap_cmd_delete     (IMAPSession    *session,
342                                  const gchar    *folder);
343 static gint imap_cmd_fetch      (IMAPSession    *sock,
344                                  guint32         uid,
345                                  const gchar    *filename,
346                                  gboolean        headers,
347                                  gboolean        body);
348 static gint imap_cmd_append     (IMAPSession    *session,
349                                  const gchar    *destfolder,
350                                  const gchar    *file,
351                                  IMAPFlags       flags,
352                                  guint32        *new_uid);
353 static gint imap_cmd_copy       (IMAPSession *session,
354                                  struct mailimap_set * set,
355                                  const gchar *destfolder,
356                                  GRelation *uid_mapping,
357                                  struct mailimap_set ** source,
358                                  struct mailimap_set ** dest);
359 static gint imap_cmd_store      (IMAPSession    *session,
360                                  struct mailimap_set * set,
361                                  IMAPFlags flags,
362                                  int do_add);
363 static gint imap_cmd_expunge    (IMAPSession    *session);
364
365 static void imap_path_separator_subst           (gchar          *str,
366                                                  gchar           separator);
367
368 static gchar *imap_utf8_to_modified_utf7        (const gchar    *from);
369 static gchar *imap_modified_utf7_to_utf8        (const gchar    *mutf7_str);
370
371 static gboolean imap_rename_folder_func         (GNode          *node,
372                                                  gpointer        data);
373 static gint imap_get_num_list                   (Folder         *folder,
374                                                  FolderItem     *item,
375                                                  GSList        **list,
376                                                  gboolean       *old_uids_valid);
377 static GSList *imap_get_msginfos                (Folder         *folder,
378                                                  FolderItem     *item,
379                                                  GSList         *msgnum_list);
380 static MsgInfo *imap_get_msginfo                (Folder         *folder,
381                                                  FolderItem     *item,
382                                                  gint            num);
383 static gboolean imap_scan_required              (Folder         *folder,
384                                                  FolderItem     *item);
385 static void imap_change_flags                   (Folder         *folder,
386                                                  FolderItem     *item,
387                                                  MsgInfo        *msginfo,
388                                                  MsgPermFlags    newflags);
389 static gint imap_get_flags                      (Folder         *folder,
390                                                  FolderItem     *item,
391                                                  MsgInfoList    *msglist,
392                                                  GRelation      *msgflags);
393 static gchar *imap_folder_get_path              (Folder         *folder);
394 static gchar *imap_item_get_path                (Folder         *folder,
395                                                  FolderItem     *item);
396 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
397
398
399 /* data types conversion libetpan <-> claws */
400 static GSList * imap_list_from_lep(IMAPFolder * folder,
401                                    clist * list, const gchar * real_path, gboolean all);
402 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
403 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
404 static GSList * imap_uid_list_from_lep(clist * list);
405 static GSList * imap_uid_list_from_lep_tab(carray * list);
406 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
407                                                    GHashTable * hash);
408 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
409                                        FolderItem *item);
410 static void imap_lep_set_free(GSList *seq_list);
411 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags);
412
413 typedef struct _hashtable_data {
414         GSList *msglist;
415         IMAPFolderItem *item;
416 } hashtable_data;
417
418 static FolderClass imap_class;
419
420 typedef struct _thread_data {
421         gchar *server;
422         gushort port;
423         gboolean done;
424         SockInfo *sock;
425 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
426         SSLType ssl_type;
427 #endif
428 } thread_data;
429
430 FolderClass *imap_get_class(void)
431 {
432         if (imap_class.idstr == NULL) {
433                 imap_class.type = F_IMAP;
434                 imap_class.idstr = "imap";
435                 imap_class.uistr = "IMAP4";
436
437                 /* Folder functions */
438                 imap_class.new_folder = imap_folder_new;
439                 imap_class.destroy_folder = imap_folder_destroy;
440                 imap_class.scan_tree = imap_scan_tree;
441                 imap_class.create_tree = imap_create_tree;
442
443                 /* FolderItem functions */
444                 imap_class.item_new = imap_folder_item_new;
445                 imap_class.item_destroy = imap_folder_item_destroy;
446                 imap_class.item_get_path = imap_item_get_path;
447                 imap_class.create_folder = imap_create_folder;
448                 imap_class.rename_folder = imap_rename_folder;
449                 imap_class.remove_folder = imap_remove_folder;
450                 imap_class.close = imap_close;
451                 imap_class.get_num_list = imap_get_num_list;
452                 imap_class.scan_required = imap_scan_required;
453                 imap_class.set_xml = folder_set_xml;
454                 imap_class.get_xml = folder_get_xml;
455                 imap_class.item_set_xml = imap_item_set_xml;
456                 imap_class.item_get_xml = imap_item_get_xml;
457
458                 /* Message functions */
459                 imap_class.get_msginfo = imap_get_msginfo;
460                 imap_class.get_msginfos = imap_get_msginfos;
461                 imap_class.fetch_msg = imap_fetch_msg;
462                 imap_class.fetch_msg_full = imap_fetch_msg_full;
463                 imap_class.add_msg = imap_add_msg;
464                 imap_class.add_msgs = imap_add_msgs;
465                 imap_class.copy_msg = imap_copy_msg;
466                 imap_class.copy_msgs = imap_copy_msgs;
467                 imap_class.remove_msg = imap_remove_msg;
468                 imap_class.remove_msgs = imap_remove_msgs;
469                 imap_class.remove_all_msg = imap_remove_all_msg;
470                 imap_class.is_msg_changed = imap_is_msg_changed;
471                 imap_class.change_flags = imap_change_flags;
472                 imap_class.get_flags = imap_get_flags;
473                 imap_class.set_batch = imap_set_batch;
474                 imap_class.synchronise = imap_synchronise;
475                 imap_class.remove_cached_msg = imap_remove_cached_msg;
476 #ifdef USE_PTREAD
477                 pthread_mutex_init(&imap_mutex, NULL);
478 #endif
479         }
480         
481         return &imap_class;
482 }
483
484 static void imap_refresh_sensitivity (IMAPSession *session)
485 {
486         MainWindow *mainwin;
487
488         if (session->sens_update_block)
489                 return;
490         mainwin = mainwindow_get_mainwindow();
491         if (mainwin) {
492                 toolbar_main_set_sensitive(mainwin);
493                 main_window_set_menu_sensitive(mainwin);
494         }
495 }
496
497 static void lock_session(IMAPSession *session)
498 {
499         if (session) {
500                 debug_print("locking session %p (%d)\n", session, session->busy);
501                 if (session->busy)
502                         debug_print("         SESSION WAS LOCKED !!      \n");
503                 session->busy = TRUE;
504                 imap_refresh_sensitivity(session);
505         } else {
506                 debug_print("can't lock null session\n");
507         }
508 }
509
510 static void unlock_session(IMAPSession *session)
511 {
512         if (session) {
513                 debug_print("unlocking session %p\n", session);
514                 session->busy = FALSE;
515                 imap_refresh_sensitivity(session);
516         } else {
517                 debug_print("can't unlock null session\n");
518         }
519 }
520
521 static void imap_disc_session_destroy(Folder *folder)
522 {
523         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
524         IMAPSession *session = NULL;
525         
526         if (!rfolder)
527                 return;
528         session = IMAP_SESSION(rfolder->session);
529         if (!session)
530                 return;
531         rfolder->session = NULL;
532         log_warning(LOG_PROTOCOL, _("IMAP4 connection broken\n"));
533         SESSION(session)->state = SESSION_DISCONNECTED;
534         session_destroy(SESSION(session));
535 }
536
537 static gboolean is_fatal(int libetpan_errcode)
538 {
539         switch(libetpan_errcode) {
540         case MAILIMAP_ERROR_STREAM:
541         case MAILIMAP_ERROR_PROTOCOL:
542         case MAILIMAP_ERROR_PARSE:
543         case MAILIMAP_ERROR_BAD_STATE:
544                 return TRUE;
545         default:
546                 return FALSE;
547         }
548 }
549
550 static void imap_handle_error(Session *session, int libetpan_errcode)
551 {
552         switch(libetpan_errcode) {
553         case MAILIMAP_NO_ERROR:
554                 return;
555         case MAILIMAP_NO_ERROR_AUTHENTICATED:
556                 log_warning(LOG_PROTOCOL, _("IMAP error: authenticated\n"));
557                 break;
558         case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
559                 log_warning(LOG_PROTOCOL, _("IMAP error: not authenticated\n"));
560                 break;
561         case MAILIMAP_ERROR_BAD_STATE:
562                 log_warning(LOG_PROTOCOL, _("IMAP error: bad state\n"));
563                 break;
564         case MAILIMAP_ERROR_STREAM:
565                 log_warning(LOG_PROTOCOL, _("IMAP error: stream error\n"));
566                 break;
567         case MAILIMAP_ERROR_PARSE:
568                 log_warning(LOG_PROTOCOL, _("IMAP error: parse error "
569                                             "(very probably non-RFC compliance from the server)\n"));
570                 break;
571         case MAILIMAP_ERROR_CONNECTION_REFUSED:
572                 log_warning(LOG_PROTOCOL, _("IMAP error: connection refused\n"));
573                 break;
574         case MAILIMAP_ERROR_MEMORY:
575                 log_warning(LOG_PROTOCOL, _("IMAP error: memory error\n"));
576                 break;
577         case MAILIMAP_ERROR_FATAL:
578                 log_warning(LOG_PROTOCOL, _("IMAP error: fatal error\n"));
579                 break;
580         case MAILIMAP_ERROR_PROTOCOL:
581                 log_warning(LOG_PROTOCOL, _("IMAP error: protocol error"
582                                             "(very probably non-RFC compliance from the server)\n"));
583                 break;
584         case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
585                 log_warning(LOG_PROTOCOL, _("IMAP error: connection not accepted\n"));
586                 break;
587         case MAILIMAP_ERROR_APPEND:
588                 log_warning(LOG_PROTOCOL, _("IMAP error: APPEND error\n"));
589                 break;
590         case MAILIMAP_ERROR_NOOP:
591                 log_warning(LOG_PROTOCOL, _("IMAP error: NOOP error\n"));
592                 break;
593         case MAILIMAP_ERROR_LOGOUT:
594                 log_warning(LOG_PROTOCOL, _("IMAP error: LOGOUT error\n"));
595                 break;
596         case MAILIMAP_ERROR_CAPABILITY:
597                 log_warning(LOG_PROTOCOL, _("IMAP error: CAPABILITY error\n"));
598                 break;
599         case MAILIMAP_ERROR_CHECK:
600                 log_warning(LOG_PROTOCOL, _("IMAP error: CHECK error\n"));
601                 break;
602         case MAILIMAP_ERROR_CLOSE:
603                 log_warning(LOG_PROTOCOL, _("IMAP error: CLOSE error\n"));
604                 break;
605         case MAILIMAP_ERROR_EXPUNGE:
606                 log_warning(LOG_PROTOCOL, _("IMAP error: EXPUNGE error\n"));
607                 break;
608         case MAILIMAP_ERROR_COPY:
609                 log_warning(LOG_PROTOCOL, _("IMAP error: COPY error\n"));
610                 break;
611         case MAILIMAP_ERROR_UID_COPY:
612                 log_warning(LOG_PROTOCOL, _("IMAP error: UID COPY error\n"));
613                 break;
614         case MAILIMAP_ERROR_CREATE:
615                 log_warning(LOG_PROTOCOL, _("IMAP error: CREATE error\n"));
616                 break;
617         case MAILIMAP_ERROR_DELETE:
618                 log_warning(LOG_PROTOCOL, _("IMAP error: DELETE error\n"));
619                 break;
620         case MAILIMAP_ERROR_EXAMINE:
621                 log_warning(LOG_PROTOCOL, _("IMAP error: EXAMINE error\n"));
622                 break;
623         case MAILIMAP_ERROR_FETCH:
624                 log_warning(LOG_PROTOCOL, _("IMAP error: FETCH error\n"));
625                 break;
626         case MAILIMAP_ERROR_UID_FETCH:
627                 log_warning(LOG_PROTOCOL, _("IMAP error: UID FETCH error\n"));
628                 break;
629         case MAILIMAP_ERROR_LIST:
630                 log_warning(LOG_PROTOCOL, _("IMAP error: LIST error\n"));
631                 break;
632         case MAILIMAP_ERROR_LOGIN:
633                 log_warning(LOG_PROTOCOL, _("IMAP error: LOGIN error\n"));
634                 break;
635         case MAILIMAP_ERROR_LSUB:
636                 log_warning(LOG_PROTOCOL, _("IMAP error: LSUB error\n"));
637                 break;
638         case MAILIMAP_ERROR_RENAME:
639                 log_warning(LOG_PROTOCOL, _("IMAP error: RENAME error\n"));
640                 break;
641         case MAILIMAP_ERROR_SEARCH:
642                 log_warning(LOG_PROTOCOL, _("IMAP error: SEARCH error\n"));
643                 break;
644         case MAILIMAP_ERROR_UID_SEARCH:
645                 log_warning(LOG_PROTOCOL, _("IMAP error: UID SEARCH error\n"));
646                 break;
647         case MAILIMAP_ERROR_SELECT:
648                 log_warning(LOG_PROTOCOL, _("IMAP error: SELECT error\n"));
649                 break;
650         case MAILIMAP_ERROR_STATUS:
651                 log_warning(LOG_PROTOCOL, _("IMAP error: STATUS error\n"));
652                 break;
653         case MAILIMAP_ERROR_STORE:
654                 log_warning(LOG_PROTOCOL, _("IMAP error: STORE error\n"));
655                 break;
656         case MAILIMAP_ERROR_UID_STORE:
657                 log_warning(LOG_PROTOCOL, _("IMAP error: UID STORE error\n"));
658                 break;
659         case MAILIMAP_ERROR_SUBSCRIBE:
660                 log_warning(LOG_PROTOCOL, _("IMAP error: SUBSCRIBE error\n"));
661                 break;
662         case MAILIMAP_ERROR_UNSUBSCRIBE:
663                 log_warning(LOG_PROTOCOL, _("IMAP error: UNSUBSCRIBE error\n"));
664                 break;
665         case MAILIMAP_ERROR_STARTTLS:
666                 log_warning(LOG_PROTOCOL, _("IMAP error: STARTTLS error\n"));
667                 break;
668         case MAILIMAP_ERROR_INVAL:
669                 log_warning(LOG_PROTOCOL, _("IMAP error: INVAL error\n"));
670                 break;
671         case MAILIMAP_ERROR_EXTENSION:
672                 log_warning(LOG_PROTOCOL, _("IMAP error: EXTENSION error\n"));
673                 break;
674         case MAILIMAP_ERROR_SASL:
675                 log_warning(LOG_PROTOCOL, _("IMAP error: SASL error\n"));
676                 break;
677 #if (LIBETPAN_VERSION_MAJOR > 0 || LIBETPAN_VERSION_MINOR > 48)
678 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
679         case MAILIMAP_ERROR_SSL:
680                 log_warning(LOG_PROTOCOL, _("IMAP error: SSL error\n"));
681                 break;
682 #endif
683 #endif
684         default:
685                 log_warning(LOG_PROTOCOL, _("IMAP error: Unknown error [%d]\n"),
686                         libetpan_errcode);
687                 break;
688         }
689
690         if (session && is_fatal(libetpan_errcode)) {
691                 imap_disc_session_destroy(IMAP_SESSION(session)->folder);
692         } else if (session && !is_fatal(libetpan_errcode)) {
693                 if (IMAP_SESSION(session)->busy)
694                         unlock_session(IMAP_SESSION(session));
695         }
696 }
697
698 static Folder *imap_folder_new(const gchar *name, const gchar *path)
699 {
700         Folder *folder;
701
702         folder = (Folder *)g_new0(IMAPFolder, 1);
703         folder->klass = &imap_class;
704         imap_folder_init(folder, name, path);
705
706         return folder;
707 }
708
709 static void imap_folder_destroy(Folder *folder)
710 {
711         while (imap_folder_get_refcnt(folder) > 0)
712                 gtk_main_iteration();
713         
714         folder_remote_folder_destroy(REMOTE_FOLDER(folder));
715         imap_done(folder);
716 }
717
718 static void imap_folder_init(Folder *folder, const gchar *name,
719                              const gchar *path)
720 {
721         folder_remote_folder_init((Folder *)folder, name, path);
722         IMAP_FOLDER(folder)->max_set_size = IMAP_SET_MAX_COUNT;
723 }
724
725 static FolderItem *imap_folder_item_new(Folder *folder)
726 {
727         IMAPFolderItem *item;
728         
729         item = g_new0(IMAPFolderItem, 1);
730         item->lastuid = 0;
731         item->uid_next = 0;
732         item->uid_list = NULL;
733
734         return (FolderItem *)item;
735 }
736
737 static void imap_folder_item_destroy(Folder *folder, FolderItem *_item)
738 {
739         IMAPFolderItem *item = (IMAPFolderItem *)_item;
740
741         g_return_if_fail(item != NULL);
742         g_slist_free(item->uid_list);
743
744         g_free(_item);
745 }
746
747 static gboolean imap_reset_uid_lists_func(GNode *node, gpointer data)
748 {
749         IMAPFolderItem *item = (IMAPFolderItem *)node->data;
750         
751         item->lastuid = 0;
752         g_slist_free(item->uid_list);
753         item->uid_list = NULL;
754         
755         return FALSE;
756 }
757
758 static void imap_reset_uid_lists(Folder *folder)
759 {
760         if(folder->node == NULL)
761                 return;
762         
763         /* Destroy all uid lists and rest last uid */
764         g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL); 
765 }
766
767 static int imap_get_capabilities(IMAPSession *session)
768 {
769         struct mailimap_capability_data *capabilities = NULL;
770         clistiter *cur;
771         int result = -1;
772
773         if (session->capability != NULL)
774                 return MAILIMAP_NO_ERROR;
775
776         capabilities = imap_threaded_capability(session->folder, &result);
777
778         if (result != MAILIMAP_NO_ERROR) {
779                 imap_handle_error(SESSION(session), result);
780                 return MAILIMAP_ERROR_CAPABILITY;
781         }
782
783         if (capabilities == NULL) {
784                 return MAILIMAP_NO_ERROR;
785         }
786
787         for(cur = clist_begin(capabilities->cap_list) ; cur != NULL ;
788             cur = clist_next(cur)) {
789                 struct mailimap_capability * cap = 
790                         clist_content(cur);
791                 if (!cap || cap->cap_data.cap_name == NULL)
792                         continue;
793                 session->capability = g_slist_append
794                                 (session->capability,
795                                  g_strdup(cap->cap_data.cap_name));
796                 debug_print("got capa %s\n", cap->cap_data.cap_name);
797         }
798         mailimap_capability_data_free(capabilities);
799         return MAILIMAP_NO_ERROR;
800 }
801
802 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap) 
803 {
804         GSList *cur;
805         for (cur = session->capability; cur; cur = cur->next) {
806                 if (!g_ascii_strcasecmp(cur->data, cap))
807                         return TRUE;
808         }
809         return FALSE;
810 }
811
812 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
813                       IMAPAuthType type)
814 {
815         gint ok = MAILIMAP_ERROR_BAD_STATE;
816         static time_t last_login_err = 0;
817         gchar *ext_info = "";
818         int r;
819         if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
820                 imap_handle_error(SESSION(session), r);
821                 return r;
822         }
823         switch(type) {
824         case IMAP_AUTH_ANON:
825                 ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
826                 break;
827         case IMAP_AUTH_CRAM_MD5:
828                 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
829                 break;
830         case IMAP_AUTH_LOGIN:
831                 ok = imap_cmd_login(session, user, pass, "LOGIN");
832                 break;
833         case IMAP_AUTH_GSSAPI:
834                 ok = imap_cmd_login(session, user, pass, "GSSAPI");
835                 break;
836         default:
837                 debug_print("capabilities:\n"
838                                 "\t ANONYMOUS %d\n"
839                                 "\t CRAM-MD5 %d\n"
840                                 "\t LOGIN %d\n"
841                                 "\t GSSAPI %d\n", 
842                         imap_has_capability(session, "ANONYMOUS"),
843                         imap_has_capability(session, "CRAM-MD5"),
844                         imap_has_capability(session, "LOGIN"),
845                         imap_has_capability(session, "GSSAPI"));
846                 if (imap_has_capability(session, "CRAM-MD5"))
847                         ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
848                 if (ok == MAILIMAP_ERROR_BAD_STATE && imap_has_capability(session, "GSSAPI"))
849                         ok = imap_cmd_login(session, user, pass, "GSSAPI");
850                 if (ok == MAILIMAP_ERROR_BAD_STATE) /* we always try LOGIN before giving up */
851                         ok = imap_cmd_login(session, user, pass, "LOGIN");
852         }
853
854         if (ok == MAILIMAP_NO_ERROR)
855                 session->authenticated = TRUE;
856         else {
857                 if (type == IMAP_AUTH_CRAM_MD5) {
858                         ext_info = _("\n\nCRAM-MD5 logins only work if libetpan has been "
859                                      "compiled with SASL support and the "
860                                      "CRAM-MD5 SASL plugin is installed.");
861                 } 
862
863                 if (time(NULL) - last_login_err > 10) {
864                         if (!prefs_common.no_recv_err_panel) {
865                                 alertpanel_error(_("Connection to %s failed: "
866                                         "login refused.%s"),
867                                         SESSION(session)->server, ext_info);
868                         } else {
869                                 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
870                                         "login refused.%s\n"),
871                                         SESSION(session)->server, ext_info);
872                         }
873                 }
874                 last_login_err = time(NULL);
875         }
876         return ok;
877 }
878
879 static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *session)
880 {
881         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
882         /* Check if this is the first try to establish a
883            connection, if yes we don't try to reconnect */
884         debug_print("reconnecting\n");
885         if (rfolder->session == NULL) {
886                 log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
887                             folder->account->recv_server);
888                 session_destroy(SESSION(session));
889                 session = NULL;
890         } else {
891                 rfolder->session = NULL;
892                 log_warning(LOG_PROTOCOL, _("IMAP4 connection to %s has been"
893                             " disconnected. Reconnecting...\n"),
894                             folder->account->recv_server);
895                 statusbar_print_all(_("IMAP4 connection to %s has been"
896                             " disconnected. Reconnecting...\n"),
897                             folder->account->recv_server);
898                 SESSION(session)->state = SESSION_DISCONNECTED;
899                 session_destroy(SESSION(session));
900                 /* Clear folders session to make imap_session_get create
901                    a new session, because of rfolder->session == NULL
902                    it will not try to reconnect again and so avoid an
903                    endless loop */
904                 debug_print("getting session...\n");
905                 session = imap_session_get(folder);
906                 rfolder->session = SESSION(session);
907                 statusbar_pop_all();
908         }
909         return session;
910 }
911
912 static IMAPSession *imap_session_get(Folder *folder)
913 {
914         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
915         IMAPSession *session = NULL;
916         gint r = MAILIMAP_NO_ERROR;
917
918         g_return_val_if_fail(folder != NULL, NULL);
919         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
920         g_return_val_if_fail(folder->account != NULL, NULL);
921         
922         if (prefs_common.work_offline && 
923             !inc_offline_should_override(FALSE,
924                 _("Claws Mail needs network access in order "
925                   "to access the IMAP server."))) {
926                 return NULL;
927         }
928
929         /* Make sure we have a session */
930         if (rfolder->session != NULL) {
931                 session = IMAP_SESSION(rfolder->session);
932         } else if (rfolder->connecting) {
933                 debug_print("already connecting\n");
934                 return NULL;
935         } else {
936                 imap_reset_uid_lists(folder);
937                 if (time(NULL) - rfolder->last_failure <= 2)
938                         return NULL;
939                 rfolder->connecting = TRUE;
940                 session = imap_session_new(folder, folder->account);
941         }
942         if(session == NULL) {
943                 rfolder->last_failure = time(NULL);
944                 rfolder->connecting = FALSE;
945                 return NULL;
946         }
947
948         /* Make sure session is authenticated */
949         if (!IMAP_SESSION(session)->authenticated)
950                 imap_session_authenticate(IMAP_SESSION(session), folder->account);
951         
952         if (!IMAP_SESSION(session)->authenticated) {
953                 imap_threaded_disconnect(session->folder);
954                 rfolder->session = NULL;
955                 SESSION(session)->state = SESSION_DISCONNECTED;
956                 session_destroy(SESSION(session));
957                 rfolder->last_failure = time(NULL);
958                 rfolder->connecting = FALSE;
959                 return NULL;
960         }
961
962         /* I think the point of this code is to avoid sending a
963          * keepalive if we've used the session recently and therefore
964          * think it's still alive.  Unfortunately, most of the code
965          * does not yet check for errors on the socket, and so if the
966          * connection drops we don't notice until the timeout expires.
967          * A better solution than sending a NOOP every time would be
968          * for every command to be prepared to retry until it is
969          * successfully sent. -- mbp */
970         if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
971                 /* verify that the session is still alive */
972                 if ((r = imap_cmd_noop(session)) != MAILIMAP_NO_ERROR) {
973                         debug_print("disconnected!\n");
974                         if (!is_fatal(r))
975                                 session = imap_reconnect_if_possible(folder, session);
976                         else
977                                 session = imap_session_get(folder);
978                 }
979                 if (session)
980                         session->cancelled = FALSE;
981         }
982
983         rfolder->session = SESSION(session);
984         rfolder->connecting = FALSE;
985
986         return IMAP_SESSION(session);
987 }
988
989 static IMAPSession *imap_session_new(Folder * folder,
990                                      const PrefsAccount *account)
991 {
992         IMAPSession *session;
993         gushort port;
994         int r;
995         int authenticated = FALSE;
996         
997 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
998         /* FIXME: IMAP over SSL only... */ 
999         SSLType ssl_type;
1000
1001         port = account->set_imapport ? account->imapport
1002                 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1003         ssl_type = account->ssl_imap;   
1004 #else
1005         if (account->ssl_imap != SSL_NONE) {
1006                 if (alertpanel_full(_("Insecure connection"),
1007                         _("This connection is configured to be secured "
1008                           "using SSL, but SSL is not available in this "
1009                           "build of Claws Mail. \n\n"
1010                           "Do you want to continue connecting to this "
1011                           "server? The communication would not be "
1012                           "secure."),
1013                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), 
1014                           NULL, FALSE, NULL, ALERT_WARNING,
1015                           G_ALERTDEFAULT) != G_ALERTALTERNATE)
1016                         return NULL;
1017         }
1018         port = account->set_imapport ? account->imapport
1019                 : IMAP4_PORT;
1020 #endif
1021
1022         imap_init(folder);
1023         statuswindow_print_all(_("Connecting to IMAP4 server: %s..."), folder->account->recv_server);
1024         if (account->set_tunnelcmd) {
1025                 r = imap_threaded_connect_cmd(folder,
1026                                               account->tunnelcmd,
1027                                               account->recv_server,
1028                                               port);
1029         }
1030         else {
1031 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1032                 if (ssl_type == SSL_TUNNEL) {
1033                         r = imap_threaded_connect_ssl(folder,
1034                                                       account->recv_server,
1035                                                       port);
1036                 }
1037                 else 
1038 #endif
1039                 {
1040                         r = imap_threaded_connect(folder,
1041                                                   account->recv_server,
1042                                                   port);
1043                 }
1044         }
1045         
1046         statuswindow_pop_all();
1047         if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1048                 authenticated = TRUE;
1049         }
1050         else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1051                 authenticated = FALSE;
1052         }
1053         else {
1054 #if (LIBETPAN_VERSION_MAJOR > 0 || LIBETPAN_VERSION_MINOR > 48)
1055 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1056                 if (r == MAILIMAP_ERROR_SSL)
1057                         log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
1058                 else
1059 #endif
1060 #endif
1061                         imap_handle_error(NULL, r);
1062
1063                 if(!prefs_common.no_recv_err_panel) {
1064                         alertpanel_error_log(_("Can't connect to IMAP4 server: %s:%d"),
1065                                          account->recv_server, port);
1066                 } else {
1067                         log_error(LOG_PROTOCOL, _("Can't connect to IMAP4 server: %s:%d\n"),
1068                                          account->recv_server, port);
1069                 } 
1070                 
1071                 return NULL;
1072         }
1073         
1074         session = g_new0(IMAPSession, 1);
1075         session_init(SESSION(session));
1076         SESSION(session)->type             = SESSION_IMAP;
1077         SESSION(session)->server           = g_strdup(account->recv_server);
1078         SESSION(session)->sock             = NULL;
1079         
1080         SESSION(session)->destroy          = imap_session_destroy;
1081
1082         session->capability = NULL;
1083         
1084         session->authenticated = authenticated;
1085         session->mbox = NULL;
1086         session->exists = 0;
1087         session->recent = 0;
1088         session->expunge = 0;
1089         session->cmd_count = 0;
1090         session->folder = folder;
1091         IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1092
1093 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1094         if (account->ssl_imap == SSL_STARTTLS) {
1095                 gint ok;
1096
1097                 ok = imap_cmd_starttls(session);
1098                 if (ok != MAILIMAP_NO_ERROR) {
1099                         log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
1100                         session_destroy(SESSION(session));
1101                         return NULL;
1102                 }
1103
1104                 imap_free_capabilities(session);
1105                 session->authenticated = FALSE;
1106                 session->uidplus = FALSE;
1107                 session->cmd_count = 1;
1108         }
1109 #endif
1110         log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1111                     (session->authenticated) ? "pre" : "un");
1112         
1113         return session;
1114 }
1115
1116 static void imap_session_authenticate(IMAPSession *session, 
1117                                       const PrefsAccount *account)
1118 {
1119         gchar *pass, *acc_pass;
1120         gboolean failed = FALSE;
1121
1122         g_return_if_fail(account->userid != NULL);
1123         acc_pass = account->passwd;
1124 try_again:
1125         pass = acc_pass;
1126         if (!pass && account->imap_auth_type != IMAP_AUTH_ANON) {
1127                 gchar *tmp_pass;
1128                 tmp_pass = input_dialog_query_password(account->recv_server, account->userid);
1129                 if (!tmp_pass)
1130                         return;
1131                 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return;});
1132                 g_free(tmp_pass);
1133         } else if (account->imap_auth_type == IMAP_AUTH_ANON) {
1134                 pass = "";
1135         }
1136         statuswindow_print_all(_("Connecting to IMAP4 server %s...\n"),
1137                                 account->recv_server);
1138         if (imap_auth(session, account->userid, pass, account->imap_auth_type) != MAILIMAP_NO_ERROR) {
1139                 statusbar_pop_all();
1140                 
1141                 if (!failed) {
1142                         acc_pass = NULL;
1143                         failed = TRUE;
1144                         goto try_again;
1145                 } else {
1146                         if (prefs_common.no_recv_err_panel) {
1147                                 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s."), account->recv_server);
1148                                 mainwindow_show_error();
1149                         } else
1150                                 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1151                 }               
1152
1153                 return;
1154         } 
1155
1156         statuswindow_pop_all();
1157         session->authenticated = TRUE;
1158         return;
1159 }
1160
1161 static void imap_session_destroy(Session *session)
1162 {
1163         if (session->state != SESSION_DISCONNECTED)
1164                 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1165         
1166         imap_free_capabilities(IMAP_SESSION(session));
1167         g_free(IMAP_SESSION(session)->mbox);
1168         sock_close(session->sock);
1169         session->sock = NULL;
1170 }
1171
1172 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1173 {
1174         return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1175 }
1176
1177 static guint get_file_size_with_crs(const gchar *filename) 
1178 {
1179         FILE *fp = NULL;
1180         guint cnt = 0;
1181         gchar buf[4096];
1182         
1183         if (filename == NULL)
1184                 return -1;
1185         
1186         fp = fopen(filename, "rb");
1187         if (!fp)
1188                 return -1;
1189         
1190         while (fgets(buf, sizeof (buf), fp) != NULL) {
1191                 cnt += strlen(buf);
1192                 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1193                         cnt++;
1194         }
1195         
1196         fclose(fp);
1197         return cnt;
1198 }
1199
1200 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1201 {
1202         gchar *path, *filename;
1203
1204         path = folder_item_get_path(item);
1205
1206         if (!is_dir_exist(path)) {
1207                 g_free(path);
1208                 return;
1209         }
1210
1211         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
1212         g_free(path);
1213
1214         if (is_file_exist(filename)) {
1215                 g_unlink(filename);
1216         }
1217         g_free(filename);
1218 }
1219
1220 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1221                                   gboolean headers, gboolean body)
1222 {
1223         gchar *path, *filename;
1224         IMAPSession *session;
1225         gint ok;
1226
1227         g_return_val_if_fail(folder != NULL, NULL);
1228         g_return_val_if_fail(item != NULL, NULL);
1229
1230         if (uid == 0)
1231                 return NULL;
1232
1233         path = folder_item_get_path(item);
1234         if (!is_dir_exist(path))
1235                 make_dir_hier(path);
1236         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1237         g_free(path);
1238         debug_print("trying to fetch cached %s\n", filename);
1239         if (is_file_exist(filename)) {
1240                 /* see whether the local file represents the whole message
1241                  * or not. As the IMAP server reports size with \r chars,
1242                  * we have to update the local file (UNIX \n only) size */
1243                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1244                 guint have_size = -1;
1245
1246                 if (cached)
1247                         debug_print("message %d has been already %scached.\n", uid,
1248                                 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1249                 
1250                 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1251                         have_size = get_file_size_with_crs(filename);
1252                         if (cached && (cached->size <= have_size || !body)) {
1253                                 procmsg_msginfo_free(cached);
1254                                 ok = file_strip_crs(filename);
1255                                 if (ok == 0 && cached && cached->size <= have_size) {
1256                                         /* we have it all and stripped */
1257                                         debug_print("...fully cached in fact; setting flag.\n");
1258                                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1259                                 }
1260                                 return filename;
1261                         } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1262                                 debug_print("message not cached and file recent, considering file complete\n");
1263                                 ok = file_strip_crs(filename);
1264                                 if (ok == 0)
1265                                         return filename;
1266                         } else {
1267                                 procmsg_msginfo_free(cached);
1268                         }
1269                 }
1270                 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1271                         procmsg_msginfo_free(cached);
1272                         return filename;
1273                 }
1274         } else {
1275                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1276                 if (cached) {
1277                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1278                         procmsg_msginfo_free(cached);
1279                 }
1280         }
1281
1282         debug_print("getting session...\n");
1283         session = imap_session_get(folder);
1284         
1285         if (!session) {
1286                 g_free(filename);
1287                 return NULL;
1288         }
1289         session_set_access_time(SESSION(session));
1290         lock_session(session); /* unlocked later in the function */
1291
1292         debug_print("IMAP fetching messages\n");
1293         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
1294                          NULL, NULL, NULL, NULL, FALSE);
1295         if (ok != MAILIMAP_NO_ERROR) {
1296                 g_warning("can't select mailbox %s\n", item->path);
1297                 g_free(filename);
1298                 return NULL;
1299         }
1300
1301         session_set_access_time(SESSION(session));
1302
1303         debug_print("getting message %d...\n", uid);
1304         ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1305
1306         if (ok != MAILIMAP_NO_ERROR) {
1307                 g_warning("can't fetch message %d\n", uid);
1308                 g_free(filename);
1309                 return NULL;
1310         }
1311
1312         session_set_access_time(SESSION(session));
1313         unlock_session(session);
1314
1315         ok = file_strip_crs(filename);
1316
1317         if (ok == 0 && headers && body) {
1318                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1319                 if (cached) {
1320                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1321                         procmsg_msginfo_free(cached);
1322                 }
1323         } else if (ok == -1) {
1324                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1325                 if (cached) {
1326                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1327                         procmsg_msginfo_free(cached);
1328                 }
1329         }
1330         return filename;
1331 }
1332
1333 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1334 {
1335         gchar *path, *filename;
1336         guint size = 0;
1337         MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1338         
1339         if (!cached)
1340                 return FALSE;
1341
1342         if (MSG_IS_FULLY_CACHED(cached->flags)) {
1343                 procmsg_msginfo_free(cached);
1344                 return TRUE;
1345         }
1346         path = folder_item_get_path(item);
1347         if (!is_dir_exist(path))
1348                 return FALSE;
1349
1350         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1351         g_free(path);
1352         if (is_file_exist(filename)) {
1353                 if (cached && cached->total_size == cached->size) {
1354                         /* fast path */
1355                         g_free(filename);
1356                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1357                         return TRUE;
1358                 }
1359                 size = get_file_size_with_crs(filename);
1360                 g_free(filename);
1361         }
1362         if (cached && size >= cached->size) {
1363                 cached->total_size = cached->size;
1364                 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1365                 procmsg_msginfo_free(cached);
1366                 return TRUE;
1367         }
1368         if (cached)
1369                 procmsg_msginfo_free(cached);
1370         return FALSE;   
1371 }
1372
1373 void imap_cache_msg(FolderItem *item, gint msgnum)
1374 {
1375         Folder *folder = NULL;
1376         
1377         if (!item)
1378                 return;
1379         folder = item->folder;
1380         
1381         if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1382                 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1383                 debug_print("fetched %s\n", tmp);
1384                 g_free(tmp);
1385         }
1386 }
1387
1388 static gint imap_add_msg(Folder *folder, FolderItem *dest, 
1389                          const gchar *file, MsgFlags *flags)
1390 {
1391         gint ret;
1392         GSList file_list;
1393         MsgFileInfo fileinfo;
1394
1395         g_return_val_if_fail(file != NULL, -1);
1396
1397         fileinfo.msginfo = NULL;
1398         fileinfo.file = (gchar *)file;
1399         fileinfo.flags = flags;
1400         file_list.data = &fileinfo;
1401         file_list.next = NULL;
1402
1403         ret = imap_add_msgs(folder, dest, &file_list, NULL);
1404         return ret;
1405 }
1406
1407 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1408                    GRelation *relation)
1409 {
1410         gchar *destdir;
1411         IMAPSession *session;
1412         guint32 last_uid = 0;
1413         GSList *cur;
1414         MsgFileInfo *fileinfo;
1415         gint ok = MAILIMAP_NO_ERROR;
1416         gint curnum = 0, total = 0;
1417         gboolean missing_uids = FALSE;
1418
1419         g_return_val_if_fail(folder != NULL, -1);
1420         g_return_val_if_fail(dest != NULL, -1);
1421         g_return_val_if_fail(file_list != NULL, -1);
1422         
1423         debug_print("getting session...\n");
1424         session = imap_session_get(folder);
1425         if (!session) {
1426                 return -1;
1427         }
1428         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
1429
1430         statusbar_print_all(_("Adding messages..."));
1431         total = g_slist_length(file_list);
1432         for (cur = file_list; cur != NULL; cur = cur->next) {
1433                 IMAPFlags iflags = 0;
1434                 guint32 new_uid = 0;
1435                 gchar *real_file = NULL;
1436                 fileinfo = (MsgFileInfo *)cur->data;
1437
1438                 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1439                 curnum++;
1440
1441                 if (fileinfo->flags) {
1442                         if (MSG_IS_MARKED(*fileinfo->flags))
1443                                 iflags |= IMAP_FLAG_FLAGGED;
1444                         if (MSG_IS_REPLIED(*fileinfo->flags))
1445                                 iflags |= IMAP_FLAG_ANSWERED;
1446                         if (!MSG_IS_UNREAD(*fileinfo->flags))
1447                                 iflags |= IMAP_FLAG_SEEN;
1448                 }
1449                 
1450                 if (real_file == NULL)
1451                         real_file = g_strdup(fileinfo->file);
1452                 
1453                 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1454                     folder_has_parent_of_type(dest, F_OUTBOX) ||
1455                     folder_has_parent_of_type(dest, F_DRAFT) ||
1456                     folder_has_parent_of_type(dest, F_TRASH))
1457                         iflags |= IMAP_FLAG_SEEN;
1458
1459                 ok = imap_cmd_append(session, destdir, real_file, iflags, 
1460                                      &new_uid);
1461
1462                 if (ok != MAILIMAP_NO_ERROR) {
1463                         g_warning("can't append message %s\n", real_file);
1464                         g_free(real_file);
1465                         g_free(destdir);
1466                         statusbar_progress_all(0,0,0);
1467                         statusbar_pop_all();
1468                         return -1;
1469                 } else {
1470                         debug_print("appended new message as %d\n", new_uid);
1471                         /* put the local file in the imapcache, so that we don't
1472                          * have to fetch it back later. */
1473                         
1474                         if (new_uid == 0) {
1475                                 missing_uids = TRUE;
1476                                 debug_print("Missing UID (0)\n");
1477                         }
1478                         if (new_uid > 0) {
1479                                 gchar *cache_path = folder_item_get_path(dest);
1480                                 if (!is_dir_exist(cache_path))
1481                                         make_dir_hier(cache_path);
1482                                 if (is_dir_exist(cache_path)) {
1483                                         gchar *cache_file = g_strconcat(
1484                                                 cache_path, G_DIR_SEPARATOR_S, 
1485                                                 itos(new_uid), NULL);
1486                                         copy_file(real_file, cache_file, TRUE);
1487                                         debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1488                                         g_free(cache_file);
1489                                 }
1490                                 g_free(cache_path);
1491                         }
1492                 }
1493
1494                 if (relation != NULL)
1495                         g_relation_insert(relation, fileinfo->msginfo != NULL ? 
1496                                           (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1497                                           GINT_TO_POINTER(new_uid));
1498                 if (last_uid < new_uid) {
1499                         last_uid = new_uid;
1500                 }
1501
1502                 g_free(real_file);
1503         }
1504         
1505         statusbar_progress_all(0,0,0);
1506         statusbar_pop_all();
1507         
1508         
1509         g_free(destdir);
1510
1511         imap_scan_required(folder, dest);
1512
1513         session = imap_session_get(folder);
1514         if (!session) {
1515                 return -1;
1516         }
1517         if (missing_uids) {
1518                 gint a;
1519                 ok = imap_select(session, IMAP_FOLDER(folder), dest->path,
1520                          &a, NULL, NULL, NULL, FALSE);
1521         }
1522         return last_uid;
1523 }
1524
1525 static GSList *flatten_mailimap_set(struct mailimap_set * set) 
1526 {
1527         GSList *result = NULL;
1528         clistiter *list;
1529         int start, end, t;
1530         GSList *cur;
1531
1532         for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1533                 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1534                 start = item->set_first;
1535                 end = item->set_last;
1536                 for (t = start; t <= end; t++) {
1537                         result = g_slist_prepend(result, GINT_TO_POINTER(t));
1538                 }
1539         }
1540         result = g_slist_reverse(result);
1541         if (debug_get_mode()) {
1542                 debug_print("flat imap set: ");
1543                 for (cur = result; cur; cur = cur->next) {
1544                         debug_print("%d ", GPOINTER_TO_INT(cur->data));
1545                 }
1546                 debug_print("\n");
1547         }
1548         
1549         return result;
1550 }
1551 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
1552                               MsgInfoList *msglist, GRelation *relation)
1553 {
1554         FolderItem *src;
1555         gchar *destdir;
1556         GSList *seq_list, *cur;
1557         MsgInfo *msginfo;
1558         IMAPSession *session;
1559         gint ok = MAILIMAP_NO_ERROR;
1560         GRelation *uid_mapping;
1561         gint last_num = 0;
1562         gboolean single = FALSE;
1563
1564         g_return_val_if_fail(folder != NULL, -1);
1565         g_return_val_if_fail(dest != NULL, -1);
1566         g_return_val_if_fail(msglist != NULL, -1);
1567         
1568         debug_print("getting session...\n");
1569         session = imap_session_get(folder);
1570         
1571         if (!session) {
1572                 return -1;
1573         }
1574
1575         msginfo = (MsgInfo *)msglist->data;
1576         if (msglist->next == NULL)
1577                 single = TRUE;
1578         src = msginfo->folder;
1579         if (src == dest) {
1580                 g_warning("the src folder is identical to the dest.\n");
1581                 return -1;
1582         }
1583
1584         if (src->folder != dest->folder) {
1585                 GSList *infolist = NULL, *cur;
1586                 int res = -1;
1587                 for (cur = msglist; cur; cur = cur->next) {
1588                         msginfo = (MsgInfo *)cur->data;
1589                         MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1590                         fileinfo->file = procmsg_get_message_file(msginfo);
1591                         fileinfo->flags = &(msginfo->flags);
1592                         infolist = g_slist_prepend(infolist, fileinfo);
1593                 }
1594                 infolist = g_slist_reverse(infolist);
1595                 res = folder_item_add_msgs(dest, infolist, FALSE);
1596                 for (cur = infolist; cur; cur = cur->next) {
1597                         MsgFileInfo *info = (MsgFileInfo *)cur->data;
1598                         g_free(info->file);
1599                         g_free(info);
1600                 }
1601                 g_slist_free(infolist);
1602                 return res;
1603         } 
1604
1605         lock_session(session); /* unlocked later in the function */
1606
1607         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
1608                          NULL, NULL, NULL, NULL, FALSE);
1609         if (ok != MAILIMAP_NO_ERROR) {
1610                 return ok;
1611         }
1612
1613         unlock_session(session);
1614
1615         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
1616         seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1617         uid_mapping = g_relation_new(2);
1618         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1619         
1620         statusbar_print_all(_("Copying messages..."));
1621         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1622                 struct mailimap_set * seq_set;
1623                 struct mailimap_set * source = NULL;
1624                 struct mailimap_set * dest = NULL;
1625                 seq_set = cur->data;
1626
1627                 debug_print("Copying messages from %s to %s ...\n",
1628                             src->path, destdir);
1629
1630                 lock_session(session); /* unlocked later in the function */
1631                 ok = imap_cmd_copy(session, seq_set, destdir, uid_mapping,
1632                         &source, &dest);
1633                 
1634                 if (is_fatal(ok)) {
1635                         session = NULL;
1636                 }
1637
1638                 if (ok == MAILIMAP_NO_ERROR) {
1639                         unlock_session(session);
1640                         if (relation && source && dest) {
1641                                 GSList *s_list = flatten_mailimap_set(source);
1642                                 GSList *d_list = flatten_mailimap_set(dest);
1643                                 GSList *s_cur, *d_cur;
1644                                 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1645
1646                                         for (s_cur = s_list, d_cur = d_list; 
1647                                              s_cur && d_cur; 
1648                                              s_cur = s_cur->next, d_cur = d_cur->next) {
1649                                                 g_relation_insert(uid_mapping, s_cur->data, d_cur->data);
1650                                         }
1651
1652                                 } else {
1653                                         debug_print("hhhmm, source list length != dest list length.\n");
1654                                 }
1655                                 g_slist_free(s_list);
1656                                 g_slist_free(d_list);
1657                         }
1658                 }
1659
1660
1661                 if (source)
1662                         mailimap_set_free(source);
1663                 if (dest)
1664                         mailimap_set_free(dest);
1665
1666                 if (ok != MAILIMAP_NO_ERROR) {
1667                         g_relation_destroy(uid_mapping);
1668                         imap_lep_set_free(seq_list);
1669                         statusbar_pop_all();
1670                         return -1;
1671                 }
1672         }
1673
1674         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1675                 MsgInfo *msginfo = (MsgInfo *)cur->data;
1676                 GTuples *tuples;
1677
1678                 tuples = g_relation_select(uid_mapping, 
1679                                            GINT_TO_POINTER(msginfo->msgnum),
1680                                            0);
1681                 if (tuples->len > 0) {
1682                         gint num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
1683                         g_relation_insert(relation, msginfo,
1684                                           GINT_TO_POINTER(num));
1685                         if (num > last_num)
1686                                 last_num = num;
1687                         debug_print("copied message %d as %d\n", msginfo->msgnum, num);
1688                         /* put the local file in the imapcache, so that we don't
1689                          * have to fetch it back later. */
1690                         if (num > 0) {
1691                                 gchar *cache_path = folder_item_get_path(msginfo->folder);
1692                                 gchar *real_file = g_strconcat(
1693                                         cache_path, G_DIR_SEPARATOR_S, 
1694                                         itos(msginfo->msgnum), NULL);
1695                                 gchar *cache_file = NULL;
1696                                 g_free(cache_path);
1697                                 cache_path = folder_item_get_path(dest);
1698                                 cache_file = g_strconcat(
1699                                         cache_path, G_DIR_SEPARATOR_S, 
1700                                         itos(num), NULL);
1701                                 if (!is_dir_exist(cache_path))
1702                                         make_dir_hier(cache_path);
1703                                 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
1704                                         copy_file(real_file, cache_file, TRUE);
1705                                         debug_print("copied to cache: %s\n", cache_file);
1706                                 }
1707                                 g_free(real_file);
1708                                 g_free(cache_file);
1709                                 g_free(cache_path);
1710                         }
1711                 } else
1712                         g_relation_insert(relation, msginfo,
1713                                           GINT_TO_POINTER(0));
1714                 g_tuples_destroy(tuples);
1715         }
1716         statusbar_pop_all();
1717
1718         g_relation_destroy(uid_mapping);
1719         imap_lep_set_free(seq_list);
1720
1721         g_free(destdir);
1722         
1723         IMAP_FOLDER_ITEM(dest)->lastuid = 0;
1724         IMAP_FOLDER_ITEM(dest)->uid_next = 0;
1725         g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
1726         IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
1727
1728         imap_scan_required(folder, dest);
1729         if (ok == MAILIMAP_NO_ERROR)
1730                 return last_num;
1731         else
1732                 return -1;
1733 }
1734
1735 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1736 {
1737         GSList msglist;
1738
1739         g_return_val_if_fail(msginfo != NULL, -1);
1740
1741         msglist.data = msginfo;
1742         msglist.next = NULL;
1743
1744         return imap_copy_msgs(folder, dest, &msglist, NULL);
1745 }
1746
1747 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
1748                     MsgInfoList *msglist, GRelation *relation)
1749 {
1750         MsgInfo *msginfo;
1751         gint ret;
1752
1753         g_return_val_if_fail(folder != NULL, -1);
1754         g_return_val_if_fail(dest != NULL, -1);
1755         g_return_val_if_fail(msglist != NULL, -1);
1756
1757         msginfo = (MsgInfo *)msglist->data;
1758         g_return_val_if_fail(msginfo->folder != NULL, -1);
1759
1760         ret = imap_do_copy_msgs(folder, dest, msglist, relation);
1761         return ret;
1762 }
1763
1764
1765 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
1766                                 MsgInfoList *msglist, GRelation *relation)
1767 {
1768         gchar *destdir, *dir;
1769         GSList *numlist = NULL, *cur;
1770         MsgInfo *msginfo;
1771         IMAPSession *session;
1772         gint ok = MAILIMAP_NO_ERROR;
1773         GRelation *uid_mapping;
1774         
1775         g_return_val_if_fail(folder != NULL, -1);
1776         g_return_val_if_fail(dest != NULL, -1);
1777         g_return_val_if_fail(msglist != NULL, -1);
1778
1779         debug_print("getting session...\n");
1780         session = imap_session_get(folder);
1781         if (!session) {
1782                 return -1;
1783         }
1784
1785         lock_session(session); /* unlocked later in the function */
1786
1787         msginfo = (MsgInfo *)msglist->data;
1788
1789         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
1790                          NULL, NULL, NULL, NULL, FALSE);
1791         if (ok != MAILIMAP_NO_ERROR) {
1792                 return ok;
1793         }
1794
1795         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
1796         for (cur = msglist; cur; cur = cur->next) {
1797                 msginfo = (MsgInfo *)cur->data;
1798                 if (!MSG_IS_DELETED(msginfo->flags))
1799                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
1800         }
1801         numlist = g_slist_reverse(numlist);
1802
1803         uid_mapping = g_relation_new(2);
1804         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1805
1806         if (numlist != NULL) {
1807                 ok = imap_set_message_flags
1808                         (session, numlist, IMAP_FLAG_DELETED, TRUE);
1809                 if (ok != MAILIMAP_NO_ERROR) {
1810                         log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
1811                         return ok;
1812                 }
1813         } /* else we just need to expunge */
1814         ok = imap_cmd_expunge(session);
1815         if (ok != MAILIMAP_NO_ERROR) {
1816                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
1817                 return ok;
1818         }
1819         
1820         session->folder_content_changed = TRUE;
1821         unlock_session(session);
1822
1823         dir = folder_item_get_path(msginfo->folder);
1824         if (is_dir_exist(dir)) {
1825                 for (cur = msglist; cur; cur = cur->next) {
1826                         msginfo = (MsgInfo *)cur->data;
1827                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
1828                 }
1829         }
1830         g_free(dir);
1831
1832         g_relation_destroy(uid_mapping);
1833         g_slist_free(numlist);
1834
1835         imap_scan_required(folder, dest);
1836
1837         g_free(destdir);
1838         if (ok == MAILIMAP_NO_ERROR)
1839                 return 0;
1840         else
1841                 return -1;
1842 }
1843
1844 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
1845                     MsgInfoList *msglist, GRelation *relation)
1846 {
1847         MsgInfo *msginfo;
1848
1849         g_return_val_if_fail(folder != NULL, -1);
1850         g_return_val_if_fail(dest != NULL, -1);
1851         if (msglist == NULL)
1852                 return 0;
1853
1854         msginfo = (MsgInfo *)msglist->data;
1855         g_return_val_if_fail(msginfo->folder != NULL, -1);
1856
1857         return imap_do_remove_msgs(folder, dest, msglist, relation);
1858 }
1859
1860 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
1861 {
1862         GSList *list = folder_item_get_msg_list(item);
1863         gint res = imap_remove_msgs(folder, item, list, NULL);
1864         procmsg_msg_list_free(list);
1865         return res;
1866 }
1867
1868 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
1869                                     MsgInfo *msginfo)
1870 {
1871         /* TODO: properly implement this method */
1872         return FALSE;
1873 }
1874
1875 static gint imap_close(Folder *folder, FolderItem *item)
1876 {
1877         return 0;
1878 }
1879
1880 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
1881 {
1882         FolderItem *item = NULL;
1883         IMAPSession *session;
1884         gchar *root_folder = NULL;
1885
1886         g_return_val_if_fail(folder != NULL, -1);
1887         g_return_val_if_fail(folder->account != NULL, -1);
1888
1889         debug_print("getting session...\n");
1890         session = imap_session_get(folder);
1891         if (!session) {
1892                 if (!folder->node) {
1893                         folder_tree_destroy(folder);
1894                         item = folder_item_new(folder, folder->name, NULL);
1895                         item->folder = folder;
1896                         folder->node = item->node = g_node_new(item);
1897                 }
1898                 return -1;
1899         }
1900
1901         if (folder->account->imap_dir && *folder->account->imap_dir) {
1902                 gchar *real_path;
1903                 int r;
1904                 clist * lep_list;
1905
1906                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
1907                 extract_quote(root_folder, '"');
1908                 subst_char(root_folder,
1909                            imap_get_path_separator(session, IMAP_FOLDER(folder),
1910                                                    root_folder),
1911                            '/');
1912                 strtailchomp(root_folder, '/');
1913                 real_path = imap_get_real_path
1914                         (session, IMAP_FOLDER(folder), root_folder);
1915                 debug_print("IMAP root directory: %s\n", real_path);
1916
1917                 /* check if root directory exist */
1918
1919                 r = imap_threaded_list(session->folder, "", real_path,
1920                                        &lep_list);
1921
1922                 if (r != MAILIMAP_NO_ERROR)
1923                         imap_handle_error(SESSION(session), r);
1924
1925                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
1926                         if (!folder->node) {
1927                                 item = folder_item_new(folder, folder->name, NULL);
1928                                 item->folder = folder;
1929                                 folder->node = item->node = g_node_new(item);
1930                         }
1931                         return -1;
1932                 }
1933                 mailimap_list_result_free(lep_list);
1934                                 
1935                 g_free(real_path);
1936         }
1937
1938         if (folder->node)
1939                 item = FOLDER_ITEM(folder->node->data);
1940                 
1941         if (item && !item->path && root_folder) {
1942                 item->path = g_strdup(root_folder);
1943         }
1944
1945         if (!item || ((item->path || root_folder) &&
1946                       strcmp2(item->path, root_folder) != 0)) {
1947                 folder_tree_destroy(folder);
1948                 item = folder_item_new(folder, folder->name, root_folder);
1949                 item->folder = folder;
1950                 folder->node = item->node = g_node_new(item);
1951         }
1952
1953         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
1954         imap_create_missing_folders(folder);
1955
1956         return 0;
1957 }
1958
1959 static gint imap_scan_tree(Folder *folder)
1960 {
1961         gboolean subs_only = FALSE;
1962         if (folder->account) {
1963                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
1964                 subs_only = folder->account->imap_subsonly;
1965         }
1966         return imap_scan_tree_real(folder, subs_only);
1967 }
1968
1969 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
1970 {
1971         Folder *folder;
1972         IMAPFolder *imapfolder;
1973         FolderItem *new_item;
1974         GSList *item_list, *cur;
1975         GNode *node;
1976         gchar *real_path;
1977         gchar *wildcard_path;
1978         gchar separator;
1979         gchar wildcard[3];
1980         clist * lep_list;
1981         int r;
1982         
1983         g_return_val_if_fail(item != NULL, -1);
1984         g_return_val_if_fail(item->folder != NULL, -1);
1985         g_return_val_if_fail(item->no_sub == FALSE, -1);
1986
1987         folder = item->folder;
1988         imapfolder = IMAP_FOLDER(folder);
1989
1990         separator = imap_get_path_separator(session, imapfolder, item->path);
1991
1992         if (folder->ui_func)
1993                 folder->ui_func(folder, item, folder->ui_func_data);
1994
1995         if (item->path) {
1996                 wildcard[0] = separator;
1997                 wildcard[1] = '%';
1998                 wildcard[2] = '\0';
1999                 real_path = imap_get_real_path(session, imapfolder, item->path);
2000         } else {
2001                 wildcard[0] = '%';
2002                 wildcard[1] = '\0';
2003                 real_path = g_strdup("");
2004         }
2005
2006         Xstrcat_a(wildcard_path, real_path, wildcard,
2007                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2008         lep_list = NULL;
2009         
2010         if (subs_only)
2011                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2012         else
2013                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2014
2015         if (r != MAILIMAP_NO_ERROR) {
2016                 imap_handle_error(SESSION(session), r);
2017                 item_list = NULL;
2018         }
2019         else {
2020                 item_list = imap_list_from_lep(imapfolder,
2021                                                lep_list, real_path, FALSE);
2022                 mailimap_list_result_free(lep_list);
2023         }
2024         
2025         g_free(real_path);
2026
2027         node = item->node->children;
2028         while (node != NULL) {
2029                 FolderItem *old_item = FOLDER_ITEM(node->data);
2030                 GNode *next = node->next;
2031
2032                 new_item = NULL;
2033                 for (cur = item_list; cur != NULL; cur = cur->next) {
2034                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2035                         if (!strcmp2(old_item->path, cur_item->path)) {
2036                                 new_item = cur_item;
2037                                 break;
2038                         }
2039                 }
2040                 if (!new_item) {
2041                         if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
2042                                 debug_print("not removing INBOX\n");
2043                         } else {
2044                                 debug_print("folder '%s' not found. removing...\n",
2045                                             old_item->path);
2046                                 folder_item_remove(old_item);
2047                         }
2048                 } else {
2049                         old_item->no_sub = new_item->no_sub;
2050                         old_item->no_select = new_item->no_select;
2051                         if (old_item->no_sub == TRUE && node->children) {
2052                                 debug_print("folder '%s' doesn't have "
2053                                             "subfolders. removing...\n",
2054                                             old_item->path);
2055                                 folder_item_remove_children(old_item);
2056                         }
2057                 }
2058
2059                 node = next;
2060         }
2061
2062         for (cur = item_list; cur != NULL; cur = cur->next) {
2063                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2064                 new_item = NULL;
2065
2066                 for (node = item->node->children; node != NULL;
2067                      node = node->next) {
2068                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
2069                                      cur_item->path)) {
2070                                 new_item = FOLDER_ITEM(node->data);
2071                                 folder_item_destroy(cur_item);
2072                                 cur_item = NULL;
2073                                 break;
2074                         }
2075                 }
2076                 if (!new_item) {
2077                         new_item = cur_item;
2078                         debug_print("new folder '%s' found.\n", new_item->path);
2079                         folder_item_append(item, new_item);
2080                 }
2081
2082                 if (!strcmp(new_item->path, "INBOX")) {
2083                         new_item->stype = F_INBOX;
2084                         folder->inbox = new_item;
2085                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2086                         gchar *base;
2087
2088                         base = g_path_get_basename(new_item->path);
2089
2090                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2091                                 new_item->stype = F_OUTBOX;
2092                                 folder->outbox = new_item;
2093                         } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
2094                                 new_item->stype = F_DRAFT;
2095                                 folder->draft = new_item;
2096                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2097                                 new_item->stype = F_QUEUE;
2098                                 folder->queue = new_item;
2099                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2100                                 new_item->stype = F_TRASH;
2101                                 folder->trash = new_item;
2102                         }
2103                         g_free(base);
2104                 }
2105
2106                 if (new_item->no_sub == FALSE)
2107                         imap_scan_tree_recursive(session, new_item, subs_only);
2108         }
2109
2110         g_slist_free(item_list);
2111
2112         return MAILIMAP_NO_ERROR;
2113 }
2114
2115 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2116 {
2117         IMAPSession *session = imap_session_get(folder);
2118         gchar *real_path;
2119         gchar *wildcard_path;
2120         gchar separator;
2121         gchar wildcard[3];
2122         clist * lep_list;
2123         GSList *item_list = NULL, *cur;
2124         GList *child_list = NULL, *tmplist = NULL;
2125         GSList *sub_list = NULL;
2126         int r;
2127
2128         if (!session)
2129                 return NULL;
2130
2131         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
2132
2133         if (item->path) {
2134                 wildcard[0] = separator;
2135                 wildcard[1] = '%';
2136                 wildcard[2] = '\0';
2137                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2138         } else {
2139                 wildcard[0] = '%';
2140                 wildcard[1] = '\0';
2141                 real_path = g_strdup("");
2142         }
2143
2144         Xstrcat_a(wildcard_path, real_path, wildcard,
2145                   {g_free(real_path); return NULL;});
2146         lep_list = NULL;
2147         
2148         if (unsubs_only)
2149                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2150                                 item->path?item->path:item->name);
2151         else
2152                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2153                                 item->path?item->path:item->name);
2154
2155         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2156         if (r) {
2157                 statusbar_pop_all();
2158                 return NULL;
2159         }
2160         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2161                                lep_list, real_path, FALSE);
2162         mailimap_list_result_free(lep_list);
2163
2164         for (cur = item_list; cur != NULL; cur = cur->next) {
2165                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2166                 if (recursive) {
2167                         tmplist = imap_scan_subtree(folder, cur_item, 
2168                                         unsubs_only, recursive);
2169                         if (tmplist)
2170                                 child_list = g_list_concat(child_list, tmplist);
2171                 }
2172                 child_list = g_list_prepend(child_list,
2173                                 imap_get_real_path(session, 
2174                                         IMAP_FOLDER(folder), cur_item->path));
2175                 
2176                 folder_item_destroy(cur_item);
2177         }
2178         child_list = g_list_reverse(child_list);
2179         g_slist_free(item_list);
2180
2181         if (unsubs_only) {
2182                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2183                 if (r) {
2184                         statusbar_pop_all();
2185                         return NULL;
2186                 }
2187                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2188                                        lep_list, real_path, FALSE);
2189                 mailimap_list_result_free(lep_list);
2190
2191                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2192                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2193                         GList *oldlitem = NULL;
2194                         gchar *tmp = imap_get_real_path(session, 
2195                                         IMAP_FOLDER(folder), cur_item->path);
2196                         folder_item_destroy(cur_item);
2197                         oldlitem = g_list_find_custom(
2198                                         child_list, tmp, (GCompareFunc)strcmp2);
2199                         if (oldlitem) {
2200                                 child_list = g_list_remove_link(child_list, oldlitem);
2201                                 g_free(oldlitem->data);
2202                                 g_list_free(oldlitem);
2203                         }
2204                         g_free(tmp);
2205                 }
2206         }
2207
2208         statusbar_pop_all();
2209
2210         return child_list;
2211 }
2212
2213 static gint imap_create_tree(Folder *folder)
2214 {
2215         g_return_val_if_fail(folder != NULL, -1);
2216         g_return_val_if_fail(folder->node != NULL, -1);
2217         g_return_val_if_fail(folder->node->data != NULL, -1);
2218         g_return_val_if_fail(folder->account != NULL, -1);
2219
2220         imap_scan_tree(folder);
2221         imap_create_missing_folders(folder);
2222
2223         return 0;
2224 }
2225
2226 static void imap_create_missing_folders(Folder *folder)
2227 {
2228         g_return_if_fail(folder != NULL);
2229
2230         if (!folder->inbox)
2231                 folder->inbox = imap_create_special_folder
2232                         (folder, F_INBOX, "INBOX");
2233         if (!folder->trash)
2234                 folder->trash = imap_create_special_folder
2235                         (folder, F_TRASH, "Trash");
2236         if (!folder->queue)
2237                 folder->queue = imap_create_special_folder
2238                         (folder, F_QUEUE, "Queue");
2239         if (!folder->outbox)
2240                 folder->outbox = imap_create_special_folder
2241                         (folder, F_OUTBOX, "Sent");
2242         if (!folder->draft)
2243                 folder->draft = imap_create_special_folder
2244                         (folder, F_DRAFT, "Drafts");
2245 }
2246
2247 static FolderItem *imap_create_special_folder(Folder *folder,
2248                                               SpecialFolderItemType stype,
2249                                               const gchar *name)
2250 {
2251         FolderItem *item;
2252         FolderItem *new_item;
2253
2254         g_return_val_if_fail(folder != NULL, NULL);
2255         g_return_val_if_fail(folder->node != NULL, NULL);
2256         g_return_val_if_fail(folder->node->data != NULL, NULL);
2257         g_return_val_if_fail(folder->account != NULL, NULL);
2258         g_return_val_if_fail(name != NULL, NULL);
2259
2260         item = FOLDER_ITEM(folder->node->data);
2261         new_item = imap_create_folder(folder, item, name);
2262
2263         if (!new_item) {
2264                 g_warning("Can't create '%s'\n", name);
2265                 if (!folder->inbox) return NULL;
2266
2267                 new_item = imap_create_folder(folder, folder->inbox, name);
2268                 if (!new_item)
2269                         g_warning("Can't create '%s' under INBOX\n", name);
2270                 else
2271                         new_item->stype = stype;
2272         } else
2273                 new_item->stype = stype;
2274
2275         return new_item;
2276 }
2277
2278 static gchar *imap_folder_get_path(Folder *folder)
2279 {
2280         gchar *folder_path;
2281
2282         g_return_val_if_fail(folder != NULL, NULL);
2283         g_return_val_if_fail(folder->account != NULL, NULL);
2284
2285         folder_path = g_strconcat(get_imap_cache_dir(),
2286                                   G_DIR_SEPARATOR_S,
2287                                   folder->account->recv_server,
2288                                   G_DIR_SEPARATOR_S,
2289                                   folder->account->userid,
2290                                   NULL);
2291
2292         return folder_path;
2293 }
2294
2295 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
2296 {
2297         gchar *folder_path, *path;
2298
2299         g_return_val_if_fail(folder != NULL, NULL);
2300         g_return_val_if_fail(item != NULL, NULL);
2301         folder_path = imap_folder_get_path(folder);
2302
2303         g_return_val_if_fail(folder_path != NULL, NULL);
2304         if (folder_path[0] == G_DIR_SEPARATOR) {
2305                 if (item->path)
2306                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
2307                                            item->path, NULL);
2308                 else
2309                         path = g_strdup(folder_path);
2310         } else {
2311                 if (item->path)
2312                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2313                                            folder_path, G_DIR_SEPARATOR_S,
2314                                            item->path, NULL);
2315                 else
2316                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2317                                            folder_path, NULL);
2318         }
2319         g_free(folder_path);
2320
2321         return path;
2322 }
2323
2324 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
2325                                const gchar *name)
2326 {
2327         gchar *dirpath, *imap_path;
2328         IMAPSession *session;
2329         FolderItem *new_item;
2330         gchar separator;
2331         gchar *new_name;
2332         const gchar *p;
2333         gint ok;
2334         gboolean no_select = FALSE, no_sub = FALSE;
2335         gboolean exist = FALSE;
2336         
2337         g_return_val_if_fail(folder != NULL, NULL);
2338         g_return_val_if_fail(folder->account != NULL, NULL);
2339         g_return_val_if_fail(parent != NULL, NULL);
2340         g_return_val_if_fail(name != NULL, NULL);
2341
2342         debug_print("getting session...\n");
2343         session = imap_session_get(folder);
2344         if (!session) {
2345                 return NULL;
2346         }
2347
2348         if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
2349                 dirpath = g_strdup(name);
2350         }else if (parent->path)
2351                 dirpath = g_strconcat(parent->path, "/", name, NULL);
2352         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
2353                 dirpath = g_strdup(name);
2354         else if (folder->account->imap_dir && *folder->account->imap_dir) {
2355                 gchar *imap_dir;
2356
2357                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
2358                 strtailchomp(imap_dir, '/');
2359                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
2360         } else
2361                 dirpath = g_strdup(name);
2362                 
2363         
2364
2365         /* keep trailing directory separator to create a folder that contains
2366            sub folder */
2367         imap_path = imap_utf8_to_modified_utf7(dirpath);
2368
2369         strtailchomp(dirpath, '/');
2370         Xstrdup_a(new_name, name, {
2371                 g_free(dirpath); 
2372                 return NULL;});
2373
2374         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path);
2375         imap_path_separator_subst(imap_path, separator);
2376         /* remove trailing / for display */
2377         strtailchomp(new_name, '/');
2378
2379         if (strcmp(dirpath, "INBOX") != 0) {
2380                 GPtrArray *argbuf;
2381                 int r;
2382                 clist * lep_list;
2383                 
2384                 argbuf = g_ptr_array_new();
2385                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
2386                 if (r != MAILIMAP_NO_ERROR) {
2387                         imap_handle_error(SESSION(session), r);
2388                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
2389                         g_free(imap_path);
2390                         g_free(dirpath);
2391                         ptr_array_free_strings(argbuf);
2392                         g_ptr_array_free(argbuf, TRUE);
2393                         return NULL;
2394                 }
2395                 
2396                 if (clist_count(lep_list) > 0)
2397                         exist = TRUE;
2398                 mailimap_list_result_free(lep_list);
2399                 lep_list = NULL;
2400                 if (!exist) {
2401                         ok = imap_cmd_create(session, imap_path);
2402                         if (ok != MAILIMAP_NO_ERROR) {
2403                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
2404                                 g_free(imap_path);
2405                                 g_free(dirpath);
2406                                 return NULL;
2407                         }
2408                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
2409                         if (r == MAILIMAP_NO_ERROR) {
2410                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2411                                                lep_list, dirpath, TRUE);
2412                                 if (item_list) {
2413                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2414                                         no_select = cur_item->no_select;
2415                                         no_sub = cur_item->no_sub;
2416                                         g_slist_free(item_list);
2417                                 } 
2418                                 mailimap_list_result_free(lep_list);
2419                         } else {
2420                                 imap_handle_error(SESSION(session), r);
2421                         }
2422                 }
2423                 imap_threaded_subscribe(folder, imap_path, TRUE);
2424         } else {
2425                 clist *lep_list;
2426                 int r;
2427                 /* just get flags */
2428                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
2429                 if (r == MAILIMAP_NO_ERROR) {
2430                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2431                                        lep_list, dirpath, TRUE);
2432                         if (item_list) {
2433                                 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2434                                 no_select = cur_item->no_select;
2435                                 no_sub = cur_item->no_sub;
2436                                 g_slist_free(item_list);
2437                         } 
2438                         mailimap_list_result_free(lep_list);
2439                 } else {
2440                         imap_handle_error(SESSION(session), r);
2441                 }
2442         }
2443
2444         new_item = folder_item_new(folder, new_name, dirpath);
2445         new_item->no_select = no_select;
2446         new_item->no_sub = no_sub;
2447         folder_item_append(parent, new_item);
2448         g_free(imap_path);
2449         g_free(dirpath);
2450
2451         dirpath = folder_item_get_path(new_item);
2452         if (!is_dir_exist(dirpath))
2453                 make_dir_hier(dirpath);
2454         g_free(dirpath);
2455
2456         if (exist) {
2457                 /* folder existed, scan it */
2458                 imap_scan_required(folder, new_item);
2459                 folder_item_scan_full(new_item, FALSE);
2460         }
2461
2462         return new_item;
2463 }
2464
2465 static gint imap_rename_folder(Folder *folder, FolderItem *item,
2466                                const gchar *name)
2467 {
2468         gchar *dirpath;
2469         gchar *newpath;
2470         gchar *real_oldpath;
2471         gchar *real_newpath;
2472         gchar *paths[2];
2473         gchar *old_cache_dir;
2474         gchar *new_cache_dir;
2475         IMAPSession *session;
2476         gchar separator;
2477         gint ok;
2478         gint exists, recent, unseen;
2479         guint32 uid_validity;
2480
2481         g_return_val_if_fail(folder != NULL, -1);
2482         g_return_val_if_fail(item != NULL, -1);
2483         g_return_val_if_fail(item->path != NULL, -1);
2484         g_return_val_if_fail(name != NULL, -1);
2485
2486         debug_print("getting session...\n");
2487         session = imap_session_get(folder);
2488         if (!session) {
2489                 return -1;
2490         }
2491
2492         if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path)) != NULL) {
2493                 g_warning(_("New folder name must not contain the namespace "
2494                             "path separator"));
2495                 return -1;
2496         }
2497
2498         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2499
2500         g_free(session->mbox);
2501         session->mbox = NULL;
2502         session->exists = 0;
2503         session->recent = 0;
2504         session->expunge = 0;
2505         ok = imap_cmd_examine(session, "INBOX",
2506                               &exists, &recent, &unseen, &uid_validity, FALSE);
2507         if (ok != MAILIMAP_NO_ERROR) {
2508                 g_free(real_oldpath);
2509                 return -1;
2510         }
2511
2512         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
2513         if (strchr(item->path, G_DIR_SEPARATOR)) {
2514                 dirpath = g_path_get_dirname(item->path);
2515                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
2516                 g_free(dirpath);
2517         } else
2518                 newpath = g_strdup(name);
2519
2520         real_newpath = imap_utf8_to_modified_utf7(newpath);
2521         imap_path_separator_subst(real_newpath, separator);
2522
2523         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
2524         if (ok != MAILIMAP_NO_ERROR) {
2525                 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
2526                             real_oldpath, real_newpath);
2527                 g_free(real_oldpath);
2528                 g_free(newpath);
2529                 g_free(real_newpath);
2530                 return -1;
2531         }
2532         g_free(item->name);
2533         item->name = g_strdup(name);
2534
2535         old_cache_dir = folder_item_get_path(item);
2536
2537         paths[0] = g_strdup(item->path);
2538         paths[1] = newpath;
2539         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2540                         imap_rename_folder_func, paths);
2541
2542         if (is_dir_exist(old_cache_dir)) {
2543                 new_cache_dir = folder_item_get_path(item);
2544                 if (rename(old_cache_dir, new_cache_dir) < 0) {
2545                         FILE_OP_ERROR(old_cache_dir, "rename");
2546                 }
2547                 g_free(new_cache_dir);
2548         }
2549
2550         g_free(old_cache_dir);
2551         g_free(paths[0]);
2552         g_free(newpath);
2553         g_free(real_oldpath);
2554         g_free(real_newpath);
2555         return 0;
2556 }
2557
2558 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
2559 {
2560         gchar *path;
2561         gint r = -1;
2562         IMAPSession *session;
2563         debug_print("getting session...\n");
2564
2565         session = imap_session_get(folder);
2566         if (!session) {
2567                 return -1;
2568         }
2569         if (item && item->path) {
2570                 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2571                 if (!path)
2572                         return -1;
2573                 if (!strcmp(path, "INBOX") && sub == FALSE)
2574                         return -1;
2575                 debug_print("%ssubscribing %s\n", sub?"":"un", path);
2576                 r = imap_threaded_subscribe(folder, path, sub);
2577                 g_free(path);
2578         } else if (rpath) {
2579                 r = imap_threaded_subscribe(folder, rpath, sub);
2580         } else
2581                 return -1;
2582         return r;
2583 }
2584
2585 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
2586 {
2587         gint ok;
2588         IMAPSession *session;
2589         gchar *path;
2590         gchar *cache_dir;
2591         gboolean selected_folder;
2592
2593         g_return_val_if_fail(folder != NULL, -1);
2594         g_return_val_if_fail(item != NULL, -1);
2595         g_return_val_if_fail(item->path != NULL, -1);
2596
2597         debug_print("getting session...\n");
2598         session = imap_session_get(folder);
2599         if (!session) {
2600                 return -1;
2601         }
2602         path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2603
2604         imap_threaded_subscribe(folder, path, FALSE);
2605
2606         selected_folder = (session->mbox != NULL) &&
2607                           (!strcmp(session->mbox, item->path));
2608         if (selected_folder) {
2609                 ok = imap_cmd_close(session);
2610                 if (ok != MAILIMAP_NO_ERROR) {
2611                         debug_print("close err %d\n", ok);
2612                         imap_handle_error(SESSION(session), ok);
2613                         return ok;
2614                 }
2615         }
2616         ok = imap_cmd_delete(session, path);
2617         if (ok != MAILIMAP_NO_ERROR) {
2618                 gchar *tmp = g_strdup_printf("%s%c", path, 
2619                                 imap_get_path_separator(session, IMAP_FOLDER(folder), path));
2620                 g_free(path);
2621                 path = tmp;
2622                 ok = imap_cmd_delete(session, path);
2623         }
2624
2625         if (ok != MAILIMAP_NO_ERROR) {
2626                 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
2627                 g_free(path);
2628                 return -1;
2629         }
2630
2631         g_free(path);
2632         cache_dir = folder_item_get_path(item);
2633         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
2634                 g_warning("can't remove directory '%s'\n", cache_dir);
2635         g_free(cache_dir);
2636         folder_item_remove(item);
2637         return 0;
2638 }
2639
2640 static gint imap_remove_folder(Folder *folder, FolderItem *item)
2641 {
2642         GNode *node, *next;
2643
2644         g_return_val_if_fail(item != NULL, -1);
2645         g_return_val_if_fail(item->folder != NULL, -1);
2646         g_return_val_if_fail(item->node != NULL, -1);
2647
2648         node = item->node->children;
2649         while (node != NULL) {
2650                 next = node->next;
2651                 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
2652                         return -1;
2653                 node = next;
2654         }
2655         debug_print("IMAP removing %s\n", item->path);
2656
2657         if (imap_remove_all_msg(folder, item) < 0)
2658                 return -1;
2659         return imap_remove_folder_real(folder, item);
2660 }
2661
2662 typedef struct _uncached_data {
2663         IMAPSession *session;
2664         FolderItem *item;
2665         MsgNumberList *numlist;
2666         guint cur;
2667         guint total;
2668         gboolean done;
2669         int ok;
2670 } uncached_data;
2671
2672 static void *imap_get_uncached_messages_thread(void *data)
2673 {
2674         uncached_data *stuff = (uncached_data *)data;
2675         IMAPSession *session = stuff->session;
2676         FolderItem *item = stuff->item;
2677         MsgNumberList *numlist = stuff->numlist;
2678         
2679         GSList *newlist = NULL;
2680         GSList *llast = NULL;
2681         GSList *seq_list, *cur;
2682
2683         debug_print("uncached_messages\n");
2684         
2685         if (session == NULL || item == NULL || item->folder == NULL
2686             || FOLDER_CLASS(item->folder) != &imap_class) {
2687                 stuff->done = TRUE;
2688                 return NULL;
2689         }
2690         
2691         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
2692         debug_print("get msgs info\n");
2693         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2694                 struct mailimap_set * imapset;
2695                 unsigned int i;
2696                 int r;
2697                 carray * env_list;
2698                 int count;
2699                 
2700                 if (session->cancelled)
2701                         break;
2702                 
2703                 imapset = cur->data;
2704                 
2705                 r = imap_threaded_fetch_env(session->folder,
2706                                             imapset, &env_list);
2707                 if (r != MAILIMAP_NO_ERROR) {
2708                         imap_handle_error(SESSION(session), r);
2709                         if (is_fatal(r)) {
2710                                 stuff->ok = r;
2711                                 return NULL;
2712                         }
2713                         continue;
2714                 }
2715
2716                 session_set_access_time(SESSION(session));
2717
2718                 count = 0;
2719                 for(i = 0 ; i < carray_count(env_list) ; i ++) {
2720                         struct imap_fetch_env_info * info;
2721                         MsgInfo * msginfo;
2722                         
2723                         info = carray_get(env_list, i);
2724                         msginfo = imap_envelope_from_lep(info, item);
2725                         if (msginfo == NULL)
2726                                 continue;
2727                         msginfo->folder = item;
2728                         if (!newlist)
2729                                 llast = newlist = g_slist_append(newlist, msginfo);
2730                         else {
2731                                 llast = g_slist_append(llast, msginfo);
2732                                 llast = llast->next;
2733                         }
2734                         count ++;
2735                 }
2736                 
2737                 imap_fetch_env_free(env_list);
2738         }
2739         
2740         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2741                 struct mailimap_set * imapset;
2742                 
2743                 imapset = cur->data;
2744                 mailimap_set_free(imapset);
2745         }
2746         
2747         session_set_access_time(SESSION(session));
2748         stuff->done = TRUE;
2749         return newlist;
2750 }
2751
2752 #define MAX_MSG_NUM 50
2753
2754 static GSList *imap_get_uncached_messages(IMAPSession *session,
2755                                         FolderItem *item,
2756                                         MsgNumberList *numlist,
2757                                         int *r)
2758 {
2759         GSList *result = NULL;
2760         GSList * cur;
2761         uncached_data *data = g_new0(uncached_data, 1);
2762         int finished;
2763         
2764         finished = 0;
2765         cur = numlist;
2766         data->total = g_slist_length(numlist);
2767         data->ok = MAILIMAP_NO_ERROR;
2768         debug_print("messages list : %i\n", data->total);
2769
2770         while (cur != NULL) {
2771                 GSList * partial_result;
2772                 int count;
2773                 GSList * newlist;
2774                 GSList * llast;
2775                 
2776                 llast = NULL;
2777                 count = 0;
2778                 newlist = NULL;
2779                 while (count < MAX_MSG_NUM) {
2780                         void * p;
2781                         
2782                         p = cur->data;
2783                         
2784                         if (newlist == NULL)
2785                                 llast = newlist = g_slist_append(newlist, p);
2786                         else {
2787                                 llast = g_slist_append(llast, p);
2788                                 llast = llast->next;
2789                         }
2790                         count ++;
2791                         
2792                         cur = cur->next;
2793                         if (cur == NULL)
2794                                 break;
2795                 }
2796                 
2797                 data->done = FALSE;
2798                 data->session = session;
2799                 data->item = item;
2800                 data->numlist = newlist;
2801                 data->cur += count;
2802                 
2803                 if (prefs_common.work_offline && 
2804                     !inc_offline_should_override(FALSE,
2805                         _("Claws Mail needs network access in order "
2806                           "to access the IMAP server."))) {
2807                         g_free(data);
2808                         return NULL;
2809                 }
2810                 
2811                 partial_result =
2812                         (GSList *)imap_get_uncached_messages_thread(data);
2813                 *r = data->ok;
2814                 if (data->ok != MAILIMAP_NO_ERROR) {
2815                         goto bail;
2816                 }
2817                 statusbar_progress_all(data->cur,data->total, 1);
2818                 
2819                 g_slist_free(newlist);
2820                 
2821                 result = g_slist_concat(result, partial_result);
2822         }
2823 bail:
2824         g_free(data);
2825         
2826         statusbar_progress_all(0,0,0);
2827         statusbar_pop_all();
2828         
2829         return result;
2830 }
2831
2832 static void imap_delete_all_cached_messages(FolderItem *item)
2833 {
2834         gchar *dir;
2835
2836         g_return_if_fail(item != NULL);
2837         g_return_if_fail(item->folder != NULL);
2838         g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
2839
2840         debug_print("Deleting all cached messages...\n");
2841
2842         dir = folder_item_get_path(item);
2843         if (is_dir_exist(dir))
2844                 remove_all_numbered_files(dir);
2845         g_free(dir);
2846
2847         debug_print("done.\n");
2848 }
2849
2850 gchar imap_get_path_separator_for_item(FolderItem *item)
2851 {
2852         Folder *folder = NULL;
2853         IMAPFolder *imap_folder = NULL;
2854         IMAPSession *session = NULL;
2855         gchar result = '/';
2856         
2857         if (!item)
2858                 return '/';
2859         folder = item->folder;
2860         
2861         if (!folder)
2862                 return '/';
2863         
2864         imap_folder = IMAP_FOLDER(folder);
2865         
2866         if (!imap_folder)
2867                 return '/';
2868         
2869         debug_print("getting session...");
2870         session = imap_session_get(FOLDER(folder));
2871         result = imap_get_path_separator(session, imap_folder, item->path);
2872         return result;
2873 }
2874
2875 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder)
2876 {
2877         clist * lep_list;
2878         int r;
2879         gchar separator = '\0';
2880         
2881         g_return_val_if_fail(session != NULL, '/');
2882         r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
2883         
2884         if (r != MAILIMAP_NO_ERROR) {
2885                 imap_handle_error(SESSION(session), r);
2886                 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
2887                 return '\0';
2888         }
2889
2890         if (clist_count(lep_list) > 0) {
2891                 clistiter * iter = clist_begin(lep_list); 
2892                 struct mailimap_mailbox_list * mb;
2893                 mb = clist_content(iter);
2894
2895                 separator = mb->mb_delimiter;
2896                 debug_print("got separator: %c\n", folder->last_seen_separator);
2897         }
2898         mailimap_list_result_free(lep_list);
2899         return separator;
2900 }
2901
2902 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path)
2903 {
2904         gchar separator = '/';
2905
2906         if (folder->last_seen_separator == 0) {
2907                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "");
2908         }
2909
2910         if (folder->last_seen_separator == 0) {
2911                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX");
2912         }
2913
2914         if (folder->last_seen_separator != 0) {
2915                 debug_print("using separator: %c\n", folder->last_seen_separator);
2916                 return folder->last_seen_separator;
2917         }
2918
2919         return separator;
2920 }
2921
2922 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path)
2923 {
2924         gchar *real_path;
2925         gchar separator;
2926
2927         g_return_val_if_fail(folder != NULL, NULL);
2928         g_return_val_if_fail(path != NULL, NULL);
2929
2930         real_path = imap_utf8_to_modified_utf7(path);
2931         separator = imap_get_path_separator(session, folder, path);
2932         imap_path_separator_subst(real_path, separator);
2933
2934         return real_path;
2935 }
2936
2937 static gint imap_set_message_flags(IMAPSession *session,
2938                                    MsgNumberList *numlist,
2939                                    IMAPFlags flags,
2940                                    gboolean is_set)
2941 {
2942         gint ok = 0;
2943         GSList *seq_list;
2944         GSList * cur;
2945         gint total = 0;
2946         IMAPFolder *folder = NULL;
2947         GSList *sorted_list = NULL;
2948
2949         if (numlist == NULL || session == NULL)
2950                 return MAILIMAP_ERROR_BAD_STATE;
2951         
2952         folder = IMAP_FOLDER(session->folder);
2953         
2954         sorted_list = g_slist_copy(numlist);
2955         sorted_list = g_slist_sort(sorted_list, g_int_compare);
2956         
2957         cur = g_slist_last(sorted_list);
2958
2959         if (cur)
2960                 total = GPOINTER_TO_INT(cur->data);
2961         
2962         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
2963
2964         statusbar_print_all(_("Flagging messages..."));
2965
2966         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
2967                 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
2968                 struct mailimap_set_item *set_item = clist_content(
2969                                                         clist_begin(imapset->set_list));
2970
2971                 statusbar_progress_all(set_item->set_first, total, 1);
2972
2973                 ok = imap_cmd_store(session, imapset,
2974                                     flags, is_set);
2975                 statusbar_progress_all(set_item->set_last, total, 1);
2976                 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
2977                         /* reduce max set size */
2978                         folder->max_set_size /= 2;
2979                 }
2980                 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
2981                         break;
2982                 }
2983         }
2984         
2985         g_slist_free(sorted_list);
2986
2987         statusbar_progress_all(0,0,0);
2988         statusbar_pop_all();
2989
2990         imap_lep_set_free(seq_list);
2991         
2992         return ok;
2993 }
2994
2995 typedef struct _select_data {
2996         IMAPSession *session;
2997         gchar *real_path;
2998         gint *exists;
2999         gint *recent;
3000         gint *unseen;
3001         guint32 *uid_validity;
3002         gboolean done;
3003 } select_data;
3004
3005 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3006                         const gchar *path,
3007                         gint *exists, gint *recent, gint *unseen,
3008                         guint32 *uid_validity, gboolean block)
3009 {
3010         gchar *real_path;
3011         gint ok;
3012         gint exists_, recent_, unseen_;
3013         guint32 uid_validity_;
3014         
3015         if (!exists && !recent && !unseen && !uid_validity) {
3016                 if (session->mbox && strcmp(session->mbox, path) == 0)
3017                         return MAILIMAP_NO_ERROR;
3018         }
3019         if (!exists)
3020                 exists = &exists_;
3021         if (!recent)
3022                 recent = &recent_;
3023         if (!unseen)
3024                 unseen = &unseen_;
3025         if (!uid_validity)
3026                 uid_validity = &uid_validity_;
3027
3028         g_free(session->mbox);
3029         session->mbox = NULL;
3030         session->exists = 0;
3031         session->recent = 0;
3032         session->expunge = 0;
3033
3034         real_path = imap_get_real_path(session, folder, path);
3035
3036         ok = imap_cmd_select(session, real_path,
3037                              exists, recent, unseen, uid_validity, block);
3038         if (ok != MAILIMAP_NO_ERROR) {
3039                 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
3040         } else {
3041                 session->mbox = g_strdup(path);
3042                 session->folder_content_changed = FALSE;
3043                 session->exists = *exists;
3044                 session->recent = *recent;
3045                 session->expunge = 0;
3046                 session->unseen = *unseen;
3047                 session->uid_validity = *uid_validity;
3048                 debug_print("select: exists %d recent %d expunge %d uid_validity %d\n", 
3049                         session->exists, session->recent, session->expunge,
3050                         session->uid_validity);
3051         }
3052         g_free(real_path);
3053
3054         return ok;
3055 }
3056
3057 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3058                         const gchar *path, IMAPFolderItem *item,
3059                         gint *messages,
3060                         guint32 *uid_next, guint32 *uid_validity,
3061                         gint *unseen, gboolean block)
3062 {
3063         int r;
3064         clistiter * iter;
3065         struct mailimap_mailbox_data_status * data_status;
3066         int got_values;
3067         gchar *real_path;
3068         guint mask = 0;
3069         
3070         real_path = imap_get_real_path(session, folder, path);
3071
3072         if (messages) {
3073                 mask |= 1 << 0;
3074                 *messages = 0;
3075         }
3076         if (uid_next) {
3077                 mask |= 1 << 2;
3078                 *uid_next = 0;
3079         }
3080         if (uid_validity) {
3081                 mask |= 1 << 3;
3082                 *uid_validity = 0;
3083         }
3084         if (unseen) {
3085                 mask |= 1 << 4;
3086                 *unseen = 0;
3087         }
3088         
3089         if (session->mbox != NULL &&
3090             !strcmp(session->mbox, item->item.path)) {
3091                 r = imap_cmd_close(session);
3092                 if (r != MAILIMAP_NO_ERROR) {
3093                         imap_handle_error(SESSION(session), r);
3094                         debug_print("close err %d\n", r);
3095                         return r;
3096                 }
3097         }
3098         
3099         r = imap_threaded_status(FOLDER(folder), real_path, 
3100                 &data_status, mask);
3101
3102         g_free(real_path);
3103         if (r != MAILIMAP_NO_ERROR) {
3104                 imap_handle_error(SESSION(session), r);
3105                 debug_print("status err %d\n", r);
3106                 return r;
3107         }
3108         
3109         if (data_status->st_info_list == NULL) {
3110                 mailimap_mailbox_data_status_free(data_status);
3111                 debug_print("status->st_info_list == NULL\n");
3112                 return MAILIMAP_ERROR_BAD_STATE;
3113         }
3114         
3115         got_values = 0;
3116         for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
3117             iter = clist_next(iter)) {
3118                 struct mailimap_status_info * info;             
3119                 
3120                 info = clist_content(iter);
3121                 switch (info->st_att) {
3122                 case MAILIMAP_STATUS_ATT_MESSAGES:
3123                         if (messages) {
3124                                 * messages = info->st_value;
3125                                 got_values |= 1 << 0;
3126                         }
3127                         break;
3128                         
3129                 case MAILIMAP_STATUS_ATT_UIDNEXT:
3130                         if (uid_next) {
3131                                 * uid_next = info->st_value;
3132                                 got_values |= 1 << 2;
3133                         }
3134                         break;
3135                         
3136                 case MAILIMAP_STATUS_ATT_UIDVALIDITY:
3137                         if (uid_validity) {
3138                                 * uid_validity = info->st_value;
3139                                 got_values |= 1 << 3;
3140                         }
3141                         break;
3142                         
3143                 case MAILIMAP_STATUS_ATT_UNSEEN:
3144                         if (unseen) {
3145                                 * unseen = info->st_value;
3146                                 got_values |= 1 << 4;
3147                         }
3148                         break;
3149                 }
3150         }
3151         mailimap_mailbox_data_status_free(data_status);
3152         
3153         if (got_values != mask) {
3154                 g_warning("status: incomplete values received (%d)\n", got_values);
3155         }
3156         return MAILIMAP_NO_ERROR;
3157 }
3158
3159 static void imap_free_capabilities(IMAPSession *session)
3160 {
3161         slist_free_strings(session->capability);
3162         g_slist_free(session->capability);
3163         session->capability = NULL;
3164 }
3165
3166 /* low-level IMAP4rev1 commands */
3167
3168 static gint imap_cmd_login(IMAPSession *session,
3169                            const gchar *user, const gchar *pass,
3170                            const gchar *type)
3171 {
3172         int r;
3173         gint ok;
3174
3175         if (!strcmp(type, "LOGIN") && imap_has_capability(session, "LOGINDISABLED")) {
3176                 gint ok = MAILIMAP_ERROR_BAD_STATE;
3177                 if (imap_has_capability(session, "STARTTLS")) {
3178 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
3179                         log_warning(LOG_PROTOCOL, _("Server requires TLS to log in.\n"));
3180                         ok = imap_cmd_starttls(session);
3181                         if (ok != MAILIMAP_NO_ERROR) {
3182                                 log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
3183                                 return ok;
3184                         } else {
3185                                 /* refresh capas */
3186                                 imap_free_capabilities(session);
3187                                 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
3188                                         imap_handle_error(SESSION(session), r);
3189                                         log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
3190                                         return r;
3191                                 }
3192                         }
3193 #else           
3194                         log_error(LOG_PROTOCOL, _("Connection to %s failed: "
3195                                         "server requires TLS, but Claws Mail "
3196                                         "has been compiled without OpenSSL "
3197                                         "support.\n"),
3198                                         SESSION(session)->server);
3199                         return MAILIMAP_ERROR_BAD_STATE;
3200 #endif
3201                 } else {
3202                         log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
3203                         return MAILIMAP_ERROR_BAD_STATE;
3204                 }
3205         }
3206
3207         log_print(LOG_PROTOCOL, "IMAP4> Logging %s to %s using %s\n", 
3208                         user,
3209                         SESSION(session)->server,
3210                         type);
3211         r = imap_threaded_login(session->folder, user, pass, type);
3212         if (r != MAILIMAP_NO_ERROR) {
3213                 imap_handle_error(SESSION(session), r);
3214                 log_print(LOG_PROTOCOL, "IMAP4< Error logging in to %s\n",
3215                                 SESSION(session)->server);
3216                 ok = r;
3217         } else {
3218                 log_print(LOG_PROTOCOL, "IMAP4< Login to %s successful\n",
3219                                 SESSION(session)->server);
3220                 ok = MAILIMAP_NO_ERROR;
3221         }
3222         return ok;
3223 }
3224
3225 static gint imap_cmd_noop(IMAPSession *session)
3226 {
3227         int r;
3228         unsigned int exists, recent, expunge, unseen, uidnext, uidval;
3229         
3230         r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
3231         if (r != MAILIMAP_NO_ERROR) {
3232                 imap_handle_error(SESSION(session), r);
3233                 debug_print("noop err %d\n", r);
3234                 return r;
3235         }
3236
3237         session->folder_content_changed = FALSE;
3238
3239         if ((exists && exists != session->exists)
3240          || (recent && recent != session->recent)
3241          || (expunge && expunge != session->expunge)
3242          || (unseen && unseen != session->unseen)) {
3243                 session->folder_content_changed = TRUE;
3244         }
3245         if (uidnext != 0 && uidnext != session->uid_next) {
3246                 session->uid_next = uidnext;
3247                 session->folder_content_changed = TRUE;
3248         }
3249         if (uidval != 0 && uidval != session->uid_validity) {
3250                 session->uid_validity = uidval;
3251                 session->folder_content_changed = TRUE;
3252         }
3253
3254         session->exists = exists;
3255         session->recent = recent;
3256         session->expunge = expunge;
3257         session->unseen = unseen;
3258
3259         session_set_access_time(SESSION(session));
3260
3261         return MAILIMAP_NO_ERROR;
3262 }
3263
3264 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
3265 static gint imap_cmd_starttls(IMAPSession *session)
3266 {
3267         int r;
3268         
3269         r = imap_threaded_starttls(session->folder, 
3270                 SESSION(session)->server, SESSION(session)->port);
3271         if (r != MAILIMAP_NO_ERROR) {
3272                 imap_handle_error(SESSION(session), r);
3273                 debug_print("starttls err %d\n", r);
3274                 return r;
3275         }
3276         return MAILIMAP_NO_ERROR;
3277 }
3278 #endif
3279
3280 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
3281                             gint *exists, gint *recent, gint *unseen,
3282                             guint32 *uid_validity, gboolean block)
3283 {
3284         int r;
3285
3286         r = imap_threaded_select(session->folder, folder,
3287                                  exists, recent, unseen, uid_validity);
3288         if (r != MAILIMAP_NO_ERROR) {
3289                 imap_handle_error(SESSION(session), r);
3290                 debug_print("select err %d\n", r);
3291                 return r;
3292         }
3293         return MAILIMAP_NO_ERROR;
3294 }
3295
3296 static gint imap_cmd_close(IMAPSession *session)
3297 {
3298         int r;
3299
3300         r = imap_threaded_close(session->folder);
3301         if (r != MAILIMAP_NO_ERROR) {
3302                 imap_handle_error(SESSION(session), r);
3303                 debug_print("close err %d\n", r);
3304                 return r;
3305         }
3306         g_free(session->mbox);
3307         session->mbox = NULL;
3308         session->exists = 0;
3309         session->recent = 0;
3310         session->expunge = 0;
3311         return MAILIMAP_NO_ERROR;
3312 }
3313
3314 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
3315                              gint *exists, gint *recent, gint *unseen,
3316                              guint32 *uid_validity, gboolean block)
3317 {
3318         int r;
3319
3320         r = imap_threaded_examine(session->folder, folder,
3321                                   exists, recent, unseen, uid_validity);
3322         if (r != MAILIMAP_NO_ERROR) {
3323                 imap_handle_error(SESSION(session), r);
3324                 debug_print("examine err %d\n", r);
3325                 
3326                 return r;
3327         }
3328         return MAILIMAP_NO_ERROR;
3329 }
3330
3331 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
3332 {
3333         int r;
3334
3335         r = imap_threaded_create(session->folder, folder);
3336         if (r != MAILIMAP_NO_ERROR) {
3337                 imap_handle_error(SESSION(session), r);
3338                 
3339                 return r;
3340         }
3341
3342         return MAILIMAP_NO_ERROR;
3343 }
3344
3345 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
3346                             const gchar *new_folder)
3347 {
3348         int r;
3349
3350         r = imap_threaded_rename(session->folder, old_folder,
3351                                  new_folder);
3352         if (r != MAILIMAP_NO_ERROR) {
3353                 imap_handle_error(SESSION(session), r);
3354                 return r;
3355         }
3356
3357         return MAILIMAP_NO_ERROR;
3358 }
3359
3360 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
3361 {
3362         int r;
3363         
3364
3365         r = imap_threaded_delete(session->folder, folder);
3366         if (r != MAILIMAP_NO_ERROR) {
3367                 imap_handle_error(SESSION(session), r);
3368                 return r;
3369         }
3370
3371         return MAILIMAP_NO_ERROR;
3372 }
3373
3374 typedef struct _fetch_data {
3375         IMAPSession *session;
3376         guint32 uid;
3377         const gchar *filename;
3378         gboolean headers;
3379         gboolean body;
3380         gboolean done;
3381 } fetch_data;
3382
3383 static void *imap_cmd_fetch_thread(void *data)
3384 {
3385         fetch_data *stuff = (fetch_data *)data;
3386         IMAPSession *session = stuff->session;
3387         guint32 uid = stuff->uid;
3388         const gchar *filename = stuff->filename;
3389         int r;
3390         
3391         if (stuff->body) {
3392                 r = imap_threaded_fetch_content(session->folder,
3393                                                uid, 1, filename);
3394         }
3395         else {
3396                 r = imap_threaded_fetch_content(session->folder,
3397                                                 uid, 0, filename);
3398         }
3399         if (r != MAILIMAP_NO_ERROR) {
3400                 imap_handle_error(SESSION(session), r);
3401                 debug_print("fetch err %d\n", r);
3402                 return GINT_TO_POINTER(MAILIMAP_ERROR_BAD_STATE);
3403         }
3404         return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
3405 }
3406
3407 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
3408                                 const gchar *filename, gboolean headers,
3409                                 gboolean body)
3410 {
3411         fetch_data *data = g_new0(fetch_data, 1);
3412         int result = 0;
3413         data->done = FALSE;
3414         data->session = session;
3415         data->uid = uid;
3416         data->filename = filename;
3417         data->headers = headers;
3418         data->body = body;
3419
3420         if (prefs_common.work_offline && 
3421             !inc_offline_should_override(FALSE,
3422                 _("Claws Mail needs network access in order "
3423                   "to access the IMAP server."))) {
3424                 g_free(data);
3425                 return -1;
3426         }
3427         statusbar_print_all(_("Fetching message..."));
3428         result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
3429         statusbar_pop_all();
3430         g_free(data);
3431         return result;
3432 }
3433
3434
3435 static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
3436                             const gchar *file, IMAPFlags flags, 
3437                             guint32 *new_uid)
3438 {
3439         struct mailimap_flag_list * flag_list;
3440         int r;
3441         
3442         g_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
3443
3444         flag_list = imap_flag_to_lep(flags);
3445         lock_session(session);
3446         r = imap_threaded_append(session->folder, destfolder,
3447                          file, flag_list, (int *)new_uid);
3448         mailimap_flag_list_free(flag_list);
3449
3450         if (r != MAILIMAP_NO_ERROR) {
3451                 imap_handle_error(SESSION(session), r);
3452                 debug_print("append err %d\n", r);
3453                 return r;
3454         }
3455
3456         unlock_session(session);
3457
3458         return MAILIMAP_NO_ERROR;
3459 }
3460
3461 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
3462                           const gchar *destfolder, GRelation *uid_mapping,
3463                           struct mailimap_set **source, struct mailimap_set **dest)
3464 {
3465         int r;
3466         
3467         g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
3468         g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
3469         g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
3470
3471         r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
3472         if (r != MAILIMAP_NO_ERROR) {
3473                 imap_handle_error(SESSION(session), r);
3474                 return r;
3475         }
3476
3477         return MAILIMAP_NO_ERROR;
3478 }
3479
3480 static gint imap_cmd_store(IMAPSession *session, struct mailimap_set * set,
3481                            IMAPFlags flags, int do_add)
3482 {
3483         int r;
3484         struct mailimap_flag_list * flag_list;
3485         struct mailimap_store_att_flags * store_att_flags;
3486         
3487         flag_list = imap_flag_to_lep(flags);
3488         
3489         if (do_add)
3490                 store_att_flags =
3491                         mailimap_store_att_flags_new_add_flags_silent(flag_list);
3492         else
3493                 store_att_flags =
3494                         mailimap_store_att_flags_new_remove_flags_silent(flag_list);
3495         
3496         r = imap_threaded_store(session->folder, set, store_att_flags);
3497         mailimap_store_att_flags_free(store_att_flags);
3498         if (r != MAILIMAP_NO_ERROR) {
3499                 imap_handle_error(SESSION(session), r);
3500                 return r;
3501         }
3502         
3503         return MAILIMAP_NO_ERROR;
3504 }
3505
3506 static gint imap_cmd_expunge(IMAPSession *session)
3507 {
3508         int r;
3509         
3510         if (prefs_common.work_offline && 
3511             !inc_offline_should_override(FALSE,
3512                 _("Claws Mail needs network access in order "
3513                   "to access the IMAP server."))) {
3514                 return -1;
3515         }
3516
3517         r = imap_threaded_expunge(session->folder);
3518         if (r != MAILIMAP_NO_ERROR) {
3519                 imap_handle_error(SESSION(session), r);
3520                 return r;
3521         }
3522
3523         return MAILIMAP_NO_ERROR;
3524 }
3525
3526 static void imap_path_separator_subst(gchar *str, gchar separator)
3527 {
3528         gchar *p;
3529         gboolean in_escape = FALSE;
3530
3531         if (!separator || separator == '/') return;
3532
3533         for (p = str; *p != '\0'; p++) {
3534                 if (*p == '/' && !in_escape)
3535                         *p = separator;
3536                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
3537                         in_escape = TRUE;
3538                 else if (*p == '-' && in_escape)
3539                         in_escape = FALSE;
3540         }
3541 }
3542
3543 static gchar *imap_modified_utf7_to_utf8(const gchar *mutf7_str)
3544 {
3545         static iconv_t cd = (iconv_t)-1;
3546         static gboolean iconv_ok = TRUE;
3547         GString *norm_utf7;
3548         gchar *norm_utf7_p;
3549         size_t norm_utf7_len;
3550         const gchar *p;
3551         gchar *to_str, *to_p;
3552         size_t to_len;
3553         gboolean in_escape = FALSE;
3554
3555         if (!iconv_ok) return g_strdup(mutf7_str);
3556
3557         if (cd == (iconv_t)-1) {
3558                 cd = iconv_open(CS_INTERNAL, CS_UTF_7);
3559                 if (cd == (iconv_t)-1) {
3560                         g_warning("iconv cannot convert UTF-7 to %s\n",
3561                                   CS_INTERNAL);
3562                         iconv_ok = FALSE;
3563                         return g_strdup(mutf7_str);
3564                 }
3565         }
3566
3567         /* modified UTF-7 to normal UTF-7 conversion */
3568         norm_utf7 = g_string_new(NULL);
3569
3570         for (p = mutf7_str; *p != '\0'; p++) {
3571                 /* replace: '&'  -> '+',
3572                             "&-" -> '&',
3573                             escaped ','  -> '/' */
3574                 if (!in_escape && *p == '&') {
3575                         if (*(p + 1) != '-') {
3576                                 g_string_append_c(norm_utf7, '+');
3577                                 in_escape = TRUE;
3578                         } else {
3579                                 g_string_append_c(norm_utf7, '&');
3580                                 p++;
3581                         }
3582                 } else if (in_escape && *p == ',') {
3583                         g_string_append_c(norm_utf7, '/');
3584                 } else if (in_escape && *p == '-') {
3585                         g_string_append_c(norm_utf7, '-');
3586                         in_escape = FALSE;
3587                 } else {
3588                         g_string_append_c(norm_utf7, *p);
3589                 }
3590         }
3591
3592         norm_utf7_p = norm_utf7->str;
3593         norm_utf7_len = norm_utf7->len;
3594         to_len = strlen(mutf7_str) * 5;
3595         to_p = to_str = g_malloc(to_len + 1);
3596
3597         if (iconv(cd, (ICONV_CONST gchar **)&norm_utf7_p, &norm_utf7_len,
3598                   &to_p, &to_len) == -1) {
3599                 g_warning(_("iconv cannot convert UTF-7 to %s\n"),
3600                           conv_get_locale_charset_str());
3601                 g_string_free(norm_utf7, TRUE);
3602                 g_free(to_str);
3603                 return g_strdup(mutf7_str);
3604         }
3605
3606         /* second iconv() call for flushing */
3607         iconv(cd, NULL, NULL, &to_p, &to_len);
3608         g_string_free(norm_utf7, TRUE);
3609         *to_p = '\0';
3610
3611         return to_str;
3612 }
3613
3614 static gchar *imap_utf8_to_modified_utf7(const gchar *from)
3615 {
3616         static iconv_t cd = (iconv_t)-1;
3617         static gboolean iconv_ok = TRUE;
3618         gchar *norm_utf7, *norm_utf7_p;
3619         size_t from_len, norm_utf7_len;
3620         GString *to_str;
3621         gchar *from_tmp, *to, *p;
3622         gboolean in_escape = FALSE;
3623
3624         if (!iconv_ok) return g_strdup(from);
3625
3626         if (cd == (iconv_t)-1) {
3627                 cd = iconv_open(CS_UTF_7, CS_INTERNAL);
3628                 if (cd == (iconv_t)-1) {
3629                         g_warning(_("iconv cannot convert %s to UTF-7\n"),
3630                                   CS_INTERNAL);
3631                         iconv_ok = FALSE;
3632                         return g_strdup(from);
3633                 }
3634         }
3635
3636         /* UTF-8 to normal UTF-7 conversion */
3637         Xstrdup_a(from_tmp, from, return g_strdup(from));
3638         from_len = strlen(from);
3639         norm_utf7_len = from_len * 5;
3640         Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
3641         norm_utf7_p = norm_utf7;
3642
3643 #define IS_PRINT(ch) (isprint(ch) && IS_ASCII(ch))
3644
3645         while (from_len > 0) {
3646                 if (*from_tmp == '+') {
3647                         *norm_utf7_p++ = '+';
3648                         *norm_utf7_p++ = '-';
3649                         norm_utf7_len -= 2;
3650                         from_tmp++;
3651                         from_len--;
3652                 } else if (IS_PRINT(*(guchar *)from_tmp)) {
3653                         /* printable ascii char */
3654                         *norm_utf7_p = *from_tmp;
3655                         norm_utf7_p++;
3656                         norm_utf7_len--;
3657                         from_tmp++;
3658                         from_len--;
3659                 } else {
3660                         size_t conv_len = 0;
3661
3662                         /* unprintable char: convert to UTF-7 */
3663                         p = from_tmp;
3664                         while (!IS_PRINT(*(guchar *)p) && conv_len < from_len) {
3665                                 conv_len += g_utf8_skip[*(guchar *)p];
3666                                 p += g_utf8_skip[*(guchar *)p];
3667                         }
3668
3669                         from_len -= conv_len;
3670                         if (iconv(cd, (ICONV_CONST gchar **)&from_tmp,
3671                                   &conv_len,
3672                                   &norm_utf7_p, &norm_utf7_len) == -1) {
3673                                 g_warning(_("iconv cannot convert UTF-8 to UTF-7\n"));
3674                                 return g_strdup(from);
3675                         }
3676
3677                         /* second iconv() call for flushing */
3678                         iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
3679                 }
3680         }
3681
3682 #undef IS_PRINT
3683
3684         *norm_utf7_p = '\0';
3685         to_str = g_string_new(NULL);
3686         for (p = norm_utf7; p < norm_utf7_p; p++) {
3687                 /* replace: '&' -> "&-",
3688                             '+' -> '&',
3689                             "+-" -> '+',
3690                             BASE64 '/' -> ',' */
3691                 if (!in_escape && *p == '&') {
3692                         g_string_append(to_str, "&-");
3693                 } else if (!in_escape && *p == '+') {
3694                         if (*(p + 1) == '-') {
3695                                 g_string_append_c(to_str, '+');
3696                                 p++;
3697                         } else {
3698                                 g_string_append_c(to_str, '&');
3699                                 in_escape = TRUE;
3700                         }
3701                 } else if (in_escape && *p == '/') {
3702                         g_string_append_c(to_str, ',');
3703                 } else if (in_escape && *p == '-') {
3704                         g_string_append_c(to_str, '-');
3705                         in_escape = FALSE;
3706                 } else {
3707                         g_string_append_c(to_str, *p);
3708                 }
3709         }
3710
3711         if (in_escape) {
3712                 in_escape = FALSE;
3713                 g_string_append_c(to_str, '-');
3714         }
3715
3716         to = to_str->str;
3717         g_string_free(to_str, FALSE);
3718
3719         return to;
3720 }
3721
3722 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
3723 {
3724         FolderItem *item = node->data;
3725         gchar **paths = data;
3726         const gchar *oldpath = paths[0];
3727         const gchar *newpath = paths[1];
3728         gchar *real_oldpath, *real_newpath;
3729         gchar *base;
3730         gchar *new_itempath;
3731         gint oldpathlen;
3732         IMAPSession *session = imap_session_get(item->folder);
3733
3734         oldpathlen = strlen(oldpath);
3735         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3736                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3737                 return TRUE;
3738         }
3739
3740         base = item->path + oldpathlen;
3741         while (*base == G_DIR_SEPARATOR) base++;
3742         if (*base == '\0')
3743                 new_itempath = g_strdup(newpath);
3744         else
3745                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3746                                            NULL);
3747
3748         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path);
3749         g_free(item->path);
3750         item->path = new_itempath;
3751         
3752         real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path);
3753         
3754         imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
3755         imap_threaded_subscribe(item->folder, real_newpath, TRUE);
3756
3757         g_free(real_oldpath);
3758         g_free(real_newpath);
3759         return FALSE;
3760 }
3761
3762 static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
3763 {
3764         GSList *uidlist, *elem;
3765         int r = -1;
3766         clist * lep_uidlist;
3767         gint ok, nummsgs = 0, lastuid_old;
3768
3769         if (session == NULL) {
3770                 return -1;
3771         }
3772
3773         ok = imap_select(session, IMAP_FOLDER(folder), item->item.path,
3774                          NULL, NULL, NULL, NULL, TRUE);
3775         if (ok != MAILIMAP_NO_ERROR) {
3776                 return -1;
3777         }
3778
3779         g_slist_free(item->uid_list);
3780         item->uid_list = NULL;
3781
3782         uidlist = NULL;
3783         
3784         if (folder->account && folder->account->low_bandwidth) {
3785                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE, NULL,
3786                                  &lep_uidlist);
3787         }
3788         
3789         if (r == MAILIMAP_NO_ERROR) {
3790                 GSList * fetchuid_list =
3791                         imap_uid_list_from_lep(lep_uidlist);
3792                 mailimap_search_result_free(lep_uidlist);
3793                 
3794                 uidlist = g_slist_concat(fetchuid_list, uidlist);
3795         } else {
3796                 carray * lep_uidtab;
3797                 if (r != -1) /* inited */
3798                         imap_handle_error(SESSION(session), r);
3799                 r = imap_threaded_fetch_uid(folder, 1,
3800                                     &lep_uidtab);
3801                 if (r == MAILIMAP_NO_ERROR) {
3802                         GSList * fetchuid_list =
3803                                 imap_uid_list_from_lep_tab(lep_uidtab);
3804                         imap_fetch_uid_list_free(lep_uidtab);
3805                         uidlist = g_slist_concat(fetchuid_list, uidlist);
3806                 }
3807         }
3808         
3809         if (r != MAILIMAP_NO_ERROR) {
3810                 imap_handle_error(SESSION(session), r);
3811                 return -1;
3812         }
3813
3814         lastuid_old = item->lastuid;
3815
3816         for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
3817                 guint msgnum;
3818
3819                 msgnum = GPOINTER_TO_INT(elem->data);
3820
3821                 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
3822                 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
3823                 nummsgs++;
3824         }
3825         g_slist_free(uidlist);
3826
3827         unlock_session(session); /* locked from imap_get_num_list */
3828
3829         return nummsgs;
3830
3831 }
3832
3833 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)
3834 {
3835         IMAPFolderItem *item = (IMAPFolderItem *)_item;
3836         IMAPSession *session;
3837         gint nummsgs;
3838         GSList *uidlist = NULL;
3839         gchar *dir;
3840         gboolean selected_folder;
3841         gint known_list_len = 0;
3842         debug_print("get_num_list\n");
3843         
3844         g_return_val_if_fail(folder != NULL, -1);
3845         g_return_val_if_fail(item != NULL, -1);
3846         g_return_val_if_fail(item->item.path != NULL, -1);
3847         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
3848         g_return_val_if_fail(folder->account != NULL, -1);
3849
3850         known_list_len = g_slist_length(item->uid_list);
3851         if (!item->should_update) {
3852                 debug_print("get_num_list: nothing to update\n");
3853                 *old_uids_valid = TRUE;
3854                 if (known_list_len == item->item.total_msgs
3855                  && known_list_len > 0) {
3856                         *msgnum_list = g_slist_copy(item->uid_list);
3857                         return known_list_len;
3858                 } else {
3859                         debug_print("don't know the list length...\n");
3860                 }
3861         }
3862
3863         if (prefs_common.work_offline && 
3864             !inc_offline_should_override(FALSE,
3865                 _("Claws Mail needs network access in order "
3866                   "to access the IMAP server."))) {
3867                 return -1;
3868         }
3869         
3870         debug_print("getting session...\n");
3871         session = imap_session_get(folder);
3872         g_return_val_if_fail(session != NULL, -1);
3873
3874         lock_session(session); /* unlocked by get_list_of_uids */
3875         if (FOLDER_ITEM(item)->path) 
3876                 statusbar_print_all(_("Scanning folder %s%c%s ..."),
3877                                       FOLDER_ITEM(item)->folder->name, 
3878                                       G_DIR_SEPARATOR,
3879                                       FOLDER_ITEM(item)->path);
3880         else
3881                 statusbar_print_all(_("Scanning folder %s ..."),
3882                                       FOLDER_ITEM(item)->folder->name);
3883
3884         selected_folder = (session->mbox != NULL) &&
3885                           (!strcmp(session->mbox, item->item.path));
3886         
3887         if (item->should_trash_cache) {
3888                 *old_uids_valid = FALSE;
3889                 debug_print("get_num_list: trashing num list\n");
3890                 debug_print("Freeing imap uid cache\n");
3891                 item->lastuid = 0;
3892                 g_slist_free(item->uid_list);
3893                 item->uid_list = NULL;
3894
3895                 imap_delete_all_cached_messages((FolderItem *)item);
3896         } else {
3897                 debug_print("get_num_list: updating num list\n");
3898                 *old_uids_valid = TRUE;
3899         }
3900
3901         nummsgs = get_list_of_uids(session, folder, item, &uidlist);
3902         /* session could be broken now, in case of fatal error */
3903
3904         debug_print("get_num_list: got %d msgs\n", nummsgs);
3905
3906         if (nummsgs < 0) {
3907                 statusbar_pop_all();
3908                 return -1;
3909         }
3910
3911         *msgnum_list = uidlist;
3912
3913         dir = folder_item_get_path((FolderItem *)item);
3914         debug_print("removing old messages from %s\n", dir);
3915         remove_numbered_files_not_in_list(dir, *msgnum_list);
3916         g_free(dir);
3917         
3918         debug_print("get_num_list - ok - %i\n", nummsgs);
3919         statusbar_pop_all();
3920         item->should_trash_cache = FALSE;
3921         item->should_update = FALSE;
3922         return nummsgs;
3923 }
3924
3925 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item)
3926 {
3927         MsgInfo *msginfo;
3928         MsgFlags flags;
3929
3930         flags.perm_flags = MSG_NEW|MSG_UNREAD;
3931         flags.tmp_flags = 0;
3932
3933         g_return_val_if_fail(item != NULL, NULL);
3934         g_return_val_if_fail(file != NULL, NULL);
3935
3936         if (folder_has_parent_of_type(item, F_QUEUE)) {
3937                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
3938         } else if (folder_has_parent_of_type(item, F_DRAFT)) {
3939                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
3940         }
3941
3942         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
3943         if (!msginfo) return NULL;
3944         
3945         msginfo->plaintext_file = g_strdup(file);
3946         msginfo->folder = item;
3947
3948         return msginfo;
3949 }
3950
3951 GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
3952                           GSList *msgnum_list)
3953 {
3954         IMAPSession *session;
3955         MsgInfoList *ret = NULL;
3956         gint ok;
3957         
3958         debug_print("get_msginfos\n");
3959         
3960         g_return_val_if_fail(folder != NULL, NULL);
3961         g_return_val_if_fail(item != NULL, NULL);
3962         g_return_val_if_fail(msgnum_list != NULL, NULL);
3963
3964         debug_print("getting session...\n");
3965         session = imap_session_get(folder);
3966         g_return_val_if_fail(session != NULL, NULL);
3967
3968         lock_session(session); /* unlocked later in the function */
3969
3970         debug_print("IMAP getting msginfos\n");
3971         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
3972                          NULL, NULL, NULL, NULL, FALSE);
3973         if (ok != MAILIMAP_NO_ERROR) {
3974                 return NULL;
3975         }
3976         if (!(folder_has_parent_of_type(item, F_DRAFT) || 
3977               folder_has_parent_of_type(item, F_QUEUE))) {
3978                 ret = g_slist_concat(ret,
3979                         imap_get_uncached_messages(session, item,
3980                                                    msgnum_list, &ok));
3981                 if (ok != MAILIMAP_NO_ERROR)
3982                         return NULL;
3983                 unlock_session(session);
3984         } else {
3985                 MsgNumberList *sorted_list, *elem, *llast = NULL;
3986                 gint startnum, lastnum;
3987         
3988                 unlock_session(session);
3989
3990                 sorted_list = g_slist_sort(g_slist_copy(msgnum_list), g_int_compare);
3991
3992                 startnum = lastnum = GPOINTER_TO_INT(sorted_list->data);
3993
3994                 llast = g_slist_last(ret);
3995                 for (elem = sorted_list;; elem = g_slist_next(elem)) {
3996                         guint num = 0;
3997
3998                         if (elem)
3999                                 num = GPOINTER_TO_INT(elem->data);
4000
4001                         if (num > lastnum + 1 || elem == NULL) {
4002                                 int i;
4003                                 for (i = startnum; i <= lastnum; ++i) {
4004                                         gchar *file;
4005                                         file = imap_fetch_msg(folder, item, i);
4006                                         if (file != NULL) {
4007                                                 MsgInfo *msginfo = imap_parse_msg(file, item);
4008                                                 if (msginfo != NULL) {
4009                                                         msginfo->msgnum = i;
4010                                                         if (llast == NULL)
4011                                                                 llast = ret = g_slist_append(ret, msginfo);
4012                                                         else {
4013                                                                 llast = g_slist_append(llast, msginfo);
4014                                                                 llast = llast->next;
4015                                                         }
4016                                                 }
4017                                                 g_free(file);
4018                                         }
4019                                 }
4020
4021                                 if (elem == NULL)
4022                                         break;
4023
4024                                 startnum = num;
4025                         }
4026                         lastnum = num;
4027                 }
4028
4029                 g_slist_free(sorted_list);
4030         }
4031         return ret;
4032 }
4033
4034 MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
4035 {
4036         MsgInfo *msginfo = NULL;
4037         MsgInfoList *msginfolist;
4038         MsgNumberList numlist;
4039
4040         numlist.next = NULL;
4041         numlist.data = GINT_TO_POINTER(uid);
4042
4043         msginfolist = imap_get_msginfos(folder, item, &numlist);
4044         if (msginfolist != NULL) {
4045                 msginfo = msginfolist->data;
4046                 g_slist_free(msginfolist);
4047         }
4048
4049         return msginfo;
4050 }
4051
4052 gboolean imap_scan_required(Folder *folder, FolderItem *_item)
4053 {
4054         IMAPSession *session;
4055         IMAPFolderItem *item = (IMAPFolderItem *)_item;
4056         gint ok, exists = 0, unseen = 0;
4057         guint32 uid_next = 0, uid_val = 0;
4058         gboolean selected_folder;
4059         
4060         g_return_val_if_fail(folder != NULL, FALSE);
4061         g_return_val_if_fail(item != NULL, FALSE);
4062         g_return_val_if_fail(item->item.folder != NULL, FALSE);
4063         g_return_val_if_fail(FOLDER_CLASS(item->item.folder) == &imap_class, FALSE);
4064
4065         if (item->item.path == NULL)
4066                 return FALSE;
4067
4068         if (item->should_update) {
4069                 debug_print("scan already required\n");
4070                 return TRUE;
4071         }
4072         debug_print("getting session...\n");
4073         session = imap_session_get(folder);
4074         
4075         g_return_val_if_fail(session != NULL, FALSE);
4076         lock_session(session); /* unlocked later in the function */
4077
4078         selected_folder = (session->mbox != NULL) &&
4079                           (!strcmp(session->mbox, item->item.path));
4080         if (selected_folder) {
4081                 if (!session->folder_content_changed) {
4082                         ok = imap_cmd_noop(session);
4083                         if (ok != MAILIMAP_NO_ERROR) {
4084                                 debug_print("disconnected!\n");
4085                                 if (!is_fatal(ok))
4086                                         session = imap_reconnect_if_possible(folder, session);
4087                                 else
4088                                         session = imap_session_get(folder);
4089                                 if (session == NULL)
4090                                         return FALSE;
4091                         }
4092
4093                         if (session->folder_content_changed) {
4094                                 debug_print("CHANGED (self-noop)! scan_required\n");
4095                                 item->should_update = TRUE;
4096                                 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4097                                         item->item.mtime = session->uid_validity;
4098                                         item->should_trash_cache = TRUE;
4099                                 }
4100                                 unlock_session(session);
4101                                 return TRUE;
4102                         }
4103                 } else {
4104                         debug_print("CHANGED (previous noop)! scan_required\n");
4105                         item->should_update = TRUE;
4106                         if (session->uid_validity && session->uid_validity != item->item.mtime) {
4107                                 item->item.mtime = session->uid_validity;
4108                                 item->should_trash_cache = TRUE;
4109                         }
4110                         unlock_session(session);
4111                         return TRUE;
4112                 }
4113         } else {
4114                 ok = imap_status(session, IMAP_FOLDER(folder), item->item.path, IMAP_FOLDER_ITEM(item),
4115                                  &exists, &uid_next, &uid_val, &unseen, FALSE);
4116                 if (ok != MAILIMAP_NO_ERROR) {
4117                         return FALSE;
4118                 }
4119                 
4120                 debug_print("exists %d, item->item.total_msgs %d\n", 
4121                         exists, item->item.total_msgs);
4122                 if (exists != item->item.total_msgs
4123                     || unseen != item->item.unread_msgs 
4124                     || uid_next != item->uid_next
4125                     || uid_val != item->item.mtime) {
4126                         debug_print("CHANGED (status)! scan_required\n");
4127                         item->last_change = time(NULL);
4128                         item->should_update = TRUE;
4129                         item->uid_next = uid_next;
4130                         if (uid_val != item->item.mtime) {
4131                                 item->item.mtime = uid_val;
4132                                 item->should_trash_cache = TRUE;
4133                         }
4134                         unlock_session(session);
4135                         return TRUE;
4136                 }
4137         }
4138         unlock_session(session);
4139
4140         item->should_update = FALSE;
4141         return FALSE;
4142 }
4143
4144 void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
4145 {
4146         IMAPSession *session;
4147         IMAPFlags flags_set = 0, flags_unset = 0;
4148         gint ok = MAILIMAP_NO_ERROR;
4149         MsgNumberList numlist;
4150         hashtable_data *ht_data = NULL;
4151
4152         g_return_if_fail(folder != NULL);
4153         g_return_if_fail(folder->klass == &imap_class);
4154         g_return_if_fail(item != NULL);
4155         g_return_if_fail(item->folder == folder);
4156         g_return_if_fail(msginfo != NULL);
4157         g_return_if_fail(msginfo->folder == item);
4158
4159         if (!MSG_IS_MARKED(msginfo->flags) &&  (newflags & MSG_MARKED))
4160                 flags_set |= IMAP_FLAG_FLAGGED;
4161         if ( MSG_IS_MARKED(msginfo->flags) && !(newflags & MSG_MARKED))
4162                 flags_unset |= IMAP_FLAG_FLAGGED;
4163
4164         if (!MSG_IS_UNREAD(msginfo->flags) &&  (newflags & MSG_UNREAD))
4165                 flags_unset |= IMAP_FLAG_SEEN;
4166         if ( MSG_IS_UNREAD(msginfo->flags) && !(newflags & MSG_UNREAD))
4167                 flags_set |= IMAP_FLAG_SEEN;
4168
4169         if (!MSG_IS_REPLIED(msginfo->flags) &&  (newflags & MSG_REPLIED))
4170                 flags_set |= IMAP_FLAG_ANSWERED;
4171         if ( MSG_IS_REPLIED(msginfo->flags) && !(newflags & MSG_REPLIED))
4172                 flags_unset |= IMAP_FLAG_ANSWERED;
4173
4174         if (!MSG_IS_DELETED(msginfo->flags) &&  (newflags & MSG_DELETED))
4175                 flags_set |= IMAP_FLAG_DELETED;
4176         if ( MSG_IS_DELETED(msginfo->flags) && !(newflags & MSG_DELETED))
4177                 flags_unset |= IMAP_FLAG_DELETED;
4178
4179         if (!flags_set && !flags_unset) {
4180                 /* the changed flags were not translatable to IMAP-speak.
4181                  * like MSG_POSTFILTERED, so just apply. */
4182                 msginfo->flags.perm_flags = newflags;
4183                 return;
4184         }
4185
4186         debug_print("getting session...\n");
4187         session = imap_session_get(folder);
4188         if (!session) {
4189                 return;
4190         }
4191
4192         if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
4193             NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
4194                 return;
4195         }
4196         numlist.next = NULL;
4197         numlist.data = GINT_TO_POINTER(msginfo->msgnum);
4198
4199         if (IMAP_FOLDER_ITEM(item)->batching) {
4200                 /* instead of performing an UID STORE command for each message change,
4201                  * as a lot of them can change "together", we just fill in hashtables
4202                  * and defer the treatment so that we're able to send only one
4203                  * command.
4204                  */
4205                 debug_print("IMAP batch mode on, deferring flags change\n");
4206                 if (flags_set) {
4207                         ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_set_table, 
4208                                 GINT_TO_POINTER(flags_set));
4209                         if (ht_data == NULL) {
4210                                 ht_data = g_new0(hashtable_data, 1);
4211                                 ht_data->item = IMAP_FOLDER_ITEM(item);
4212                                 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_set_table, 
4213                                         GINT_TO_POINTER(flags_set), ht_data);
4214                         }
4215                         ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
4216                 } 
4217                 if (flags_unset) {
4218                         ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_unset_table, 
4219                                 GINT_TO_POINTER(flags_unset));
4220                         if (ht_data == NULL) {
4221                                 ht_data = g_new0(hashtable_data, 1);
4222                                 ht_data->item = IMAP_FOLDER_ITEM(item);
4223                                 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_unset_table, 
4224                                         GINT_TO_POINTER(flags_unset), ht_data);
4225                         }
4226                         ht_data->msglist = g_slist_prepend(ht_data->msglist, 
4227                                         GINT_TO_POINTER(msginfo->msgnum));              
4228                 }
4229         } else {
4230                 debug_print("IMAP changing flags\n");
4231                 if (flags_set) {
4232                         ok = imap_set_message_flags(session, &numlist, flags_set, TRUE);
4233                         if (ok != MAILIMAP_NO_ERROR) {
4234                                 return;
4235                         }
4236                 }
4237
4238                 if (flags_unset) {
4239                         ok = imap_set_message_flags(session, &numlist, flags_unset, FALSE);
4240                         if (ok != MAILIMAP_NO_ERROR) {
4241                                 return;
4242                         }
4243                 }
4244         }
4245         msginfo->flags.perm_flags = newflags;
4246         return;
4247 }
4248
4249 static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
4250 {
4251         gint ok;
4252         IMAPSession *session;
4253         gchar *dir;
4254         MsgNumberList numlist;
4255         
4256         g_return_val_if_fail(folder != NULL, -1);
4257         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
4258         g_return_val_if_fail(item != NULL, -1);
4259
4260         debug_print("getting session...\n");
4261         session = imap_session_get(folder);
4262         if (!session) return -1;
4263
4264         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
4265                          NULL, NULL, NULL, NULL, FALSE);
4266         if (ok != MAILIMAP_NO_ERROR) {
4267                 return ok;
4268         }
4269         numlist.next = NULL;
4270         numlist.data = GINT_TO_POINTER(uid);
4271         
4272         ok = imap_set_message_flags
4273                 (session, &numlist, IMAP_FLAG_DELETED, TRUE);
4274         if (ok != MAILIMAP_NO_ERROR) {
4275                 log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
4276                 return ok;
4277         }
4278
4279         if (!session->uidplus) {
4280                 ok = imap_cmd_expunge(session);
4281         } else {
4282                 gchar *uidstr;
4283
4284                 uidstr = g_strdup_printf("%u", uid);
4285                 ok = imap_cmd_expunge(session);
4286                 g_free(uidstr);
4287         }
4288         if (ok != MAILIMAP_NO_ERROR) {
4289                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
4290                 return ok;
4291         }
4292
4293         IMAP_FOLDER_ITEM(item)->uid_list = g_slist_remove(
4294             IMAP_FOLDER_ITEM(item)->uid_list, numlist.data);
4295         dir = folder_item_get_path(item);
4296         if (is_dir_exist(dir))
4297                 remove_numbered_files(dir, uid, uid);
4298         g_free(dir);
4299         return MAILIMAP_NO_ERROR;
4300 }
4301
4302 static gint compare_msginfo(gconstpointer a, gconstpointer b)
4303 {
4304         return ((MsgInfo *)a)->msgnum - ((MsgInfo *)b)->msgnum;
4305 }
4306
4307 static guint gslist_find_next_num(MsgNumberList **list, guint num)
4308 {
4309         GSList *elem;
4310
4311         g_return_val_if_fail(list != NULL, -1);
4312
4313         for (elem = *list; elem != NULL; elem = g_slist_next(elem))
4314                 if (GPOINTER_TO_INT(elem->data) >= num)
4315                         break;
4316         *list = elem;
4317         return elem != NULL ? GPOINTER_TO_INT(elem->data) : (gint)-1;
4318 }
4319
4320 /*
4321  * NEW and DELETED flags are not syncronized
4322  * - The NEW/RECENT flags in IMAP folders can not really be directly
4323  *   modified by Sylpheed
4324  * - The DELETE/DELETED flag in IMAP and Sylpheed don't have the same
4325  *   meaning, in IMAP it always removes the messages from the FolderItem
4326  *   in Sylpheed it can mean to move the message to trash
4327  */
4328
4329 typedef struct _get_flags_data {
4330         Folder *folder;
4331         FolderItem *item;
4332         MsgInfoList *msginfo_list;
4333         GRelation *msgflags;
4334         gboolean full_search;
4335         gboolean done;
4336 } get_flags_data;
4337
4338 static /*gint*/ void *imap_get_flags_thread(void *data)
4339 {
4340         get_flags_data *stuff = (get_flags_data *)data;
4341         Folder *folder = stuff->folder;
4342         FolderItem *fitem = (FolderItem *) stuff->item;
4343         MsgInfoList *msginfo_list = stuff->msginfo_list;
4344         GRelation *msgflags = stuff->msgflags;
4345         GSList *elem;
4346         carray * lep_uidtab;
4347         IMAPSession *session;
4348         gint ok;
4349         int r = MAILIMAP_NO_ERROR;
4350         GHashTable *flags_hash = NULL;
4351         gboolean full_search = stuff->full_search;
4352         GSList *sorted_list = NULL;
4353         GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL;
4354         GSList *p_unseen, *p_answered, *p_flagged, *p_deleted;
4355         GSList *seq_list, *cur;
4356         gboolean reverse_seen = FALSE;
4357         gboolean selected_folder;
4358         gint exists_cnt, unseen_cnt;
4359         
4360         session = imap_session_get(folder);
4361
4362         if (session == NULL) {
4363                 stuff->done = TRUE;
4364                 return GINT_TO_POINTER(-1);
4365         }
4366         selected_folder = (session->mbox != NULL) &&
4367                           (!strcmp(session->mbox, fitem->path));
4368
4369         lock_session(session);
4370         if (!selected_folder) {
4371                 ok = imap_select(session, IMAP_FOLDER(folder), fitem->path,
4372                         &exists_cnt, NULL, &unseen_cnt, NULL, TRUE);
4373                 if (ok != MAILIMAP_NO_ERROR) {
4374                         stuff->done = TRUE;
4375                         return GINT_TO_POINTER(-1);
4376                 }
4377
4378                 if (unseen_cnt > exists_cnt / 2)
4379                         reverse_seen = TRUE;
4380         } 
4381         else {
4382                 if (fitem->unread_msgs > fitem->total_msgs / 2)
4383                         reverse_seen = TRUE;
4384         }
4385
4386         sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
4387         if (!full_search) {
4388                 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msginfo_list);
4389         } else {
4390                 struct mailimap_set * set;
4391                 set = mailimap_set_new_interval(1, 0);
4392                 seq_list = g_slist_append(NULL, set);
4393         }
4394
4395         if (folder->account && folder->account->low_bandwidth) {
4396                 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
4397                         struct mailimap_set * imapset;
4398                         clist * lep_uidlist;
4399                         int r;
4400
4401                         imapset = cur->data;
4402                         if (reverse_seen) {
4403                                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN,
4404                                                          full_search ? NULL:imapset, &lep_uidlist);
4405                         }
4406                         else {
4407                                 r = imap_threaded_search(folder,
4408                                                          IMAP_SEARCH_TYPE_UNSEEN,
4409                                                          full_search ? NULL:imapset, &lep_uidlist);
4410                         }
4411                         if (r == MAILIMAP_NO_ERROR) {
4412                                 GSList * uidlist;
4413
4414                                 uidlist = imap_uid_list_from_lep(lep_uidlist);
4415                                 mailimap_search_result_free(lep_uidlist);
4416
4417                                 unseen = g_slist_concat(unseen, uidlist);
4418                         } else {
4419                                 imap_handle_error(SESSION(session), r);
4420                                 goto bail;
4421                         }
4422
4423                         r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED,
4424                                                  full_search ? NULL:imapset, &lep_uidlist);
4425                         if (r == MAILIMAP_NO_ERROR) {
4426                                 GSList * uidlist;
4427
4428                                 uidlist = imap_uid_list_from_lep(lep_uidlist);
4429                                 mailimap_search_result_free(lep_uidlist);
4430
4431                                 flagged = g_slist_concat(flagged, uidlist);
4432                         } else {
4433                                 imap_handle_error(SESSION(session), r);
4434                                 goto bail;
4435                         }
4436
4437                         if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
4438                                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED,
4439                                                          full_search ? NULL:imapset, &lep_uidlist);
4440                                 if (r == MAILIMAP_NO_ERROR) {
4441                                         GSList * uidlist;
4442
4443                                         uidlist = imap_uid_list_from_lep(lep_uidlist);
4444                                         mailimap_search_result_free(lep_uidlist);
4445
4446                                         answered = g_slist_concat(answered, uidlist);
4447                                 } else {
4448                                         imap_handle_error(SESSION(session), r);
4449                                         goto bail;
4450                                 }
4451
4452                                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED,
4453                                                          full_search ? NULL:imapset, &lep_uidlist);
4454                                 if (r == MAILIMAP_NO_ERROR) {
4455                                         GSList * uidlist;
4456
4457                                         uidlist = imap_uid_list_from_lep(lep_uidlist);
4458                                         mailimap_search_result_free(lep_uidlist);
4459
4460                                         deleted = g_slist_concat(deleted, uidlist);
4461                                 } else {
4462                                         imap_handle_error(SESSION(session), r);
4463                                         goto bail;
4464                                 }
4465                         }
4466                 }
4467                 p_unseen = unseen;
4468                 p_answered = answered;
4469                 p_flagged = flagged;
4470                 p_deleted = deleted;
4471
4472         } else {
4473                 r = imap_threaded_fetch_uid_flags(folder, 1, &lep_uidtab);
4474                 if (r == MAILIMAP_NO_ERROR) {
4475                         flags_hash = g_hash_table_new_full(g_int_hash, g_int_equal, free, NULL);
4476                         imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash);
4477                         imap_fetch_uid_flags_list_free(lep_uidtab);
4478                 } else {
4479                         imap_handle_error(SESSION(session), r);
4480                         goto bail;
4481                 }
4482         }
4483
4484 bail:
4485         if (r == MAILIMAP_NO_ERROR)
4486                 unlock_session(session);
4487         
4488         for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
4489                 MsgInfo *msginfo;
4490                 MsgPermFlags flags, oldflags;
4491                 gboolean wasnew;
4492
4493                 msginfo = (MsgInfo *) elem->data;
4494                 flags = msginfo->flags.perm_flags;
4495                 wasnew = (flags & MSG_NEW);
4496                 oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_MARKED|MSG_DELETED);
4497
4498                 if (folder->account && folder->account->low_bandwidth) {
4499                         if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
4500                                 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_MARKED);
4501                         } else {
4502                                 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW | MSG_MARKED));
4503                         }
4504                         if (reverse_seen)
4505                                 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
4506                         if (gslist_find_next_num(&p_unseen, msginfo->msgnum) == msginfo->msgnum) {
4507                                 if (!reverse_seen) {
4508                                         flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
4509                                 } else {
4510                                         flags &= ~(MSG_UNREAD | MSG_NEW);
4511                                 }
4512                         }
4513
4514                         if (gslist_find_next_num(&p_flagged, msginfo->msgnum) == msginfo->msgnum)
4515                                 flags |= MSG_MARKED;
4516                         else
4517                                 flags &= ~MSG_MARKED;
4518
4519                         if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
4520                                 if (gslist_find_next_num(&p_answered, msginfo->msgnum) == msginfo->msgnum)
4521                                         flags |= MSG_REPLIED;
4522                                 else
4523                                         flags &= ~MSG_REPLIED;
4524                                 if (gslist_find_next_num(&p_deleted, msginfo->msgnum) == msginfo->msgnum)
4525                                         flags |= MSG_DELETED;
4526                                 else
4527                                         flags &= ~MSG_DELETED;
4528                         }
4529                 } else {
4530                         if (flags_hash != NULL) {
4531                                 gint * puid;
4532
4533                                 puid = malloc(sizeof(* puid));
4534                                 * puid = msginfo->msgnum;
4535
4536                                 flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash, puid));
4537                                 free(puid);
4538                         }
4539
4540                         if ((flags & MSG_UNREAD) == 0)
4541                                 flags &= ~MSG_NEW;
4542                         else if (wasnew)
4543                                 flags |= MSG_NEW;
4544                         flags |= oldflags;
4545                 }
4546
4547                 g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
4548         }
4549         
4550         if (flags_hash)
4551                 g_hash_table_destroy(flags_hash);
4552
4553         imap_lep_set_free(seq_list);
4554         g_slist_free(flagged);
4555         g_slist_free(deleted);
4556         g_slist_free(answered);
4557         g_slist_free(unseen);
4558         g_slist_free(sorted_list);
4559
4560         stuff->done = TRUE;
4561         return GINT_TO_POINTER(0);
4562 }
4563
4564 static gint imap_get_flags(Folder *folder, FolderItem *item,
4565                            MsgInfoList *msginfo_list, GRelation *msgflags)
4566 {
4567         gint result;
4568         get_flags_data *data = g_new0(get_flags_data, 1);
4569         data->done = FALSE;
4570         data->folder = folder;
4571         data->item = item;
4572         data->msginfo_list = msginfo_list;
4573         data->msgflags = msgflags;
4574         data->full_search = FALSE;
4575
4576         GSList *tmp = NULL, *cur;
4577         
4578         if (prefs_common.work_offline && 
4579             !inc_offline_should_override(FALSE,
4580                 _("Claws Mail needs network access in order "
4581                   "to access the IMAP server."))) {
4582                 g_free(data);
4583                 return -1;
4584         }
4585
4586         tmp = folder_item_get_msg_list(item);
4587
4588         if (g_slist_length(tmp) <= g_slist_length(msginfo_list))
4589                 data->full_search = TRUE;
4590         
4591         for (cur = tmp; cur; cur = cur->next)
4592                 procmsg_msginfo_free((MsgInfo *)cur->data);
4593         
4594         g_slist_free(tmp);
4595
4596         result = GPOINTER_TO_INT(imap_get_flags_thread(data));
4597         
4598         g_free(data);
4599         return result;
4600
4601 }
4602
4603 static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
4604 {
4605         gboolean flags_set = GPOINTER_TO_INT(user_data);
4606         gint flags_value = GPOINTER_TO_INT(key);
4607         hashtable_data *data = (hashtable_data *)value;
4608         IMAPFolderItem *_item = data->item;
4609         FolderItem *item = (FolderItem *)_item;
4610         gint ok = MAILIMAP_ERROR_BAD_STATE;
4611         IMAPSession *session = NULL;
4612         
4613         debug_print("getting session...\n");
4614         session = imap_session_get(item->folder);
4615
4616         data->msglist = g_slist_reverse(data->msglist);
4617         
4618         debug_print("IMAP %ssetting flags to %d for %d messages\n",
4619                 flags_set?"":"un",
4620                 flags_value,
4621                 g_slist_length(data->msglist));
4622         
4623         lock_session(session);
4624         if (session) {
4625                 ok = imap_select(session, IMAP_FOLDER(item->folder), item->path,
4626                          NULL, NULL, NULL, NULL, FALSE);
4627         }
4628         if (ok == MAILIMAP_NO_ERROR) {
4629                 ok = imap_set_message_flags(session, data->msglist, flags_value, flags_set);
4630         } else {
4631                 g_warning("can't select mailbox %s\n", item->path);
4632         }
4633
4634         if (!is_fatal(ok))
4635                 unlock_session(session);
4636
4637         g_slist_free(data->msglist);    
4638         g_free(data);
4639         return TRUE;
4640 }
4641
4642 static void process_hashtable(IMAPFolderItem *item)
4643 {
4644         if (item->flags_set_table) {
4645                 g_hash_table_foreach_remove(item->flags_set_table, process_flags, GINT_TO_POINTER(TRUE));
4646                 g_hash_table_destroy(item->flags_set_table);
4647                 item->flags_set_table = NULL;
4648         }
4649         if (item->flags_unset_table) {
4650                 g_hash_table_foreach_remove(item->flags_unset_table, process_flags, GINT_TO_POINTER(FALSE));
4651                 g_hash_table_destroy(item->flags_unset_table);
4652                 item->flags_unset_table = NULL;
4653         }
4654         
4655 }
4656
4657 static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
4658 {
4659         IMAPFolderItem *item = (IMAPFolderItem *)_item;
4660         IMAPSession *session;
4661
4662         g_return_if_fail(item != NULL);
4663         
4664         if (item->batching == batch)
4665                 return;
4666         
4667         if (batch) {
4668                 item->batching = TRUE;
4669                 debug_print("IMAP switching to batch mode\n");
4670                 if (!item->flags_set_table) {
4671                         item->flags_set_table = g_hash_table_new(NULL, g_direct_equal);
4672                 }
4673                 if (!item->flags_unset_table) {
4674                         item->flags_unset_table = g_hash_table_new(NULL, g_direct_equal);
4675                 }
4676                 session = imap_session_get(folder);
4677                 if (session) {
4678                         imap_refresh_sensitivity(session);
4679                         session->sens_update_block = TRUE;
4680                 }
4681         } else {
4682                 debug_print("IMAP switching away from batch mode\n");
4683                 /* process stuff */
4684                 process_hashtable(item);
4685                 item->batching = FALSE;
4686                 session = imap_session_get(folder);
4687                 if (session) {
4688                         session->sens_update_block = FALSE;
4689                         imap_refresh_sensitivity(session);
4690                 }
4691         }
4692 }
4693
4694
4695
4696 /* data types conversion libetpan <-> claws */
4697
4698
4699
4700 #define ETPAN_IMAP_MB_MARKED      1
4701 #define ETPAN_IMAP_MB_UNMARKED    2
4702 #define ETPAN_IMAP_MB_NOSELECT    4
4703 #define ETPAN_IMAP_MB_NOINFERIORS 8
4704
4705 static int imap_flags_to_flags(struct mailimap_mbx_list_flags * imap_flags)
4706 {
4707   int flags;
4708   clistiter * cur;
4709   
4710   flags = 0;
4711   if (imap_flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
4712     switch (imap_flags->mbf_sflag) {
4713     case MAILIMAP_MBX_LIST_SFLAG_MARKED:
4714       flags |= ETPAN_IMAP_MB_MARKED;
4715       break;
4716     case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
4717       flags |= ETPAN_IMAP_MB_NOSELECT;
4718       break;
4719     case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
4720       flags |= ETPAN_IMAP_MB_UNMARKED;
4721       break;
4722     }
4723   }
4724   
4725   for(cur = clist_begin(imap_flags->mbf_oflags) ; cur != NULL ;
4726       cur = clist_next(cur)) {
4727     struct mailimap_mbx_list_oflag * oflag;
4728     
4729     oflag = clist_content(cur);
4730     
4731     switch (oflag->of_type) {
4732     case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
4733       flags |= ETPAN_IMAP_MB_NOINFERIORS;
4734       break;
4735     }
4736   }
4737   
4738   return flags;
4739 }
4740
4741 static GSList * imap_list_from_lep(IMAPFolder * folder,
4742                                    clist * list, const gchar * real_path, gboolean all)
4743 {
4744         clistiter * iter;
4745         GSList * item_list = NULL, *llast = NULL;
4746         
4747         for(iter = clist_begin(list) ; iter != NULL ;
4748             iter = clist_next(iter)) {
4749                 struct mailimap_mailbox_list * mb;
4750                 int flags;
4751                 char delimiter;
4752                 char * name;
4753                 char * dup_name;
4754                 gchar * base;
4755                 gchar * loc_name;
4756                 gchar * loc_path;
4757                 FolderItem *new_item;
4758                 
4759                 mb = clist_content(iter);
4760
4761                 if (mb == NULL)
4762                         continue;
4763
4764                 flags = 0;
4765                 if (mb->mb_flag != NULL)
4766                         flags = imap_flags_to_flags(mb->mb_flag);
4767                 
4768                 delimiter = mb->mb_delimiter;
4769                 name = mb->mb_name;
4770                 
4771                 dup_name = strdup(name);                
4772                 if (delimiter != '\0')
4773                         subst_char(dup_name, delimiter, '/');
4774                 
4775                 base = g_path_get_basename(dup_name);
4776                 if (base[0] == '.') {
4777                         g_free(base);
4778                         free(dup_name);
4779                         continue;
4780                 }
4781                 if (!all && path_cmp(name, real_path) == 0) {
4782                         g_free(base);
4783                         free(dup_name);
4784                         continue;
4785                 }
4786
4787                 if (!all && dup_name[strlen(dup_name)-1] == '/') {
4788                         dup_name[strlen(dup_name)-1] = '\0';
4789                 }
4790                 
4791                 loc_name = imap_modified_utf7_to_utf8(base);
4792                 loc_path = imap_modified_utf7_to_utf8(dup_name);
4793                 
4794                 new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
4795                 if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
4796                         new_item->no_sub = TRUE;
4797                 if (strcmp(dup_name, "INBOX") != 0 &&
4798                     ((flags & ETPAN_IMAP_MB_NOSELECT) != 0))
4799                         new_item->no_select = TRUE;
4800                 
4801                 if (item_list == NULL)
4802                         llast = item_list = g_slist_append(item_list, new_item);
4803                 else {
4804                         llast = g_slist_append(llast, new_item);
4805                         llast = llast->next;
4806                 }
4807                 debug_print("folder '%s' found.\n", loc_path);
4808                 g_free(base);
4809                 g_free(loc_path);
4810                 g_free(loc_name);
4811                 
4812                 free(dup_name);
4813         }
4814         
4815         return item_list;
4816 }
4817
4818 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist)
4819 {
4820         GSList *sorted_list, *cur;
4821         guint first, last, next;
4822         GSList *ret_list = NULL, *llast = NULL;
4823         struct mailimap_set * current_set;
4824         unsigned int item_count;
4825         
4826         if (numlist == NULL)
4827                 return NULL;
4828         
4829         current_set = mailimap_set_new_empty();
4830         
4831         sorted_list = g_slist_copy(numlist);
4832         sorted_list = g_slist_sort(sorted_list, g_int_compare);
4833
4834         first = GPOINTER_TO_INT(sorted_list->data);
4835         
4836         item_count = 0;
4837         for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
4838                 if (GPOINTER_TO_INT(cur->data) == 0)
4839                         continue;
4840                 
4841                 item_count ++;
4842
4843                 last = GPOINTER_TO_INT(cur->data);
4844                 if (cur->next)
4845                         next = GPOINTER_TO_INT(cur->next->data);
4846                 else
4847                         next = 0;
4848
4849                 if (last + 1 != next || next == 0 || item_count >= folder->max_set_size) {
4850
4851                         struct mailimap_set_item * item;
4852                         item = mailimap_set_item_new(first, last);
4853                         mailimap_set_add(current_set, item);
4854                         
4855                         first = next;
4856
4857                         if (item_count >= folder->max_set_size) {
4858                                 if (ret_list == NULL)
4859                                         llast = ret_list = g_slist_append(ret_list,
4860                                                           current_set);
4861                                 else {
4862                                         llast = g_slist_append(llast, current_set);
4863                                         llast = llast->next;
4864                                 }
4865
4866                                 current_set = mailimap_set_new_empty();
4867                                 item_count = 0;
4868                         }
4869                 } 
4870         }
4871         
4872         if (clist_count(current_set->set_list) > 0) {
4873                 ret_list = g_slist_append(ret_list,
4874                                           current_set);
4875         }
4876         
4877         g_slist_free(sorted_list);
4878
4879         return ret_list;
4880 }
4881
4882 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist)
4883 {
4884         MsgNumberList *numlist = NULL;
4885         MsgInfoList *cur;
4886         GSList *seq_list;
4887
4888         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
4889                 MsgInfo *msginfo = (MsgInfo *) cur->data;
4890
4891                 numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
4892         }
4893         numlist = g_slist_reverse(numlist);
4894         seq_list = imap_get_lep_set_from_numlist(folder, numlist);
4895         g_slist_free(numlist);
4896
4897         return seq_list;
4898 }
4899
4900 static GSList * imap_uid_list_from_lep(clist * list)
4901 {
4902         clistiter * iter;
4903         GSList * result;
4904         
4905         result = NULL;
4906         
4907         for(iter = clist_begin(list) ; iter != NULL ;
4908             iter = clist_next(iter)) {
4909                 uint32_t * puid;
4910                 
4911                 puid = clist_content(iter);
4912                 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
4913         }
4914         
4915         result = g_slist_reverse(result);
4916         return result;
4917 }
4918
4919 static GSList * imap_uid_list_from_lep_tab(carray * list)
4920 {
4921         unsigned int i;
4922         GSList * result;
4923         
4924         result = NULL;
4925         
4926         for(i = 0 ; i < carray_count(list) ; i ++) {
4927                 uint32_t * puid;
4928                 
4929                 puid = carray_get(list, i);
4930                 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
4931         }
4932         result = g_slist_reverse(result);
4933         return result;
4934 }
4935
4936 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
4937                                                    GHashTable * hash)
4938 {
4939         unsigned int i;
4940         GSList * result;
4941         
4942         result = NULL;
4943         
4944         for(i = 0 ; i < carray_count(list) ; i += 2) {
4945                 uint32_t * puid;
4946                 int * pflags;
4947                 gint * pguid;
4948                 
4949                 puid = carray_get(list, i);
4950                 pflags = carray_get(list, i + 1);
4951                 pguid = malloc(sizeof(* pguid));
4952                 * pguid = * puid;
4953                 
4954                 g_hash_table_insert(hash, pguid, GINT_TO_POINTER(* pflags));
4955         }
4956 }
4957
4958 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
4959                                        FolderItem *item)
4960 {
4961         MsgInfo *msginfo = NULL;
4962         guint32 uid = 0;
4963         size_t size = 0;
4964         MsgFlags flags = {0, 0};
4965         
4966         if (info->headers == NULL)
4967                 return NULL;
4968
4969         MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
4970         if (folder_has_parent_of_type(item, F_QUEUE)) {
4971                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
4972         } else if (folder_has_parent_of_type(item, F_DRAFT)) {
4973                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
4974         }
4975         flags.perm_flags = info->flags;
4976         
4977         uid = info->uid;
4978         size = info->size;
4979         msginfo = procheader_parse_str(info->headers, flags, FALSE, FALSE);
4980         
4981         if (msginfo) {
4982                 msginfo->msgnum = uid;
4983                 msginfo->size = size;
4984         }
4985
4986         return msginfo;
4987 }
4988
4989 static void imap_lep_set_free(GSList *seq_list)
4990 {
4991         GSList * cur;
4992         
4993         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
4994                 struct mailimap_set * imapset;
4995                 
4996                 imapset = cur->data;
4997                 mailimap_set_free(imapset);
4998         }
4999         g_slist_free(seq_list);
5000 }
5001
5002 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags)
5003 {
5004         struct mailimap_flag_list * flag_list;
5005         
5006         flag_list = mailimap_flag_list_new_empty();
5007         
5008         if (IMAP_IS_SEEN(flags))
5009                 mailimap_flag_list_add(flag_list,
5010                                        mailimap_flag_new_seen());
5011         if (IMAP_IS_ANSWERED(flags))
5012                 mailimap_flag_list_add(flag_list,
5013                                        mailimap_flag_new_answered());
5014         if (IMAP_IS_FLAGGED(flags))
5015                 mailimap_flag_list_add(flag_list,
5016                                        mailimap_flag_new_flagged());
5017         if (IMAP_IS_DELETED(flags))
5018                 mailimap_flag_list_add(flag_list,
5019                                        mailimap_flag_new_deleted());
5020         if (IMAP_IS_DRAFT(flags))
5021                 mailimap_flag_list_add(flag_list,
5022                                        mailimap_flag_new_draft());
5023         
5024         return flag_list;
5025 }
5026
5027 guint imap_folder_get_refcnt(Folder *folder)
5028 {
5029         return ((IMAPFolder *)folder)->refcnt;
5030 }
5031
5032 void imap_folder_ref(Folder *folder)
5033 {
5034         ((IMAPFolder *)folder)->refcnt++;
5035 }
5036
5037 void imap_disconnect_all(void)
5038 {
5039         GList *list;
5040         for (list = account_get_list(); list != NULL; list = list->next) {
5041                 PrefsAccount *account = list->data;
5042                 if (account->protocol == A_IMAP4) {
5043                         RemoteFolder *folder = (RemoteFolder *)account->folder;
5044                         if (folder && folder->session) {
5045                                 IMAPSession *session = (IMAPSession *)folder->session;
5046                                 imap_threaded_disconnect(FOLDER(folder));
5047                                 SESSION(session)->state = SESSION_DISCONNECTED;
5048                                 session_destroy(SESSION(session));
5049                                 folder->session = NULL;
5050                         }
5051                 }
5052         }
5053 }
5054
5055 void imap_folder_unref(Folder *folder)
5056 {
5057         if (((IMAPFolder *)folder)->refcnt > 0)
5058                 ((IMAPFolder *)folder)->refcnt--;
5059 }
5060
5061 void imap_cancel_all(void)
5062 {
5063         GList *folderlist;
5064         GList *cur;
5065         
5066         folderlist = folder_get_list();
5067         for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
5068                 Folder *folder = (Folder *) cur->data;
5069
5070                 if (folder->klass == &imap_class) {
5071                         if (imap_is_busy(folder)) {
5072                                 IMAPSession *imap_session;
5073                                 RemoteFolder *rfolder;
5074                                 
5075                                 g_printerr("cancelled\n");
5076                                 imap_threaded_cancel(folder);
5077                                 rfolder = (RemoteFolder *) folder;
5078                                 imap_session = (IMAPSession *) rfolder->session;
5079                                 if (imap_session)
5080                                         imap_session->cancelled = 1;
5081                         }
5082                 }
5083         }
5084 }
5085
5086 gboolean imap_cancel_all_enabled(void)
5087 {
5088         GList *folderlist;
5089         GList *cur;
5090         
5091         folderlist = folder_get_list();
5092         for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
5093                 Folder *folder = (Folder *) cur->data;
5094
5095                 if (folder->klass == &imap_class) {
5096                         if (imap_is_busy(folder)) {
5097                                 return TRUE;
5098                         }
5099                 }
5100         }
5101         
5102         return FALSE;
5103 }
5104
5105 static gboolean imap_is_busy(Folder *folder)
5106 {
5107         IMAPSession *imap_session;
5108         RemoteFolder *rfolder;
5109         
5110         rfolder = (RemoteFolder *) folder;
5111         imap_session = (IMAPSession *) rfolder->session;
5112         if (imap_session == NULL)
5113                 return FALSE;
5114         
5115         return imap_session->busy;
5116 }
5117
5118 #else /* HAVE_LIBETPAN */
5119
5120 static FolderClass imap_class;
5121
5122 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
5123 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
5124
5125 static Folder   *imap_folder_new        (const gchar    *name,
5126                                          const gchar    *path)
5127 {
5128         static gboolean missing_imap_warning = TRUE;
5129         if (missing_imap_warning) {
5130                 missing_imap_warning = FALSE;
5131                 alertpanel_error(
5132                         _("You have one or more IMAP accounts "
5133                           "defined. However this version of "
5134                           "Claws Mail has been built without "
5135                           "IMAP support; your IMAP account(s) are "
5136                           "disabled.\n\n"
5137                           "You probably need to "
5138                           "install libetpan and recompile "
5139                           "Claws Mail."));
5140         }
5141         return NULL;
5142 }
5143 static gint     imap_create_tree        (Folder         *folder)
5144 {
5145         return -1;
5146 }
5147 static FolderItem *imap_create_folder   (Folder         *folder,
5148                                          FolderItem     *parent,
5149                                          const gchar    *name)
5150 {
5151         return NULL;
5152 }
5153 static gint     imap_rename_folder      (Folder         *folder,
5154                                          FolderItem     *item, 
5155                                          const gchar    *name)
5156 {
5157         return -1;
5158 }
5159
5160 gchar imap_get_path_separator_for_item(FolderItem *item)
5161 {
5162         return '/';
5163 }
5164
5165 FolderClass *imap_get_class(void)
5166 {
5167         if (imap_class.idstr == NULL) {
5168                 imap_class.type = F_IMAP;
5169                 imap_class.idstr = "imap";
5170                 imap_class.uistr = "IMAP4";
5171
5172                 imap_class.new_folder = imap_folder_new;
5173                 imap_class.create_tree = imap_create_tree;
5174                 imap_class.create_folder = imap_create_folder;
5175                 imap_class.rename_folder = imap_rename_folder;
5176
5177                 imap_class.set_xml = folder_set_xml;
5178                 imap_class.get_xml = folder_get_xml;
5179                 imap_class.item_set_xml = imap_item_set_xml;
5180                 imap_class.item_get_xml = imap_item_get_xml;
5181                 /* nothing implemented */
5182         }
5183
5184         return &imap_class;
5185 }
5186
5187 void imap_disconnect_all(void)
5188 {
5189 }
5190
5191 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
5192 {
5193         return -1;
5194 }
5195
5196 GList * imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
5197 {
5198         return NULL;
5199 }
5200
5201 void imap_cache_msg(FolderItem *item, gint msgnum)
5202 {
5203 }
5204
5205 void imap_cancel_all(void)
5206 {
5207 }
5208
5209 gboolean imap_cancel_all_enabled(void)
5210 {
5211         return FALSE;
5212 }
5213
5214 #endif
5215
5216 #ifdef HAVE_LIBETPAN
5217 static void imap_synchronise(FolderItem *item, gint days) 
5218 {
5219         if (IMAP_FOLDER_ITEM(item)->last_sync == IMAP_FOLDER_ITEM(item)->last_change) {
5220                 debug_print("%s already synced\n", item->path?item->path:item->name);
5221                 return;
5222         }
5223         debug_print("syncing %s\n", item->path?item->path:item->name);
5224         imap_gtk_synchronise(item, days);
5225         IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
5226 }
5227 #endif
5228
5229 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
5230 {
5231 #ifdef HAVE_LIBETPAN
5232         GList *cur;
5233 #endif
5234         folder_item_set_xml(folder, item, tag);
5235         
5236 #ifdef HAVE_LIBETPAN
5237         for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
5238                 XMLAttr *attr = (XMLAttr *) cur->data;
5239
5240                 if (!attr || !attr->name || !attr->value) continue;
5241                 if (!strcmp(attr->name, "uidnext"))
5242                         IMAP_FOLDER_ITEM(item)->uid_next = atoi(attr->value);
5243                 if (!strcmp(attr->name, "last_sync"))
5244                         IMAP_FOLDER_ITEM(item)->last_sync = atoi(attr->value);
5245                 if (!strcmp(attr->name, "last_change"))
5246                         IMAP_FOLDER_ITEM(item)->last_change = atoi(attr->value);
5247         }
5248         if (IMAP_FOLDER_ITEM(item)->last_change == 0)
5249                 IMAP_FOLDER_ITEM(item)->last_change = time(NULL);
5250 #endif
5251 }
5252
5253 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
5254 {
5255         XMLTag *tag;
5256
5257         tag = folder_item_get_xml(folder, item);
5258
5259 #ifdef HAVE_LIBETPAN
5260         xml_tag_add_attr(tag, xml_attr_new_int("uidnext", 
5261                         IMAP_FOLDER_ITEM(item)->uid_next));
5262         xml_tag_add_attr(tag, xml_attr_new_int("last_sync", 
5263                         IMAP_FOLDER_ITEM(item)->last_sync));
5264         xml_tag_add_attr(tag, xml_attr_new_int("last_change", 
5265                         IMAP_FOLDER_ITEM(item)->last_change));
5266
5267 #endif
5268         return tag;
5269 }