2007-10-25 [colin] 3.0.2cvs102
[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         ok = imap_set_message_flags
1807                 (session, numlist, IMAP_FLAG_DELETED, TRUE);
1808         if (ok != MAILIMAP_NO_ERROR) {
1809                 log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
1810                 return ok;
1811         }
1812         ok = imap_cmd_expunge(session);
1813         if (ok != MAILIMAP_NO_ERROR) {
1814                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
1815                 return ok;
1816         }
1817         
1818         unlock_session(session);
1819
1820         dir = folder_item_get_path(msginfo->folder);
1821         if (is_dir_exist(dir)) {
1822                 for (cur = msglist; cur; cur = cur->next) {
1823                         msginfo = (MsgInfo *)cur->data;
1824                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
1825                 }
1826         }
1827         g_free(dir);
1828
1829         g_relation_destroy(uid_mapping);
1830         g_slist_free(numlist);
1831
1832         g_free(destdir);
1833         if (ok == MAILIMAP_NO_ERROR)
1834                 return 0;
1835         else
1836                 return -1;
1837 }
1838
1839 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
1840                     MsgInfoList *msglist, GRelation *relation)
1841 {
1842         MsgInfo *msginfo;
1843
1844         g_return_val_if_fail(folder != NULL, -1);
1845         g_return_val_if_fail(dest != NULL, -1);
1846         if (msglist == NULL)
1847                 return 0;
1848
1849         msginfo = (MsgInfo *)msglist->data;
1850         g_return_val_if_fail(msginfo->folder != NULL, -1);
1851
1852         return imap_do_remove_msgs(folder, dest, msglist, relation);
1853 }
1854
1855 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
1856 {
1857         GSList *list = folder_item_get_msg_list(item);
1858         gint res = imap_remove_msgs(folder, item, list, NULL);
1859         procmsg_msg_list_free(list);
1860         return res;
1861 }
1862
1863 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
1864                                     MsgInfo *msginfo)
1865 {
1866         /* TODO: properly implement this method */
1867         return FALSE;
1868 }
1869
1870 static gint imap_close(Folder *folder, FolderItem *item)
1871 {
1872         return 0;
1873 }
1874
1875 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
1876 {
1877         FolderItem *item = NULL;
1878         IMAPSession *session;
1879         gchar *root_folder = NULL;
1880
1881         g_return_val_if_fail(folder != NULL, -1);
1882         g_return_val_if_fail(folder->account != NULL, -1);
1883
1884         debug_print("getting session...\n");
1885         session = imap_session_get(folder);
1886         if (!session) {
1887                 if (!folder->node) {
1888                         folder_tree_destroy(folder);
1889                         item = folder_item_new(folder, folder->name, NULL);
1890                         item->folder = folder;
1891                         folder->node = item->node = g_node_new(item);
1892                 }
1893                 return -1;
1894         }
1895
1896         if (folder->account->imap_dir && *folder->account->imap_dir) {
1897                 gchar *real_path;
1898                 int r;
1899                 clist * lep_list;
1900
1901                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
1902                 extract_quote(root_folder, '"');
1903                 subst_char(root_folder,
1904                            imap_get_path_separator(session, IMAP_FOLDER(folder),
1905                                                    root_folder),
1906                            '/');
1907                 strtailchomp(root_folder, '/');
1908                 real_path = imap_get_real_path
1909                         (session, IMAP_FOLDER(folder), root_folder);
1910                 debug_print("IMAP root directory: %s\n", real_path);
1911
1912                 /* check if root directory exist */
1913
1914                 r = imap_threaded_list(session->folder, "", real_path,
1915                                        &lep_list);
1916
1917                 if (r != MAILIMAP_NO_ERROR)
1918                         imap_handle_error(SESSION(session), r);
1919
1920                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
1921                         if (!folder->node) {
1922                                 item = folder_item_new(folder, folder->name, NULL);
1923                                 item->folder = folder;
1924                                 folder->node = item->node = g_node_new(item);
1925                         }
1926                         return -1;
1927                 }
1928                 mailimap_list_result_free(lep_list);
1929                                 
1930                 g_free(real_path);
1931         }
1932
1933         if (folder->node)
1934                 item = FOLDER_ITEM(folder->node->data);
1935                 
1936         if (item && !item->path && root_folder) {
1937                 item->path = g_strdup(root_folder);
1938         }
1939
1940         if (!item || ((item->path || root_folder) &&
1941                       strcmp2(item->path, root_folder) != 0)) {
1942                 folder_tree_destroy(folder);
1943                 item = folder_item_new(folder, folder->name, root_folder);
1944                 item->folder = folder;
1945                 folder->node = item->node = g_node_new(item);
1946         }
1947
1948         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
1949         imap_create_missing_folders(folder);
1950
1951         return 0;
1952 }
1953
1954 static gint imap_scan_tree(Folder *folder)
1955 {
1956         gboolean subs_only = FALSE;
1957         if (folder->account) {
1958                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
1959                 subs_only = folder->account->imap_subsonly;
1960         }
1961         return imap_scan_tree_real(folder, subs_only);
1962 }
1963
1964 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
1965 {
1966         Folder *folder;
1967         IMAPFolder *imapfolder;
1968         FolderItem *new_item;
1969         GSList *item_list, *cur;
1970         GNode *node;
1971         gchar *real_path;
1972         gchar *wildcard_path;
1973         gchar separator;
1974         gchar wildcard[3];
1975         clist * lep_list;
1976         int r;
1977         
1978         g_return_val_if_fail(item != NULL, -1);
1979         g_return_val_if_fail(item->folder != NULL, -1);
1980         g_return_val_if_fail(item->no_sub == FALSE, -1);
1981
1982         folder = item->folder;
1983         imapfolder = IMAP_FOLDER(folder);
1984
1985         separator = imap_get_path_separator(session, imapfolder, item->path);
1986
1987         if (folder->ui_func)
1988                 folder->ui_func(folder, item, folder->ui_func_data);
1989
1990         if (item->path) {
1991                 wildcard[0] = separator;
1992                 wildcard[1] = '%';
1993                 wildcard[2] = '\0';
1994                 real_path = imap_get_real_path(session, imapfolder, item->path);
1995         } else {
1996                 wildcard[0] = '%';
1997                 wildcard[1] = '\0';
1998                 real_path = g_strdup("");
1999         }
2000
2001         Xstrcat_a(wildcard_path, real_path, wildcard,
2002                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2003         lep_list = NULL;
2004         
2005         if (subs_only)
2006                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2007         else
2008                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2009
2010         if (r != MAILIMAP_NO_ERROR) {
2011                 imap_handle_error(SESSION(session), r);
2012                 item_list = NULL;
2013         }
2014         else {
2015                 item_list = imap_list_from_lep(imapfolder,
2016                                                lep_list, real_path, FALSE);
2017                 mailimap_list_result_free(lep_list);
2018         }
2019         
2020         g_free(real_path);
2021
2022         node = item->node->children;
2023         while (node != NULL) {
2024                 FolderItem *old_item = FOLDER_ITEM(node->data);
2025                 GNode *next = node->next;
2026
2027                 new_item = NULL;
2028                 for (cur = item_list; cur != NULL; cur = cur->next) {
2029                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2030                         if (!strcmp2(old_item->path, cur_item->path)) {
2031                                 new_item = cur_item;
2032                                 break;
2033                         }
2034                 }
2035                 if (!new_item) {
2036                         if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
2037                                 debug_print("not removing INBOX\n");
2038                         } else {
2039                                 debug_print("folder '%s' not found. removing...\n",
2040                                             old_item->path);
2041                                 folder_item_remove(old_item);
2042                         }
2043                 } else {
2044                         old_item->no_sub = new_item->no_sub;
2045                         old_item->no_select = new_item->no_select;
2046                         if (old_item->no_sub == TRUE && node->children) {
2047                                 debug_print("folder '%s' doesn't have "
2048                                             "subfolders. removing...\n",
2049                                             old_item->path);
2050                                 folder_item_remove_children(old_item);
2051                         }
2052                 }
2053
2054                 node = next;
2055         }
2056
2057         for (cur = item_list; cur != NULL; cur = cur->next) {
2058                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2059                 new_item = NULL;
2060
2061                 for (node = item->node->children; node != NULL;
2062                      node = node->next) {
2063                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
2064                                      cur_item->path)) {
2065                                 new_item = FOLDER_ITEM(node->data);
2066                                 folder_item_destroy(cur_item);
2067                                 cur_item = NULL;
2068                                 break;
2069                         }
2070                 }
2071                 if (!new_item) {
2072                         new_item = cur_item;
2073                         debug_print("new folder '%s' found.\n", new_item->path);
2074                         folder_item_append(item, new_item);
2075                 }
2076
2077                 if (!strcmp(new_item->path, "INBOX")) {
2078                         new_item->stype = F_INBOX;
2079                         folder->inbox = new_item;
2080                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2081                         gchar *base;
2082
2083                         base = g_path_get_basename(new_item->path);
2084
2085                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2086                                 new_item->stype = F_OUTBOX;
2087                                 folder->outbox = new_item;
2088                         } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
2089                                 new_item->stype = F_DRAFT;
2090                                 folder->draft = new_item;
2091                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2092                                 new_item->stype = F_QUEUE;
2093                                 folder->queue = new_item;
2094                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2095                                 new_item->stype = F_TRASH;
2096                                 folder->trash = new_item;
2097                         }
2098                         g_free(base);
2099                 }
2100
2101                 if (new_item->no_sub == FALSE)
2102                         imap_scan_tree_recursive(session, new_item, subs_only);
2103         }
2104
2105         g_slist_free(item_list);
2106
2107         return MAILIMAP_NO_ERROR;
2108 }
2109
2110 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2111 {
2112         IMAPSession *session = imap_session_get(folder);
2113         gchar *real_path;
2114         gchar *wildcard_path;
2115         gchar separator;
2116         gchar wildcard[3];
2117         clist * lep_list;
2118         GSList *item_list = NULL, *cur;
2119         GList *child_list = NULL, *tmplist = NULL;
2120         GSList *sub_list = NULL;
2121         int r;
2122
2123         if (!session)
2124                 return NULL;
2125
2126         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
2127
2128         if (item->path) {
2129                 wildcard[0] = separator;
2130                 wildcard[1] = '%';
2131                 wildcard[2] = '\0';
2132                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2133         } else {
2134                 wildcard[0] = '%';
2135                 wildcard[1] = '\0';
2136                 real_path = g_strdup("");
2137         }
2138
2139         Xstrcat_a(wildcard_path, real_path, wildcard,
2140                   {g_free(real_path); return NULL;});
2141         lep_list = NULL;
2142         
2143         if (unsubs_only)
2144                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2145                                 item->path?item->path:item->name);
2146         else
2147                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2148                                 item->path?item->path:item->name);
2149
2150         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2151         if (r) {
2152                 statusbar_pop_all();
2153                 return NULL;
2154         }
2155         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2156                                lep_list, real_path, FALSE);
2157         mailimap_list_result_free(lep_list);
2158
2159         for (cur = item_list; cur != NULL; cur = cur->next) {
2160                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2161                 if (recursive) {
2162                         tmplist = imap_scan_subtree(folder, cur_item, 
2163                                         unsubs_only, recursive);
2164                         if (tmplist)
2165                                 child_list = g_list_concat(child_list, tmplist);
2166                 }
2167                 child_list = g_list_prepend(child_list,
2168                                 imap_get_real_path(session, 
2169                                         IMAP_FOLDER(folder), cur_item->path));
2170                 
2171                 folder_item_destroy(cur_item);
2172         }
2173         child_list = g_list_reverse(child_list);
2174         g_slist_free(item_list);
2175
2176         if (unsubs_only) {
2177                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2178                 if (r) {
2179                         statusbar_pop_all();
2180                         return NULL;
2181                 }
2182                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2183                                        lep_list, real_path, FALSE);
2184                 mailimap_list_result_free(lep_list);
2185
2186                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2187                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2188                         GList *oldlitem = NULL;
2189                         gchar *tmp = imap_get_real_path(session, 
2190                                         IMAP_FOLDER(folder), cur_item->path);
2191                         folder_item_destroy(cur_item);
2192                         oldlitem = g_list_find_custom(
2193                                         child_list, tmp, (GCompareFunc)strcmp2);
2194                         if (oldlitem) {
2195                                 child_list = g_list_remove_link(child_list, oldlitem);
2196                                 g_free(oldlitem->data);
2197                                 g_list_free(oldlitem);
2198                         }
2199                         g_free(tmp);
2200                 }
2201         }
2202
2203         statusbar_pop_all();
2204
2205         return child_list;
2206 }
2207
2208 static gint imap_create_tree(Folder *folder)
2209 {
2210         g_return_val_if_fail(folder != NULL, -1);
2211         g_return_val_if_fail(folder->node != NULL, -1);
2212         g_return_val_if_fail(folder->node->data != NULL, -1);
2213         g_return_val_if_fail(folder->account != NULL, -1);
2214
2215         imap_scan_tree(folder);
2216         imap_create_missing_folders(folder);
2217
2218         return 0;
2219 }
2220
2221 static void imap_create_missing_folders(Folder *folder)
2222 {
2223         g_return_if_fail(folder != NULL);
2224
2225         if (!folder->inbox)
2226                 folder->inbox = imap_create_special_folder
2227                         (folder, F_INBOX, "INBOX");
2228         if (!folder->trash)
2229                 folder->trash = imap_create_special_folder
2230                         (folder, F_TRASH, "Trash");
2231         if (!folder->queue)
2232                 folder->queue = imap_create_special_folder
2233                         (folder, F_QUEUE, "Queue");
2234         if (!folder->outbox)
2235                 folder->outbox = imap_create_special_folder
2236                         (folder, F_OUTBOX, "Sent");
2237         if (!folder->draft)
2238                 folder->draft = imap_create_special_folder
2239                         (folder, F_DRAFT, "Drafts");
2240 }
2241
2242 static FolderItem *imap_create_special_folder(Folder *folder,
2243                                               SpecialFolderItemType stype,
2244                                               const gchar *name)
2245 {
2246         FolderItem *item;
2247         FolderItem *new_item;
2248
2249         g_return_val_if_fail(folder != NULL, NULL);
2250         g_return_val_if_fail(folder->node != NULL, NULL);
2251         g_return_val_if_fail(folder->node->data != NULL, NULL);
2252         g_return_val_if_fail(folder->account != NULL, NULL);
2253         g_return_val_if_fail(name != NULL, NULL);
2254
2255         item = FOLDER_ITEM(folder->node->data);
2256         new_item = imap_create_folder(folder, item, name);
2257
2258         if (!new_item) {
2259                 g_warning("Can't create '%s'\n", name);
2260                 if (!folder->inbox) return NULL;
2261
2262                 new_item = imap_create_folder(folder, folder->inbox, name);
2263                 if (!new_item)
2264                         g_warning("Can't create '%s' under INBOX\n", name);
2265                 else
2266                         new_item->stype = stype;
2267         } else
2268                 new_item->stype = stype;
2269
2270         return new_item;
2271 }
2272
2273 static gchar *imap_folder_get_path(Folder *folder)
2274 {
2275         gchar *folder_path;
2276
2277         g_return_val_if_fail(folder != NULL, NULL);
2278         g_return_val_if_fail(folder->account != NULL, NULL);
2279
2280         folder_path = g_strconcat(get_imap_cache_dir(),
2281                                   G_DIR_SEPARATOR_S,
2282                                   folder->account->recv_server,
2283                                   G_DIR_SEPARATOR_S,
2284                                   folder->account->userid,
2285                                   NULL);
2286
2287         return folder_path;
2288 }
2289
2290 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
2291 {
2292         gchar *folder_path, *path;
2293
2294         g_return_val_if_fail(folder != NULL, NULL);
2295         g_return_val_if_fail(item != NULL, NULL);
2296         folder_path = imap_folder_get_path(folder);
2297
2298         g_return_val_if_fail(folder_path != NULL, NULL);
2299         if (folder_path[0] == G_DIR_SEPARATOR) {
2300                 if (item->path)
2301                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
2302                                            item->path, NULL);
2303                 else
2304                         path = g_strdup(folder_path);
2305         } else {
2306                 if (item->path)
2307                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2308                                            folder_path, G_DIR_SEPARATOR_S,
2309                                            item->path, NULL);
2310                 else
2311                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2312                                            folder_path, NULL);
2313         }
2314         g_free(folder_path);
2315
2316         return path;
2317 }
2318
2319 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
2320                                const gchar *name)
2321 {
2322         gchar *dirpath, *imap_path;
2323         IMAPSession *session;
2324         FolderItem *new_item;
2325         gchar separator;
2326         gchar *new_name;
2327         const gchar *p;
2328         gint ok;
2329         gboolean no_select = FALSE, no_sub = FALSE;
2330         gboolean exist = FALSE;
2331         
2332         g_return_val_if_fail(folder != NULL, NULL);
2333         g_return_val_if_fail(folder->account != NULL, NULL);
2334         g_return_val_if_fail(parent != NULL, NULL);
2335         g_return_val_if_fail(name != NULL, NULL);
2336
2337         debug_print("getting session...\n");
2338         session = imap_session_get(folder);
2339         if (!session) {
2340                 return NULL;
2341         }
2342
2343         if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
2344                 dirpath = g_strdup(name);
2345         }else if (parent->path)
2346                 dirpath = g_strconcat(parent->path, "/", name, NULL);
2347         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
2348                 dirpath = g_strdup(name);
2349         else if (folder->account->imap_dir && *folder->account->imap_dir) {
2350                 gchar *imap_dir;
2351
2352                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
2353                 strtailchomp(imap_dir, '/');
2354                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
2355         } else
2356                 dirpath = g_strdup(name);
2357                 
2358         
2359
2360         /* keep trailing directory separator to create a folder that contains
2361            sub folder */
2362         imap_path = imap_utf8_to_modified_utf7(dirpath);
2363
2364         strtailchomp(dirpath, '/');
2365         Xstrdup_a(new_name, name, {
2366                 g_free(dirpath); 
2367                 return NULL;});
2368
2369         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path);
2370         imap_path_separator_subst(imap_path, separator);
2371         /* remove trailing / for display */
2372         strtailchomp(new_name, '/');
2373
2374         if (strcmp(dirpath, "INBOX") != 0) {
2375                 GPtrArray *argbuf;
2376                 int r;
2377                 clist * lep_list;
2378                 
2379                 argbuf = g_ptr_array_new();
2380                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
2381                 if (r != MAILIMAP_NO_ERROR) {
2382                         imap_handle_error(SESSION(session), r);
2383                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
2384                         g_free(imap_path);
2385                         g_free(dirpath);
2386                         ptr_array_free_strings(argbuf);
2387                         g_ptr_array_free(argbuf, TRUE);
2388                         return NULL;
2389                 }
2390                 
2391                 if (clist_count(lep_list) > 0)
2392                         exist = TRUE;
2393                 mailimap_list_result_free(lep_list);
2394                 lep_list = NULL;
2395                 if (!exist) {
2396                         ok = imap_cmd_create(session, imap_path);
2397                         if (ok != MAILIMAP_NO_ERROR) {
2398                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
2399                                 g_free(imap_path);
2400                                 g_free(dirpath);
2401                                 return NULL;
2402                         }
2403                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
2404                         if (r == MAILIMAP_NO_ERROR) {
2405                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2406                                                lep_list, dirpath, TRUE);
2407                                 if (item_list) {
2408                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2409                                         no_select = cur_item->no_select;
2410                                         no_sub = cur_item->no_sub;
2411                                         g_slist_free(item_list);
2412                                 } 
2413                                 mailimap_list_result_free(lep_list);
2414                         } else {
2415                                 imap_handle_error(SESSION(session), r);
2416                         }
2417                 }
2418                 imap_threaded_subscribe(folder, imap_path, TRUE);
2419         } else {
2420                 clist *lep_list;
2421                 int r;
2422                 /* just get flags */
2423                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
2424                 if (r == MAILIMAP_NO_ERROR) {
2425                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2426                                        lep_list, dirpath, TRUE);
2427                         if (item_list) {
2428                                 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2429                                 no_select = cur_item->no_select;
2430                                 no_sub = cur_item->no_sub;
2431                                 g_slist_free(item_list);
2432                         } 
2433                         mailimap_list_result_free(lep_list);
2434                 } else {
2435                         imap_handle_error(SESSION(session), r);
2436                 }
2437         }
2438
2439         new_item = folder_item_new(folder, new_name, dirpath);
2440         new_item->no_select = no_select;
2441         new_item->no_sub = no_sub;
2442         folder_item_append(parent, new_item);
2443         g_free(imap_path);
2444         g_free(dirpath);
2445
2446         dirpath = folder_item_get_path(new_item);
2447         if (!is_dir_exist(dirpath))
2448                 make_dir_hier(dirpath);
2449         g_free(dirpath);
2450
2451         if (exist) {
2452                 /* folder existed, scan it */
2453                 imap_scan_required(folder, new_item);
2454                 folder_item_scan_full(new_item, FALSE);
2455         }
2456
2457         return new_item;
2458 }
2459
2460 static gint imap_rename_folder(Folder *folder, FolderItem *item,
2461                                const gchar *name)
2462 {
2463         gchar *dirpath;
2464         gchar *newpath;
2465         gchar *real_oldpath;
2466         gchar *real_newpath;
2467         gchar *paths[2];
2468         gchar *old_cache_dir;
2469         gchar *new_cache_dir;
2470         IMAPSession *session;
2471         gchar separator;
2472         gint ok;
2473         gint exists, recent, unseen;
2474         guint32 uid_validity;
2475
2476         g_return_val_if_fail(folder != NULL, -1);
2477         g_return_val_if_fail(item != NULL, -1);
2478         g_return_val_if_fail(item->path != NULL, -1);
2479         g_return_val_if_fail(name != NULL, -1);
2480
2481         debug_print("getting session...\n");
2482         session = imap_session_get(folder);
2483         if (!session) {
2484                 return -1;
2485         }
2486
2487         if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path)) != NULL) {
2488                 g_warning(_("New folder name must not contain the namespace "
2489                             "path separator"));
2490                 return -1;
2491         }
2492
2493         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2494
2495         g_free(session->mbox);
2496         session->mbox = NULL;
2497         session->exists = 0;
2498         session->recent = 0;
2499         session->expunge = 0;
2500         ok = imap_cmd_examine(session, "INBOX",
2501                               &exists, &recent, &unseen, &uid_validity, FALSE);
2502         if (ok != MAILIMAP_NO_ERROR) {
2503                 g_free(real_oldpath);
2504                 return -1;
2505         }
2506
2507         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
2508         if (strchr(item->path, G_DIR_SEPARATOR)) {
2509                 dirpath = g_path_get_dirname(item->path);
2510                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
2511                 g_free(dirpath);
2512         } else
2513                 newpath = g_strdup(name);
2514
2515         real_newpath = imap_utf8_to_modified_utf7(newpath);
2516         imap_path_separator_subst(real_newpath, separator);
2517
2518         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
2519         if (ok != MAILIMAP_NO_ERROR) {
2520                 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
2521                             real_oldpath, real_newpath);
2522                 g_free(real_oldpath);
2523                 g_free(newpath);
2524                 g_free(real_newpath);
2525                 return -1;
2526         }
2527         g_free(item->name);
2528         item->name = g_strdup(name);
2529
2530         old_cache_dir = folder_item_get_path(item);
2531
2532         paths[0] = g_strdup(item->path);
2533         paths[1] = newpath;
2534         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2535                         imap_rename_folder_func, paths);
2536
2537         if (is_dir_exist(old_cache_dir)) {
2538                 new_cache_dir = folder_item_get_path(item);
2539                 if (rename(old_cache_dir, new_cache_dir) < 0) {
2540                         FILE_OP_ERROR(old_cache_dir, "rename");
2541                 }
2542                 g_free(new_cache_dir);
2543         }
2544
2545         g_free(old_cache_dir);
2546         g_free(paths[0]);
2547         g_free(newpath);
2548         g_free(real_oldpath);
2549         g_free(real_newpath);
2550         return 0;
2551 }
2552
2553 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
2554 {
2555         gchar *path;
2556         gint r = -1;
2557         IMAPSession *session;
2558         debug_print("getting session...\n");
2559
2560         session = imap_session_get(folder);
2561         if (!session) {
2562                 return -1;
2563         }
2564         if (item && item->path) {
2565                 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2566                 if (!path)
2567                         return -1;
2568                 if (!strcmp(path, "INBOX") && sub == FALSE)
2569                         return -1;
2570                 debug_print("%ssubscribing %s\n", sub?"":"un", path);
2571                 r = imap_threaded_subscribe(folder, path, sub);
2572                 g_free(path);
2573         } else if (rpath) {
2574                 r = imap_threaded_subscribe(folder, rpath, sub);
2575         } else
2576                 return -1;
2577         return r;
2578 }
2579
2580 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
2581 {
2582         gint ok;
2583         IMAPSession *session;
2584         gchar *path;
2585         gchar *cache_dir;
2586         gboolean selected_folder;
2587
2588         g_return_val_if_fail(folder != NULL, -1);
2589         g_return_val_if_fail(item != NULL, -1);
2590         g_return_val_if_fail(item->path != NULL, -1);
2591
2592         debug_print("getting session...\n");
2593         session = imap_session_get(folder);
2594         if (!session) {
2595                 return -1;
2596         }
2597         path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2598
2599         imap_threaded_subscribe(folder, path, FALSE);
2600
2601         selected_folder = (session->mbox != NULL) &&
2602                           (!strcmp(session->mbox, item->path));
2603         if (selected_folder) {
2604                 ok = imap_cmd_close(session);
2605                 if (ok != MAILIMAP_NO_ERROR) {
2606                         debug_print("close err %d\n", ok);
2607                         imap_handle_error(SESSION(session), ok);
2608                         return ok;
2609                 }
2610         }
2611         ok = imap_cmd_delete(session, path);
2612         if (ok != MAILIMAP_NO_ERROR) {
2613                 gchar *tmp = g_strdup_printf("%s%c", path, 
2614                                 imap_get_path_separator(session, IMAP_FOLDER(folder), path));
2615                 g_free(path);
2616                 path = tmp;
2617                 ok = imap_cmd_delete(session, path);
2618         }
2619
2620         if (ok != MAILIMAP_NO_ERROR) {
2621                 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
2622                 g_free(path);
2623                 return -1;
2624         }
2625
2626         g_free(path);
2627         cache_dir = folder_item_get_path(item);
2628         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
2629                 g_warning("can't remove directory '%s'\n", cache_dir);
2630         g_free(cache_dir);
2631         folder_item_remove(item);
2632         return 0;
2633 }
2634
2635 static gint imap_remove_folder(Folder *folder, FolderItem *item)
2636 {
2637         GNode *node, *next;
2638
2639         g_return_val_if_fail(item != NULL, -1);
2640         g_return_val_if_fail(item->folder != NULL, -1);
2641         g_return_val_if_fail(item->node != NULL, -1);
2642
2643         node = item->node->children;
2644         while (node != NULL) {
2645                 next = node->next;
2646                 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
2647                         return -1;
2648                 node = next;
2649         }
2650         debug_print("IMAP removing %s\n", item->path);
2651
2652         if (imap_remove_all_msg(folder, item) < 0)
2653                 return -1;
2654         return imap_remove_folder_real(folder, item);
2655 }
2656
2657 typedef struct _uncached_data {
2658         IMAPSession *session;
2659         FolderItem *item;
2660         MsgNumberList *numlist;
2661         guint cur;
2662         guint total;
2663         gboolean done;
2664         int ok;
2665 } uncached_data;
2666
2667 static void *imap_get_uncached_messages_thread(void *data)
2668 {
2669         uncached_data *stuff = (uncached_data *)data;
2670         IMAPSession *session = stuff->session;
2671         FolderItem *item = stuff->item;
2672         MsgNumberList *numlist = stuff->numlist;
2673         
2674         GSList *newlist = NULL;
2675         GSList *llast = NULL;
2676         GSList *seq_list, *cur;
2677
2678         debug_print("uncached_messages\n");
2679         
2680         if (session == NULL || item == NULL || item->folder == NULL
2681             || FOLDER_CLASS(item->folder) != &imap_class) {
2682                 stuff->done = TRUE;
2683                 return NULL;
2684         }
2685         
2686         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
2687         debug_print("get msgs info\n");
2688         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2689                 struct mailimap_set * imapset;
2690                 unsigned int i;
2691                 int r;
2692                 carray * env_list;
2693                 int count;
2694                 
2695                 if (session->cancelled)
2696                         break;
2697                 
2698                 imapset = cur->data;
2699                 
2700                 r = imap_threaded_fetch_env(session->folder,
2701                                             imapset, &env_list);
2702                 if (r != MAILIMAP_NO_ERROR) {
2703                         imap_handle_error(SESSION(session), r);
2704                         if (is_fatal(r)) {
2705                                 stuff->ok = r;
2706                                 return NULL;
2707                         }
2708                         continue;
2709                 }
2710
2711                 session_set_access_time(SESSION(session));
2712
2713                 count = 0;
2714                 for(i = 0 ; i < carray_count(env_list) ; i ++) {
2715                         struct imap_fetch_env_info * info;
2716                         MsgInfo * msginfo;
2717                         
2718                         info = carray_get(env_list, i);
2719                         msginfo = imap_envelope_from_lep(info, item);
2720                         if (msginfo == NULL)
2721                                 continue;
2722                         msginfo->folder = item;
2723                         if (!newlist)
2724                                 llast = newlist = g_slist_append(newlist, msginfo);
2725                         else {
2726                                 llast = g_slist_append(llast, msginfo);
2727                                 llast = llast->next;
2728                         }
2729                         count ++;
2730                 }
2731                 
2732                 imap_fetch_env_free(env_list);
2733         }
2734         
2735         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2736                 struct mailimap_set * imapset;
2737                 
2738                 imapset = cur->data;
2739                 mailimap_set_free(imapset);
2740         }
2741         
2742         session_set_access_time(SESSION(session));
2743         stuff->done = TRUE;
2744         return newlist;
2745 }
2746
2747 #define MAX_MSG_NUM 50
2748
2749 static GSList *imap_get_uncached_messages(IMAPSession *session,
2750                                         FolderItem *item,
2751                                         MsgNumberList *numlist,
2752                                         int *r)
2753 {
2754         GSList *result = NULL;
2755         GSList * cur;
2756         uncached_data *data = g_new0(uncached_data, 1);
2757         int finished;
2758         
2759         finished = 0;
2760         cur = numlist;
2761         data->total = g_slist_length(numlist);
2762         data->ok = MAILIMAP_NO_ERROR;
2763         debug_print("messages list : %i\n", data->total);
2764
2765         while (cur != NULL) {
2766                 GSList * partial_result;
2767                 int count;
2768                 GSList * newlist;
2769                 GSList * llast;
2770                 
2771                 llast = NULL;
2772                 count = 0;
2773                 newlist = NULL;
2774                 while (count < MAX_MSG_NUM) {
2775                         void * p;
2776                         
2777                         p = cur->data;
2778                         
2779                         if (newlist == NULL)
2780                                 llast = newlist = g_slist_append(newlist, p);
2781                         else {
2782                                 llast = g_slist_append(llast, p);
2783                                 llast = llast->next;
2784                         }
2785                         count ++;
2786                         
2787                         cur = cur->next;
2788                         if (cur == NULL)
2789                                 break;
2790                 }
2791                 
2792                 data->done = FALSE;
2793                 data->session = session;
2794                 data->item = item;
2795                 data->numlist = newlist;
2796                 data->cur += count;
2797                 
2798                 if (prefs_common.work_offline && 
2799                     !inc_offline_should_override(FALSE,
2800                         _("Claws Mail needs network access in order "
2801                           "to access the IMAP server."))) {
2802                         g_free(data);
2803                         return NULL;
2804                 }
2805                 
2806                 partial_result =
2807                         (GSList *)imap_get_uncached_messages_thread(data);
2808                 *r = data->ok;
2809                 if (data->ok != MAILIMAP_NO_ERROR) {
2810                         goto bail;
2811                 }
2812                 statusbar_progress_all(data->cur,data->total, 1);
2813                 
2814                 g_slist_free(newlist);
2815                 
2816                 result = g_slist_concat(result, partial_result);
2817         }
2818 bail:
2819         g_free(data);
2820         
2821         statusbar_progress_all(0,0,0);
2822         statusbar_pop_all();
2823         
2824         return result;
2825 }
2826
2827 static void imap_delete_all_cached_messages(FolderItem *item)
2828 {
2829         gchar *dir;
2830
2831         g_return_if_fail(item != NULL);
2832         g_return_if_fail(item->folder != NULL);
2833         g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
2834
2835         debug_print("Deleting all cached messages...\n");
2836
2837         dir = folder_item_get_path(item);
2838         if (is_dir_exist(dir))
2839                 remove_all_numbered_files(dir);
2840         g_free(dir);
2841
2842         debug_print("done.\n");
2843 }
2844
2845 gchar imap_get_path_separator_for_item(FolderItem *item)
2846 {
2847         Folder *folder = NULL;
2848         IMAPFolder *imap_folder = NULL;
2849         IMAPSession *session = NULL;
2850         gchar result = '/';
2851         
2852         if (!item)
2853                 return '/';
2854         folder = item->folder;
2855         
2856         if (!folder)
2857                 return '/';
2858         
2859         imap_folder = IMAP_FOLDER(folder);
2860         
2861         if (!imap_folder)
2862                 return '/';
2863         
2864         debug_print("getting session...");
2865         session = imap_session_get(FOLDER(folder));
2866         result = imap_get_path_separator(session, imap_folder, item->path);
2867         return result;
2868 }
2869
2870 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder)
2871 {
2872         clist * lep_list;
2873         int r;
2874         gchar separator = '\0';
2875         
2876         g_return_val_if_fail(session != NULL, '/');
2877         r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
2878         
2879         if (r != MAILIMAP_NO_ERROR) {
2880                 imap_handle_error(SESSION(session), r);
2881                 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
2882                 return '\0';
2883         }
2884
2885         if (clist_count(lep_list) > 0) {
2886                 clistiter * iter = clist_begin(lep_list); 
2887                 struct mailimap_mailbox_list * mb;
2888                 mb = clist_content(iter);
2889
2890                 separator = mb->mb_delimiter;
2891                 debug_print("got separator: %c\n", folder->last_seen_separator);
2892         }
2893         mailimap_list_result_free(lep_list);
2894         return separator;
2895 }
2896
2897 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path)
2898 {
2899         gchar separator = '/';
2900
2901         if (folder->last_seen_separator == 0) {
2902                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "");
2903         }
2904
2905         if (folder->last_seen_separator == 0) {
2906                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX");
2907         }
2908
2909         if (folder->last_seen_separator != 0) {
2910                 debug_print("using separator: %c\n", folder->last_seen_separator);
2911                 return folder->last_seen_separator;
2912         }
2913
2914         return separator;
2915 }
2916
2917 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path)
2918 {
2919         gchar *real_path;
2920         gchar separator;
2921
2922         g_return_val_if_fail(folder != NULL, NULL);
2923         g_return_val_if_fail(path != NULL, NULL);
2924
2925         real_path = imap_utf8_to_modified_utf7(path);
2926         separator = imap_get_path_separator(session, folder, path);
2927         imap_path_separator_subst(real_path, separator);
2928
2929         return real_path;
2930 }
2931
2932 static gint imap_set_message_flags(IMAPSession *session,
2933                                    MsgNumberList *numlist,
2934                                    IMAPFlags flags,
2935                                    gboolean is_set)
2936 {
2937         gint ok = 0;
2938         GSList *seq_list;
2939         GSList * cur;
2940         gint total = 0;
2941         IMAPFolder *folder = NULL;
2942         GSList *sorted_list = NULL;
2943
2944         if (numlist == NULL || session == NULL)
2945                 return MAILIMAP_ERROR_BAD_STATE;
2946         
2947         folder = IMAP_FOLDER(session->folder);
2948         
2949         sorted_list = g_slist_copy(numlist);
2950         sorted_list = g_slist_sort(sorted_list, g_int_compare);
2951         
2952         cur = g_slist_last(sorted_list);
2953
2954         if (cur)
2955                 total = GPOINTER_TO_INT(cur->data);
2956         
2957         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
2958
2959         statusbar_print_all(_("Flagging messages..."));
2960
2961         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
2962                 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
2963                 struct mailimap_set_item *set_item = clist_content(
2964                                                         clist_begin(imapset->set_list));
2965
2966                 statusbar_progress_all(set_item->set_first, total, 1);
2967
2968                 ok = imap_cmd_store(session, imapset,
2969                                     flags, is_set);
2970                 statusbar_progress_all(set_item->set_last, total, 1);
2971                 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
2972                         /* reduce max set size */
2973                         folder->max_set_size /= 2;
2974                 }
2975                 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
2976                         break;
2977                 }
2978         }
2979         
2980         g_slist_free(sorted_list);
2981
2982         statusbar_progress_all(0,0,0);
2983         statusbar_pop_all();
2984
2985         imap_lep_set_free(seq_list);
2986         
2987         return ok;
2988 }
2989
2990 typedef struct _select_data {
2991         IMAPSession *session;
2992         gchar *real_path;
2993         gint *exists;
2994         gint *recent;
2995         gint *unseen;
2996         guint32 *uid_validity;
2997         gboolean done;
2998 } select_data;
2999
3000 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3001                         const gchar *path,
3002                         gint *exists, gint *recent, gint *unseen,
3003                         guint32 *uid_validity, gboolean block)
3004 {
3005         gchar *real_path;
3006         gint ok;
3007         gint exists_, recent_, unseen_;
3008         guint32 uid_validity_;
3009         
3010         if (!exists && !recent && !unseen && !uid_validity) {
3011                 if (session->mbox && strcmp(session->mbox, path) == 0)
3012                         return MAILIMAP_NO_ERROR;
3013         }
3014         if (!exists)
3015                 exists = &exists_;
3016         if (!recent)
3017                 recent = &recent_;
3018         if (!unseen)
3019                 unseen = &unseen_;
3020         if (!uid_validity)
3021                 uid_validity = &uid_validity_;
3022
3023         g_free(session->mbox);
3024         session->mbox = NULL;
3025         session->exists = 0;
3026         session->recent = 0;
3027         session->expunge = 0;
3028
3029         real_path = imap_get_real_path(session, folder, path);
3030
3031         ok = imap_cmd_select(session, real_path,
3032                              exists, recent, unseen, uid_validity, block);
3033         if (ok != MAILIMAP_NO_ERROR) {
3034                 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
3035         } else {
3036                 session->mbox = g_strdup(path);
3037                 session->folder_content_changed = FALSE;
3038                 session->exists = *exists;
3039                 session->recent = *recent;
3040                 session->expunge = 0;
3041                 session->unseen = *unseen;
3042                 session->uid_validity = *uid_validity;
3043                 debug_print("select: exists %d recent %d expunge %d uid_validity %d\n", 
3044                         session->exists, session->recent, session->expunge,
3045                         session->uid_validity);
3046         }
3047         g_free(real_path);
3048
3049         return ok;
3050 }
3051
3052 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3053                         const gchar *path, IMAPFolderItem *item,
3054                         gint *messages,
3055                         guint32 *uid_next, guint32 *uid_validity,
3056                         gint *unseen, gboolean block)
3057 {
3058         int r;
3059         clistiter * iter;
3060         struct mailimap_mailbox_data_status * data_status;
3061         int got_values;
3062         gchar *real_path;
3063         guint mask = 0;
3064         
3065         real_path = imap_get_real_path(session, folder, path);
3066
3067         if (messages) {
3068                 mask |= 1 << 0;
3069                 *messages = 0;
3070         }
3071         if (uid_next) {
3072                 mask |= 1 << 2;
3073                 *uid_next = 0;
3074         }
3075         if (uid_validity) {
3076                 mask |= 1 << 3;
3077                 *uid_validity = 0;
3078         }
3079         if (unseen) {
3080                 mask |= 1 << 4;
3081                 *unseen = 0;
3082         }
3083         
3084         if (session->mbox != NULL &&
3085             !strcmp(session->mbox, item->item.path)) {
3086                 r = imap_cmd_close(session);
3087                 if (r != MAILIMAP_NO_ERROR) {
3088                         imap_handle_error(SESSION(session), r);
3089                         debug_print("close err %d\n", r);
3090                         return r;
3091                 }
3092         }
3093         
3094         r = imap_threaded_status(FOLDER(folder), real_path, 
3095                 &data_status, mask);
3096
3097         g_free(real_path);
3098         if (r != MAILIMAP_NO_ERROR) {
3099                 imap_handle_error(SESSION(session), r);
3100                 debug_print("status err %d\n", r);
3101                 return r;
3102         }
3103         
3104         if (data_status->st_info_list == NULL) {
3105                 mailimap_mailbox_data_status_free(data_status);
3106                 debug_print("status->st_info_list == NULL\n");
3107                 return MAILIMAP_ERROR_BAD_STATE;
3108         }
3109         
3110         got_values = 0;
3111         for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
3112             iter = clist_next(iter)) {
3113                 struct mailimap_status_info * info;             
3114                 
3115                 info = clist_content(iter);
3116                 switch (info->st_att) {
3117                 case MAILIMAP_STATUS_ATT_MESSAGES:
3118                         if (messages) {
3119                                 * messages = info->st_value;
3120                                 got_values |= 1 << 0;
3121                         }
3122                         break;
3123                         
3124                 case MAILIMAP_STATUS_ATT_UIDNEXT:
3125                         if (uid_next) {
3126                                 * uid_next = info->st_value;
3127                                 got_values |= 1 << 2;
3128                         }
3129                         break;
3130                         
3131                 case MAILIMAP_STATUS_ATT_UIDVALIDITY:
3132                         if (uid_validity) {
3133                                 * uid_validity = info->st_value;
3134                                 got_values |= 1 << 3;
3135                         }
3136                         break;
3137                         
3138                 case MAILIMAP_STATUS_ATT_UNSEEN:
3139                         if (unseen) {
3140                                 * unseen = info->st_value;
3141                                 got_values |= 1 << 4;
3142                         }
3143                         break;
3144                 }
3145         }
3146         mailimap_mailbox_data_status_free(data_status);
3147         
3148         if (got_values != mask) {
3149                 g_warning("status: incomplete values received (%d)\n", got_values);
3150         }
3151         return MAILIMAP_NO_ERROR;
3152 }
3153
3154 static void imap_free_capabilities(IMAPSession *session)
3155 {
3156         slist_free_strings(session->capability);
3157         g_slist_free(session->capability);
3158         session->capability = NULL;
3159 }
3160
3161 /* low-level IMAP4rev1 commands */
3162
3163 static gint imap_cmd_login(IMAPSession *session,
3164                            const gchar *user, const gchar *pass,
3165                            const gchar *type)
3166 {
3167         int r;
3168         gint ok;
3169
3170         if (!strcmp(type, "LOGIN") && imap_has_capability(session, "LOGINDISABLED")) {
3171                 gint ok = MAILIMAP_ERROR_BAD_STATE;
3172                 if (imap_has_capability(session, "STARTTLS")) {
3173 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
3174                         log_warning(LOG_PROTOCOL, _("Server requires TLS to log in.\n"));
3175                         ok = imap_cmd_starttls(session);
3176                         if (ok != MAILIMAP_NO_ERROR) {
3177                                 log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
3178                                 return ok;
3179                         } else {
3180                                 /* refresh capas */
3181                                 imap_free_capabilities(session);
3182                                 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
3183                                         imap_handle_error(SESSION(session), r);
3184                                         log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
3185                                         return r;
3186                                 }
3187                         }
3188 #else           
3189                         log_error(LOG_PROTOCOL, _("Connection to %s failed: "
3190                                         "server requires TLS, but Claws Mail "
3191                                         "has been compiled without OpenSSL "
3192                                         "support.\n"),
3193                                         SESSION(session)->server);
3194                         return MAILIMAP_ERROR_BAD_STATE;
3195 #endif
3196                 } else {
3197                         log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
3198                         return MAILIMAP_ERROR_BAD_STATE;
3199                 }
3200         }
3201
3202         log_print(LOG_PROTOCOL, "IMAP4> Logging %s to %s using %s\n", 
3203                         user,
3204                         SESSION(session)->server,
3205                         type);
3206         r = imap_threaded_login(session->folder, user, pass, type);
3207         if (r != MAILIMAP_NO_ERROR) {
3208                 imap_handle_error(SESSION(session), r);
3209                 log_print(LOG_PROTOCOL, "IMAP4< Error logging in to %s\n",
3210                                 SESSION(session)->server);
3211                 ok = r;
3212         } else {
3213                 log_print(LOG_PROTOCOL, "IMAP4< Login to %s successful\n",
3214                                 SESSION(session)->server);
3215                 ok = MAILIMAP_NO_ERROR;
3216         }
3217         return ok;
3218 }
3219
3220 static gint imap_cmd_noop(IMAPSession *session)
3221 {
3222         int r;
3223         unsigned int exists, recent, expunge, unseen, uidnext, uidval;
3224         
3225         r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
3226         if (r != MAILIMAP_NO_ERROR) {
3227                 imap_handle_error(SESSION(session), r);
3228                 debug_print("noop err %d\n", r);
3229                 return r;
3230         }
3231
3232         session->folder_content_changed = FALSE;
3233
3234         if ((exists && exists != session->exists)
3235          || (recent && recent != session->recent)
3236          || (expunge && expunge != session->expunge)
3237          || (unseen && unseen != session->unseen)) {
3238                 session->folder_content_changed = TRUE;
3239         }
3240         if (uidnext != 0 && uidnext != session->uid_next) {
3241                 session->uid_next = uidnext;
3242                 session->folder_content_changed = TRUE;
3243         }
3244         if (uidval != 0 && uidval != session->uid_validity) {
3245                 session->uid_validity = uidval;
3246                 session->folder_content_changed = TRUE;
3247         }
3248
3249         session->exists = exists;
3250         session->recent = recent;
3251         session->expunge = expunge;
3252         session->unseen = unseen;
3253
3254         session_set_access_time(SESSION(session));
3255
3256         return MAILIMAP_NO_ERROR;
3257 }
3258
3259 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
3260 static gint imap_cmd_starttls(IMAPSession *session)
3261 {
3262         int r;
3263         
3264         r = imap_threaded_starttls(session->folder, 
3265                 SESSION(session)->server, SESSION(session)->port);
3266         if (r != MAILIMAP_NO_ERROR) {
3267                 imap_handle_error(SESSION(session), r);
3268                 debug_print("starttls err %d\n", r);
3269                 return r;
3270         }
3271         return MAILIMAP_NO_ERROR;
3272 }
3273 #endif
3274
3275 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
3276                             gint *exists, gint *recent, gint *unseen,
3277                             guint32 *uid_validity, gboolean block)
3278 {
3279         int r;
3280
3281         r = imap_threaded_select(session->folder, folder,
3282                                  exists, recent, unseen, uid_validity);
3283         if (r != MAILIMAP_NO_ERROR) {
3284                 imap_handle_error(SESSION(session), r);
3285                 debug_print("select err %d\n", r);
3286                 return r;
3287         }
3288         return MAILIMAP_NO_ERROR;
3289 }
3290
3291 static gint imap_cmd_close(IMAPSession *session)
3292 {
3293         int r;
3294
3295         r = imap_threaded_close(session->folder);
3296         if (r != MAILIMAP_NO_ERROR) {
3297                 imap_handle_error(SESSION(session), r);
3298                 debug_print("close err %d\n", r);
3299                 return r;
3300         }
3301         g_free(session->mbox);
3302         session->mbox = NULL;
3303         session->exists = 0;
3304         session->recent = 0;
3305         session->expunge = 0;
3306         return MAILIMAP_NO_ERROR;
3307 }
3308
3309 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
3310                              gint *exists, gint *recent, gint *unseen,
3311                              guint32 *uid_validity, gboolean block)
3312 {
3313         int r;
3314
3315         r = imap_threaded_examine(session->folder, folder,
3316                                   exists, recent, unseen, uid_validity);
3317         if (r != MAILIMAP_NO_ERROR) {
3318                 imap_handle_error(SESSION(session), r);
3319                 debug_print("examine err %d\n", r);
3320                 
3321                 return r;
3322         }
3323         return MAILIMAP_NO_ERROR;
3324 }
3325
3326 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
3327 {
3328         int r;
3329
3330         r = imap_threaded_create(session->folder, folder);
3331         if (r != MAILIMAP_NO_ERROR) {
3332                 imap_handle_error(SESSION(session), r);
3333                 
3334                 return r;
3335         }
3336
3337         return MAILIMAP_NO_ERROR;
3338 }
3339
3340 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
3341                             const gchar *new_folder)
3342 {
3343         int r;
3344
3345         r = imap_threaded_rename(session->folder, old_folder,
3346                                  new_folder);
3347         if (r != MAILIMAP_NO_ERROR) {
3348                 imap_handle_error(SESSION(session), r);
3349                 return r;
3350         }
3351
3352         return MAILIMAP_NO_ERROR;
3353 }
3354
3355 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
3356 {
3357         int r;
3358         
3359
3360         r = imap_threaded_delete(session->folder, folder);
3361         if (r != MAILIMAP_NO_ERROR) {
3362                 imap_handle_error(SESSION(session), r);
3363                 return r;
3364         }
3365
3366         return MAILIMAP_NO_ERROR;
3367 }
3368
3369 typedef struct _fetch_data {
3370         IMAPSession *session;
3371         guint32 uid;
3372         const gchar *filename;
3373         gboolean headers;
3374         gboolean body;
3375         gboolean done;
3376 } fetch_data;
3377
3378 static void *imap_cmd_fetch_thread(void *data)
3379 {
3380         fetch_data *stuff = (fetch_data *)data;
3381         IMAPSession *session = stuff->session;
3382         guint32 uid = stuff->uid;
3383         const gchar *filename = stuff->filename;
3384         int r;
3385         
3386         if (stuff->body) {
3387                 r = imap_threaded_fetch_content(session->folder,
3388                                                uid, 1, filename);
3389         }
3390         else {
3391                 r = imap_threaded_fetch_content(session->folder,
3392                                                 uid, 0, filename);
3393         }
3394         if (r != MAILIMAP_NO_ERROR) {
3395                 imap_handle_error(SESSION(session), r);
3396                 debug_print("fetch err %d\n", r);
3397                 return GINT_TO_POINTER(MAILIMAP_ERROR_BAD_STATE);
3398         }
3399         return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
3400 }
3401
3402 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
3403                                 const gchar *filename, gboolean headers,
3404                                 gboolean body)
3405 {
3406         fetch_data *data = g_new0(fetch_data, 1);
3407         int result = 0;
3408         data->done = FALSE;
3409         data->session = session;
3410         data->uid = uid;
3411         data->filename = filename;
3412         data->headers = headers;
3413         data->body = body;
3414
3415         if (prefs_common.work_offline && 
3416             !inc_offline_should_override(FALSE,
3417                 _("Claws Mail needs network access in order "
3418                   "to access the IMAP server."))) {
3419                 g_free(data);
3420                 return -1;
3421         }
3422         statusbar_print_all(_("Fetching message..."));
3423         result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
3424         statusbar_pop_all();
3425         g_free(data);
3426         return result;
3427 }
3428
3429
3430 static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
3431                             const gchar *file, IMAPFlags flags, 
3432                             guint32 *new_uid)
3433 {
3434         struct mailimap_flag_list * flag_list;
3435         int r;
3436         
3437         g_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
3438
3439         flag_list = imap_flag_to_lep(flags);
3440         lock_session(session);
3441         r = imap_threaded_append(session->folder, destfolder,
3442                          file, flag_list, (int *)new_uid);
3443         mailimap_flag_list_free(flag_list);
3444
3445         if (r != MAILIMAP_NO_ERROR) {
3446                 imap_handle_error(SESSION(session), r);
3447                 debug_print("append err %d\n", r);
3448                 return r;
3449         }
3450
3451         unlock_session(session);
3452
3453         return MAILIMAP_NO_ERROR;
3454 }
3455
3456 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
3457                           const gchar *destfolder, GRelation *uid_mapping,
3458                           struct mailimap_set **source, struct mailimap_set **dest)
3459 {
3460         int r;
3461         
3462         g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
3463         g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
3464         g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
3465
3466         r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
3467         if (r != MAILIMAP_NO_ERROR) {
3468                 imap_handle_error(SESSION(session), r);
3469                 return r;
3470         }
3471
3472         return MAILIMAP_NO_ERROR;
3473 }
3474
3475 static gint imap_cmd_store(IMAPSession *session, struct mailimap_set * set,
3476                            IMAPFlags flags, int do_add)
3477 {
3478         int r;
3479         struct mailimap_flag_list * flag_list;
3480         struct mailimap_store_att_flags * store_att_flags;
3481         
3482         flag_list = imap_flag_to_lep(flags);
3483         
3484         if (do_add)
3485                 store_att_flags =
3486                         mailimap_store_att_flags_new_add_flags_silent(flag_list);
3487         else
3488                 store_att_flags =
3489                         mailimap_store_att_flags_new_remove_flags_silent(flag_list);
3490         
3491         r = imap_threaded_store(session->folder, set, store_att_flags);
3492         mailimap_store_att_flags_free(store_att_flags);
3493         if (r != MAILIMAP_NO_ERROR) {
3494                 imap_handle_error(SESSION(session), r);
3495                 return r;
3496         }
3497         
3498         return MAILIMAP_NO_ERROR;
3499 }
3500
3501 static gint imap_cmd_expunge(IMAPSession *session)
3502 {
3503         int r;
3504         
3505         if (prefs_common.work_offline && 
3506             !inc_offline_should_override(FALSE,
3507                 _("Claws Mail needs network access in order "
3508                   "to access the IMAP server."))) {
3509                 return -1;
3510         }
3511
3512         r = imap_threaded_expunge(session->folder);
3513         if (r != MAILIMAP_NO_ERROR) {
3514                 imap_handle_error(SESSION(session), r);
3515                 return r;
3516         }
3517
3518         return MAILIMAP_NO_ERROR;
3519 }
3520
3521 static void imap_path_separator_subst(gchar *str, gchar separator)
3522 {
3523         gchar *p;
3524         gboolean in_escape = FALSE;
3525
3526         if (!separator || separator == '/') return;
3527
3528         for (p = str; *p != '\0'; p++) {
3529                 if (*p == '/' && !in_escape)
3530                         *p = separator;
3531                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
3532                         in_escape = TRUE;
3533                 else if (*p == '-' && in_escape)
3534                         in_escape = FALSE;
3535         }
3536 }
3537
3538 static gchar *imap_modified_utf7_to_utf8(const gchar *mutf7_str)
3539 {
3540         static iconv_t cd = (iconv_t)-1;
3541         static gboolean iconv_ok = TRUE;
3542         GString *norm_utf7;
3543         gchar *norm_utf7_p;
3544         size_t norm_utf7_len;
3545         const gchar *p;
3546         gchar *to_str, *to_p;
3547         size_t to_len;
3548         gboolean in_escape = FALSE;
3549
3550         if (!iconv_ok) return g_strdup(mutf7_str);
3551
3552         if (cd == (iconv_t)-1) {
3553                 cd = iconv_open(CS_INTERNAL, CS_UTF_7);
3554                 if (cd == (iconv_t)-1) {
3555                         g_warning("iconv cannot convert UTF-7 to %s\n",
3556                                   CS_INTERNAL);
3557                         iconv_ok = FALSE;
3558                         return g_strdup(mutf7_str);
3559                 }
3560         }
3561
3562         /* modified UTF-7 to normal UTF-7 conversion */
3563         norm_utf7 = g_string_new(NULL);
3564
3565         for (p = mutf7_str; *p != '\0'; p++) {
3566                 /* replace: '&'  -> '+',
3567                             "&-" -> '&',
3568                             escaped ','  -> '/' */
3569                 if (!in_escape && *p == '&') {
3570                         if (*(p + 1) != '-') {
3571                                 g_string_append_c(norm_utf7, '+');
3572                                 in_escape = TRUE;
3573                         } else {
3574                                 g_string_append_c(norm_utf7, '&');
3575                                 p++;
3576                         }
3577                 } else if (in_escape && *p == ',') {
3578                         g_string_append_c(norm_utf7, '/');
3579                 } else if (in_escape && *p == '-') {
3580                         g_string_append_c(norm_utf7, '-');
3581                         in_escape = FALSE;
3582                 } else {
3583                         g_string_append_c(norm_utf7, *p);
3584                 }
3585         }
3586
3587         norm_utf7_p = norm_utf7->str;
3588         norm_utf7_len = norm_utf7->len;
3589         to_len = strlen(mutf7_str) * 5;
3590         to_p = to_str = g_malloc(to_len + 1);
3591
3592         if (iconv(cd, (ICONV_CONST gchar **)&norm_utf7_p, &norm_utf7_len,
3593                   &to_p, &to_len) == -1) {
3594                 g_warning(_("iconv cannot convert UTF-7 to %s\n"),
3595                           conv_get_locale_charset_str());
3596                 g_string_free(norm_utf7, TRUE);
3597                 g_free(to_str);
3598                 return g_strdup(mutf7_str);
3599         }
3600
3601         /* second iconv() call for flushing */
3602         iconv(cd, NULL, NULL, &to_p, &to_len);
3603         g_string_free(norm_utf7, TRUE);
3604         *to_p = '\0';
3605
3606         return to_str;
3607 }
3608
3609 static gchar *imap_utf8_to_modified_utf7(const gchar *from)
3610 {
3611         static iconv_t cd = (iconv_t)-1;
3612         static gboolean iconv_ok = TRUE;
3613         gchar *norm_utf7, *norm_utf7_p;
3614         size_t from_len, norm_utf7_len;
3615         GString *to_str;
3616         gchar *from_tmp, *to, *p;
3617         gboolean in_escape = FALSE;
3618
3619         if (!iconv_ok) return g_strdup(from);
3620
3621         if (cd == (iconv_t)-1) {
3622                 cd = iconv_open(CS_UTF_7, CS_INTERNAL);
3623                 if (cd == (iconv_t)-1) {
3624                         g_warning(_("iconv cannot convert %s to UTF-7\n"),
3625                                   CS_INTERNAL);
3626                         iconv_ok = FALSE;
3627                         return g_strdup(from);
3628                 }
3629         }
3630
3631         /* UTF-8 to normal UTF-7 conversion */
3632         Xstrdup_a(from_tmp, from, return g_strdup(from));
3633         from_len = strlen(from);
3634         norm_utf7_len = from_len * 5;
3635         Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
3636         norm_utf7_p = norm_utf7;
3637
3638 #define IS_PRINT(ch) (isprint(ch) && IS_ASCII(ch))
3639
3640         while (from_len > 0) {
3641                 if (*from_tmp == '+') {
3642                         *norm_utf7_p++ = '+';
3643                         *norm_utf7_p++ = '-';
3644                         norm_utf7_len -= 2;
3645                         from_tmp++;
3646                         from_len--;
3647                 } else if (IS_PRINT(*(guchar *)from_tmp)) {
3648                         /* printable ascii char */
3649                         *norm_utf7_p = *from_tmp;
3650                         norm_utf7_p++;
3651                         norm_utf7_len--;
3652                         from_tmp++;
3653                         from_len--;
3654                 } else {
3655                         size_t conv_len = 0;
3656
3657                         /* unprintable char: convert to UTF-7 */
3658                         p = from_tmp;
3659                         while (!IS_PRINT(*(guchar *)p) && conv_len < from_len) {
3660                                 conv_len += g_utf8_skip[*(guchar *)p];
3661                                 p += g_utf8_skip[*(guchar *)p];
3662                         }
3663
3664                         from_len -= conv_len;
3665                         if (iconv(cd, (ICONV_CONST gchar **)&from_tmp,
3666                                   &conv_len,
3667                                   &norm_utf7_p, &norm_utf7_len) == -1) {
3668                                 g_warning(_("iconv cannot convert UTF-8 to UTF-7\n"));
3669                                 return g_strdup(from);
3670                         }
3671
3672                         /* second iconv() call for flushing */
3673                         iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
3674                 }
3675         }
3676
3677 #undef IS_PRINT
3678
3679         *norm_utf7_p = '\0';
3680         to_str = g_string_new(NULL);
3681         for (p = norm_utf7; p < norm_utf7_p; p++) {
3682                 /* replace: '&' -> "&-",
3683                             '+' -> '&',
3684                             "+-" -> '+',
3685                             BASE64 '/' -> ',' */
3686                 if (!in_escape && *p == '&') {
3687                         g_string_append(to_str, "&-");
3688                 } else if (!in_escape && *p == '+') {
3689                         if (*(p + 1) == '-') {
3690                                 g_string_append_c(to_str, '+');
3691                                 p++;
3692                         } else {
3693                                 g_string_append_c(to_str, '&');
3694                                 in_escape = TRUE;
3695                         }
3696                 } else if (in_escape && *p == '/') {
3697                         g_string_append_c(to_str, ',');
3698                 } else if (in_escape && *p == '-') {
3699                         g_string_append_c(to_str, '-');
3700                         in_escape = FALSE;
3701                 } else {
3702                         g_string_append_c(to_str, *p);
3703                 }
3704         }
3705
3706         if (in_escape) {
3707                 in_escape = FALSE;
3708                 g_string_append_c(to_str, '-');
3709         }
3710
3711         to = to_str->str;
3712         g_string_free(to_str, FALSE);
3713
3714         return to;
3715 }
3716
3717 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
3718 {
3719         FolderItem *item = node->data;
3720         gchar **paths = data;
3721         const gchar *oldpath = paths[0];
3722         const gchar *newpath = paths[1];
3723         gchar *real_oldpath, *real_newpath;
3724         gchar *base;
3725         gchar *new_itempath;
3726         gint oldpathlen;
3727         IMAPSession *session = imap_session_get(item->folder);
3728
3729         oldpathlen = strlen(oldpath);
3730         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3731                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3732                 return TRUE;
3733         }
3734
3735         base = item->path + oldpathlen;
3736         while (*base == G_DIR_SEPARATOR) base++;
3737         if (*base == '\0')
3738                 new_itempath = g_strdup(newpath);
3739         else
3740                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3741                                            NULL);
3742
3743         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path);
3744         g_free(item->path);
3745         item->path = new_itempath;
3746         
3747         real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path);
3748         
3749         imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
3750         imap_threaded_subscribe(item->folder, real_newpath, TRUE);
3751
3752         g_free(real_oldpath);
3753         g_free(real_newpath);
3754         return FALSE;
3755 }
3756
3757 static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
3758 {
3759         GSList *uidlist, *elem;
3760         int r = -1;
3761         clist * lep_uidlist;
3762         gint ok, nummsgs = 0, lastuid_old;
3763
3764         if (session == NULL) {
3765                 return -1;
3766         }
3767
3768         ok = imap_select(session, IMAP_FOLDER(folder), item->item.path,
3769                          NULL, NULL, NULL, NULL, TRUE);
3770         if (ok != MAILIMAP_NO_ERROR) {
3771                 return -1;
3772         }
3773
3774         g_slist_free(item->uid_list);
3775         item->uid_list = NULL;
3776
3777         uidlist = NULL;
3778         
3779         if (folder->account && folder->account->low_bandwidth) {
3780                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE, NULL,
3781                                  &lep_uidlist);
3782         }
3783         
3784         if (r == MAILIMAP_NO_ERROR) {
3785                 GSList * fetchuid_list =
3786                         imap_uid_list_from_lep(lep_uidlist);
3787                 mailimap_search_result_free(lep_uidlist);
3788                 
3789                 uidlist = g_slist_concat(fetchuid_list, uidlist);
3790         } else {
3791                 carray * lep_uidtab;
3792                 if (r != -1) /* inited */
3793                         imap_handle_error(SESSION(session), r);
3794                 r = imap_threaded_fetch_uid(folder, 1,
3795                                     &lep_uidtab);
3796                 if (r == MAILIMAP_NO_ERROR) {
3797                         GSList * fetchuid_list =
3798                                 imap_uid_list_from_lep_tab(lep_uidtab);
3799                         imap_fetch_uid_list_free(lep_uidtab);
3800                         uidlist = g_slist_concat(fetchuid_list, uidlist);
3801                 }
3802         }
3803         
3804         if (r != MAILIMAP_NO_ERROR) {
3805                 imap_handle_error(SESSION(session), r);
3806                 return -1;
3807         }
3808
3809         lastuid_old = item->lastuid;
3810
3811         for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
3812                 guint msgnum;
3813
3814                 msgnum = GPOINTER_TO_INT(elem->data);
3815
3816                 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
3817                 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
3818                 nummsgs++;
3819         }
3820         g_slist_free(uidlist);
3821
3822         unlock_session(session); /* locked from imap_get_num_list */
3823
3824         return nummsgs;
3825
3826 }
3827
3828 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)
3829 {
3830         IMAPFolderItem *item = (IMAPFolderItem *)_item;
3831         IMAPSession *session;
3832         gint nummsgs;
3833         GSList *uidlist = NULL;
3834         gchar *dir;
3835         gboolean selected_folder;
3836         gint known_list_len = 0;
3837         debug_print("get_num_list\n");
3838         
3839         g_return_val_if_fail(folder != NULL, -1);
3840         g_return_val_if_fail(item != NULL, -1);
3841         g_return_val_if_fail(item->item.path != NULL, -1);
3842         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
3843         g_return_val_if_fail(folder->account != NULL, -1);
3844
3845         known_list_len = g_slist_length(item->uid_list);
3846         if (!item->should_update) {
3847                 debug_print("get_num_list: nothing to update\n");
3848                 *old_uids_valid = TRUE;
3849                 if (known_list_len == item->item.total_msgs
3850                  && known_list_len > 0) {
3851                         *msgnum_list = g_slist_copy(item->uid_list);
3852                         return known_list_len;
3853                 } else {
3854                         debug_print("don't know the list length...\n");
3855                 }
3856         }
3857
3858         if (prefs_common.work_offline && 
3859             !inc_offline_should_override(FALSE,
3860                 _("Claws Mail needs network access in order "
3861                   "to access the IMAP server."))) {
3862                 return -1;
3863         }
3864         
3865         debug_print("getting session...\n");
3866         session = imap_session_get(folder);
3867         g_return_val_if_fail(session != NULL, -1);
3868
3869         lock_session(session); /* unlocked by get_list_of_uids */
3870         if (FOLDER_ITEM(item)->path) 
3871                 statusbar_print_all(_("Scanning folder %s%c%s ..."),
3872                                       FOLDER_ITEM(item)->folder->name, 
3873                                       G_DIR_SEPARATOR,
3874                                       FOLDER_ITEM(item)->path);
3875         else
3876                 statusbar_print_all(_("Scanning folder %s ..."),
3877                                       FOLDER_ITEM(item)->folder->name);
3878
3879         selected_folder = (session->mbox != NULL) &&
3880                           (!strcmp(session->mbox, item->item.path));
3881         
3882         if (item->should_trash_cache) {
3883                 *old_uids_valid = FALSE;
3884                 debug_print("get_num_list: trashing num list\n");
3885                 debug_print("Freeing imap uid cache\n");
3886                 item->lastuid = 0;
3887                 g_slist_free(item->uid_list);
3888                 item->uid_list = NULL;
3889
3890                 imap_delete_all_cached_messages((FolderItem *)item);
3891         } else {
3892                 debug_print("get_num_list: updating num list\n");
3893                 *old_uids_valid = TRUE;
3894         }
3895
3896         nummsgs = get_list_of_uids(session, folder, item, &uidlist);
3897         /* session could be broken now, in case of fatal error */
3898
3899         debug_print("get_num_list: got %d msgs\n", nummsgs);
3900
3901         if (nummsgs < 0) {
3902                 statusbar_pop_all();
3903                 return -1;
3904         }
3905
3906         *msgnum_list = uidlist;
3907
3908         dir = folder_item_get_path((FolderItem *)item);
3909         debug_print("removing old messages from %s\n", dir);
3910         remove_numbered_files_not_in_list(dir, *msgnum_list);
3911         g_free(dir);
3912         
3913         debug_print("get_num_list - ok - %i\n", nummsgs);
3914         statusbar_pop_all();
3915         item->should_trash_cache = FALSE;
3916         item->should_update = FALSE;
3917         return nummsgs;
3918 }
3919
3920 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item)
3921 {
3922         MsgInfo *msginfo;
3923         MsgFlags flags;
3924
3925         flags.perm_flags = MSG_NEW|MSG_UNREAD;
3926         flags.tmp_flags = 0;
3927
3928         g_return_val_if_fail(item != NULL, NULL);
3929         g_return_val_if_fail(file != NULL, NULL);
3930
3931         if (folder_has_parent_of_type(item, F_QUEUE)) {
3932                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
3933         } else if (folder_has_parent_of_type(item, F_DRAFT)) {
3934                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
3935         }
3936
3937         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
3938         if (!msginfo) return NULL;
3939         
3940         msginfo->plaintext_file = g_strdup(file);
3941         msginfo->folder = item;
3942
3943         return msginfo;
3944 }
3945
3946 GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
3947                           GSList *msgnum_list)
3948 {
3949         IMAPSession *session;
3950         MsgInfoList *ret = NULL;
3951         gint ok;
3952         
3953         debug_print("get_msginfos\n");
3954         
3955         g_return_val_if_fail(folder != NULL, NULL);
3956         g_return_val_if_fail(item != NULL, NULL);
3957         g_return_val_if_fail(msgnum_list != NULL, NULL);
3958
3959         debug_print("getting session...\n");
3960         session = imap_session_get(folder);
3961         g_return_val_if_fail(session != NULL, NULL);
3962
3963         lock_session(session); /* unlocked later in the function */
3964
3965         debug_print("IMAP getting msginfos\n");
3966         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
3967                          NULL, NULL, NULL, NULL, FALSE);
3968         if (ok != MAILIMAP_NO_ERROR) {
3969                 return NULL;
3970         }
3971         if (!(folder_has_parent_of_type(item, F_DRAFT) || 
3972               folder_has_parent_of_type(item, F_QUEUE))) {
3973                 ret = g_slist_concat(ret,
3974                         imap_get_uncached_messages(session, item,
3975                                                    msgnum_list, &ok));
3976                 if (ok != MAILIMAP_NO_ERROR)
3977                         return NULL;
3978                 unlock_session(session);
3979         } else {
3980                 MsgNumberList *sorted_list, *elem, *llast = NULL;
3981                 gint startnum, lastnum;
3982         
3983                 unlock_session(session);
3984
3985                 sorted_list = g_slist_sort(g_slist_copy(msgnum_list), g_int_compare);
3986
3987                 startnum = lastnum = GPOINTER_TO_INT(sorted_list->data);
3988
3989                 llast = g_slist_last(ret);
3990                 for (elem = sorted_list;; elem = g_slist_next(elem)) {
3991                         guint num = 0;
3992
3993                         if (elem)
3994                                 num = GPOINTER_TO_INT(elem->data);
3995
3996                         if (num > lastnum + 1 || elem == NULL) {
3997                                 int i;
3998                                 for (i = startnum; i <= lastnum; ++i) {
3999                                         gchar *file;
4000                                         file = imap_fetch_msg(folder, item, i);
4001                                         if (file != NULL) {
4002                                                 MsgInfo *msginfo = imap_parse_msg(file, item);
4003                                                 if (msginfo != NULL) {
4004                                                         msginfo->msgnum = i;
4005                                                         if (llast == NULL)
4006                                                                 llast = ret = g_slist_append(ret, msginfo);
4007                                                         else {
4008                                                                 llast = g_slist_append(llast, msginfo);
4009                                                                 llast = llast->next;
4010                                                         }
4011                                                 }
4012                                                 g_free(file);
4013                                         }
4014                                 }
4015
4016                                 if (elem == NULL)
4017                                         break;
4018
4019                                 startnum = num;
4020                         }
4021                         lastnum = num;
4022                 }
4023
4024                 g_slist_free(sorted_list);
4025         }
4026         return ret;
4027 }
4028
4029 MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
4030 {
4031         MsgInfo *msginfo = NULL;
4032         MsgInfoList *msginfolist;
4033         MsgNumberList numlist;
4034
4035         numlist.next = NULL;
4036         numlist.data = GINT_TO_POINTER(uid);
4037
4038         msginfolist = imap_get_msginfos(folder, item, &numlist);
4039         if (msginfolist != NULL) {
4040                 msginfo = msginfolist->data;
4041                 g_slist_free(msginfolist);
4042         }
4043
4044         return msginfo;
4045 }
4046
4047 gboolean imap_scan_required(Folder *folder, FolderItem *_item)
4048 {
4049         IMAPSession *session;
4050         IMAPFolderItem *item = (IMAPFolderItem *)_item;
4051         gint ok, exists = 0, unseen = 0;
4052         guint32 uid_next = 0, uid_val = 0;
4053         gboolean selected_folder;
4054         
4055         g_return_val_if_fail(folder != NULL, FALSE);
4056         g_return_val_if_fail(item != NULL, FALSE);
4057         g_return_val_if_fail(item->item.folder != NULL, FALSE);
4058         g_return_val_if_fail(FOLDER_CLASS(item->item.folder) == &imap_class, FALSE);
4059
4060         if (item->item.path == NULL)
4061                 return FALSE;
4062
4063         if (item->should_update) {
4064                 debug_print("scan already required\n");
4065                 return TRUE;
4066         }
4067         debug_print("getting session...\n");
4068         session = imap_session_get(folder);
4069         
4070         g_return_val_if_fail(session != NULL, FALSE);
4071         lock_session(session); /* unlocked later in the function */
4072
4073         selected_folder = (session->mbox != NULL) &&
4074                           (!strcmp(session->mbox, item->item.path));
4075         if (selected_folder) {
4076                 if (!session->folder_content_changed) {
4077                         ok = imap_cmd_noop(session);
4078                         if (ok != MAILIMAP_NO_ERROR) {
4079                                 debug_print("disconnected!\n");
4080                                 if (!is_fatal(ok))
4081                                         session = imap_reconnect_if_possible(folder, session);
4082                                 else
4083                                         session = imap_session_get(folder);
4084                                 if (session == NULL)
4085                                         return FALSE;
4086                         }
4087
4088                         if (session->folder_content_changed) {
4089                                 debug_print("CHANGED (self-noop)! scan_required\n");
4090                                 item->should_update = TRUE;
4091                                 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4092                                         item->item.mtime = session->uid_validity;
4093                                         item->should_trash_cache = TRUE;
4094                                 }
4095                                 unlock_session(session);
4096                                 return TRUE;
4097                         }
4098                 } else {
4099                         debug_print("CHANGED (previous noop)! scan_required\n");
4100                         item->should_update = TRUE;
4101                         if (session->uid_validity && session->uid_validity != item->item.mtime) {
4102                                 item->item.mtime = session->uid_validity;
4103                                 item->should_trash_cache = TRUE;
4104                         }
4105                         unlock_session(session);
4106                         return TRUE;
4107                 }
4108         } else {
4109                 ok = imap_status(session, IMAP_FOLDER(folder), item->item.path, IMAP_FOLDER_ITEM(item),
4110                                  &exists, &uid_next, &uid_val, &unseen, FALSE);
4111                 if (ok != MAILIMAP_NO_ERROR) {
4112                         return FALSE;
4113                 }
4114                 
4115                 debug_print("exists %d, item->item.total_msgs %d\n", 
4116                         exists, item->item.total_msgs);
4117                 if (exists != item->item.total_msgs
4118                     || unseen != item->item.unread_msgs 
4119                     || uid_next != item->uid_next
4120                     || uid_val != item->item.mtime) {
4121                         debug_print("CHANGED (status)! scan_required\n");
4122                         item->last_change = time(NULL);
4123                         item->should_update = TRUE;
4124                         item->uid_next = uid_next;
4125                         if (uid_val != item->item.mtime) {
4126                                 item->item.mtime = uid_val;
4127                                 item->should_trash_cache = TRUE;
4128                         }
4129                         unlock_session(session);
4130                         return TRUE;
4131                 }
4132         }
4133         unlock_session(session);
4134
4135         item->should_update = FALSE;
4136         return FALSE;
4137 }
4138
4139 void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
4140 {
4141         IMAPSession *session;
4142         IMAPFlags flags_set = 0, flags_unset = 0;
4143         gint ok = MAILIMAP_NO_ERROR;
4144         MsgNumberList numlist;
4145         hashtable_data *ht_data = NULL;
4146
4147         g_return_if_fail(folder != NULL);
4148         g_return_if_fail(folder->klass == &imap_class);
4149         g_return_if_fail(item != NULL);
4150         g_return_if_fail(item->folder == folder);
4151         g_return_if_fail(msginfo != NULL);
4152         g_return_if_fail(msginfo->folder == item);
4153
4154         if (!MSG_IS_MARKED(msginfo->flags) &&  (newflags & MSG_MARKED))
4155                 flags_set |= IMAP_FLAG_FLAGGED;
4156         if ( MSG_IS_MARKED(msginfo->flags) && !(newflags & MSG_MARKED))
4157                 flags_unset |= IMAP_FLAG_FLAGGED;
4158
4159         if (!MSG_IS_UNREAD(msginfo->flags) &&  (newflags & MSG_UNREAD))
4160                 flags_unset |= IMAP_FLAG_SEEN;
4161         if ( MSG_IS_UNREAD(msginfo->flags) && !(newflags & MSG_UNREAD))
4162                 flags_set |= IMAP_FLAG_SEEN;
4163
4164         if (!MSG_IS_REPLIED(msginfo->flags) &&  (newflags & MSG_REPLIED))
4165                 flags_set |= IMAP_FLAG_ANSWERED;
4166         if ( MSG_IS_REPLIED(msginfo->flags) && !(newflags & MSG_REPLIED))
4167                 flags_unset |= IMAP_FLAG_ANSWERED;
4168
4169         if (!MSG_IS_DELETED(msginfo->flags) &&  (newflags & MSG_DELETED))
4170                 flags_set |= IMAP_FLAG_DELETED;
4171         if ( MSG_IS_DELETED(msginfo->flags) && !(newflags & MSG_DELETED))
4172                 flags_unset |= IMAP_FLAG_DELETED;
4173
4174         if (!flags_set && !flags_unset) {
4175                 /* the changed flags were not translatable to IMAP-speak.
4176                  * like MSG_POSTFILTERED, so just apply. */
4177                 msginfo->flags.perm_flags = newflags;
4178                 return;
4179         }
4180
4181         debug_print("getting session...\n");
4182         session = imap_session_get(folder);
4183         if (!session) {
4184                 return;
4185         }
4186
4187         if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
4188             NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
4189                 return;
4190         }
4191         numlist.next = NULL;
4192         numlist.data = GINT_TO_POINTER(msginfo->msgnum);
4193
4194         if (IMAP_FOLDER_ITEM(item)->batching) {
4195                 /* instead of performing an UID STORE command for each message change,
4196                  * as a lot of them can change "together", we just fill in hashtables
4197                  * and defer the treatment so that we're able to send only one
4198                  * command.
4199                  */
4200                 debug_print("IMAP batch mode on, deferring flags change\n");
4201                 if (flags_set) {
4202                         ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_set_table, 
4203                                 GINT_TO_POINTER(flags_set));
4204                         if (ht_data == NULL) {
4205                                 ht_data = g_new0(hashtable_data, 1);
4206                                 ht_data->item = IMAP_FOLDER_ITEM(item);
4207                                 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_set_table, 
4208                                         GINT_TO_POINTER(flags_set), ht_data);
4209                         }
4210                         ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
4211                 } 
4212                 if (flags_unset) {
4213                         ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_unset_table, 
4214                                 GINT_TO_POINTER(flags_unset));
4215                         if (ht_data == NULL) {
4216                                 ht_data = g_new0(hashtable_data, 1);
4217                                 ht_data->item = IMAP_FOLDER_ITEM(item);
4218                                 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_unset_table, 
4219                                         GINT_TO_POINTER(flags_unset), ht_data);
4220                         }
4221                         ht_data->msglist = g_slist_prepend(ht_data->msglist, 
4222                                         GINT_TO_POINTER(msginfo->msgnum));              
4223                 }
4224         } else {
4225                 debug_print("IMAP changing flags\n");
4226                 if (flags_set) {
4227                         ok = imap_set_message_flags(session, &numlist, flags_set, TRUE);
4228                         if (ok != MAILIMAP_NO_ERROR) {
4229                                 return;
4230                         }
4231                 }
4232
4233                 if (flags_unset) {
4234                         ok = imap_set_message_flags(session, &numlist, flags_unset, FALSE);
4235                         if (ok != MAILIMAP_NO_ERROR) {
4236                                 return;
4237                         }
4238                 }
4239         }
4240         msginfo->flags.perm_flags = newflags;
4241         return;
4242 }
4243
4244 static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
4245 {
4246         gint ok;
4247         IMAPSession *session;
4248         gchar *dir;
4249         MsgNumberList numlist;
4250         
4251         g_return_val_if_fail(folder != NULL, -1);
4252         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
4253         g_return_val_if_fail(item != NULL, -1);
4254
4255         debug_print("getting session...\n");
4256         session = imap_session_get(folder);
4257         if (!session) return -1;
4258
4259         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
4260                          NULL, NULL, NULL, NULL, FALSE);
4261         if (ok != MAILIMAP_NO_ERROR) {
4262                 return ok;
4263         }
4264         numlist.next = NULL;
4265         numlist.data = GINT_TO_POINTER(uid);
4266         
4267         ok = imap_set_message_flags
4268                 (session, &numlist, IMAP_FLAG_DELETED, TRUE);
4269         if (ok != MAILIMAP_NO_ERROR) {
4270                 log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
4271                 return ok;
4272         }
4273
4274         if (!session->uidplus) {
4275                 ok = imap_cmd_expunge(session);
4276         } else {
4277                 gchar *uidstr;
4278
4279                 uidstr = g_strdup_printf("%u", uid);
4280                 ok = imap_cmd_expunge(session);
4281                 g_free(uidstr);
4282         }
4283         if (ok != MAILIMAP_NO_ERROR) {
4284                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
4285                 return ok;
4286         }
4287
4288         IMAP_FOLDER_ITEM(item)->uid_list = g_slist_remove(
4289             IMAP_FOLDER_ITEM(item)->uid_list, numlist.data);
4290         dir = folder_item_get_path(item);
4291         if (is_dir_exist(dir))
4292                 remove_numbered_files(dir, uid, uid);
4293         g_free(dir);
4294         return MAILIMAP_NO_ERROR;
4295 }
4296
4297 static gint compare_msginfo(gconstpointer a, gconstpointer b)
4298 {
4299         return ((MsgInfo *)a)->msgnum - ((MsgInfo *)b)->msgnum;
4300 }
4301
4302 static guint gslist_find_next_num(MsgNumberList **list, guint num)
4303 {
4304         GSList *elem;
4305
4306         g_return_val_if_fail(list != NULL, -1);
4307
4308         for (elem = *list; elem != NULL; elem = g_slist_next(elem))
4309                 if (GPOINTER_TO_INT(elem->data) >= num)
4310                         break;
4311         *list = elem;
4312         return elem != NULL ? GPOINTER_TO_INT(elem->data) : (gint)-1;
4313 }
4314
4315 /*
4316  * NEW and DELETED flags are not syncronized
4317  * - The NEW/RECENT flags in IMAP folders can not really be directly
4318  *   modified by Sylpheed
4319  * - The DELETE/DELETED flag in IMAP and Sylpheed don't have the same
4320  *   meaning, in IMAP it always removes the messages from the FolderItem
4321  *   in Sylpheed it can mean to move the message to trash
4322  */
4323
4324 typedef struct _get_flags_data {
4325         Folder *folder;
4326         FolderItem *item;
4327         MsgInfoList *msginfo_list;
4328         GRelation *msgflags;
4329         gboolean full_search;
4330         gboolean done;
4331 } get_flags_data;
4332
4333 static /*gint*/ void *imap_get_flags_thread(void *data)
4334 {
4335         get_flags_data *stuff = (get_flags_data *)data;
4336         Folder *folder = stuff->folder;
4337         FolderItem *fitem = (FolderItem *) stuff->item;
4338         MsgInfoList *msginfo_list = stuff->msginfo_list;
4339         GRelation *msgflags = stuff->msgflags;
4340         GSList *elem;
4341         carray * lep_uidtab;
4342         IMAPSession *session;
4343         gint ok;
4344         int r = MAILIMAP_NO_ERROR;
4345         GHashTable *flags_hash = NULL;
4346         gboolean full_search = stuff->full_search;
4347         GSList *sorted_list = NULL;
4348         GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL;
4349         GSList *p_unseen, *p_answered, *p_flagged, *p_deleted;
4350         GSList *seq_list, *cur;
4351         gboolean reverse_seen = FALSE;
4352         gboolean selected_folder;
4353         gint exists_cnt, unseen_cnt;
4354         
4355         session = imap_session_get(folder);
4356
4357         if (session == NULL) {
4358                 stuff->done = TRUE;
4359                 return GINT_TO_POINTER(-1);
4360         }
4361         selected_folder = (session->mbox != NULL) &&
4362                           (!strcmp(session->mbox, fitem->path));
4363
4364         lock_session(session);
4365         if (!selected_folder) {
4366                 ok = imap_select(session, IMAP_FOLDER(folder), fitem->path,
4367                         &exists_cnt, NULL, &unseen_cnt, NULL, TRUE);
4368                 if (ok != MAILIMAP_NO_ERROR) {
4369                         stuff->done = TRUE;
4370                         return GINT_TO_POINTER(-1);
4371                 }
4372
4373                 if (unseen_cnt > exists_cnt / 2)
4374                         reverse_seen = TRUE;
4375         } 
4376         else {
4377                 if (fitem->unread_msgs > fitem->total_msgs / 2)
4378                         reverse_seen = TRUE;
4379         }
4380
4381         sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
4382         if (!full_search) {
4383                 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msginfo_list);
4384         } else {
4385                 struct mailimap_set * set;
4386                 set = mailimap_set_new_interval(1, 0);
4387                 seq_list = g_slist_append(NULL, set);
4388         }
4389
4390         if (folder->account && folder->account->low_bandwidth) {
4391                 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
4392                         struct mailimap_set * imapset;
4393                         clist * lep_uidlist;
4394                         int r;
4395
4396                         imapset = cur->data;
4397                         if (reverse_seen) {
4398                                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN,
4399                                                          full_search ? NULL:imapset, &lep_uidlist);
4400                         }
4401                         else {
4402                                 r = imap_threaded_search(folder,
4403                                                          IMAP_SEARCH_TYPE_UNSEEN,
4404                                                          full_search ? NULL:imapset, &lep_uidlist);
4405                         }
4406                         if (r == MAILIMAP_NO_ERROR) {
4407                                 GSList * uidlist;
4408
4409                                 uidlist = imap_uid_list_from_lep(lep_uidlist);
4410                                 mailimap_search_result_free(lep_uidlist);
4411
4412                                 unseen = g_slist_concat(unseen, uidlist);
4413                         } else {
4414                                 imap_handle_error(SESSION(session), r);
4415                                 goto bail;
4416                         }
4417
4418                         r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED,
4419                                                  full_search ? NULL:imapset, &lep_uidlist);
4420                         if (r == MAILIMAP_NO_ERROR) {
4421                                 GSList * uidlist;
4422
4423                                 uidlist = imap_uid_list_from_lep(lep_uidlist);
4424                                 mailimap_search_result_free(lep_uidlist);
4425
4426                                 flagged = g_slist_concat(flagged, uidlist);
4427                         } else {
4428                                 imap_handle_error(SESSION(session), r);
4429                                 goto bail;
4430                         }
4431
4432                         if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
4433                                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED,
4434                                                          full_search ? NULL:imapset, &lep_uidlist);
4435                                 if (r == MAILIMAP_NO_ERROR) {
4436                                         GSList * uidlist;
4437
4438                                         uidlist = imap_uid_list_from_lep(lep_uidlist);
4439                                         mailimap_search_result_free(lep_uidlist);
4440
4441                                         answered = g_slist_concat(answered, uidlist);
4442                                 } else {
4443                                         imap_handle_error(SESSION(session), r);
4444                                         goto bail;
4445                                 }
4446
4447                                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED,
4448                                                          full_search ? NULL:imapset, &lep_uidlist);
4449                                 if (r == MAILIMAP_NO_ERROR) {
4450                                         GSList * uidlist;
4451
4452                                         uidlist = imap_uid_list_from_lep(lep_uidlist);
4453                                         mailimap_search_result_free(lep_uidlist);
4454
4455                                         deleted = g_slist_concat(deleted, uidlist);
4456                                 } else {
4457                                         imap_handle_error(SESSION(session), r);
4458                                         goto bail;
4459                                 }
4460                         }
4461                 }
4462                 p_unseen = unseen;
4463                 p_answered = answered;
4464                 p_flagged = flagged;
4465                 p_deleted = deleted;
4466
4467         } else {
4468                 r = imap_threaded_fetch_uid_flags(folder, 1, &lep_uidtab);
4469                 if (r == MAILIMAP_NO_ERROR) {
4470                         flags_hash = g_hash_table_new_full(g_int_hash, g_int_equal, free, NULL);
4471                         imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash);
4472                         imap_fetch_uid_flags_list_free(lep_uidtab);
4473                 } else {
4474                         imap_handle_error(SESSION(session), r);
4475                         goto bail;
4476                 }
4477         }
4478
4479 bail:
4480         if (r == MAILIMAP_NO_ERROR)
4481                 unlock_session(session);
4482         
4483         for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
4484                 MsgInfo *msginfo;
4485                 MsgPermFlags flags, oldflags;
4486                 gboolean wasnew;
4487
4488                 msginfo = (MsgInfo *) elem->data;
4489                 flags = msginfo->flags.perm_flags;
4490                 wasnew = (flags & MSG_NEW);
4491                 oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_MARKED|MSG_DELETED);
4492
4493                 if (folder->account && folder->account->low_bandwidth) {
4494                         if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
4495                                 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_MARKED);
4496                         } else {
4497                                 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW | MSG_MARKED));
4498                         }
4499                         if (reverse_seen)
4500                                 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
4501                         if (gslist_find_next_num(&p_unseen, msginfo->msgnum) == msginfo->msgnum) {
4502                                 if (!reverse_seen) {
4503                                         flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
4504                                 } else {
4505                                         flags &= ~(MSG_UNREAD | MSG_NEW);
4506                                 }
4507                         }
4508
4509                         if (gslist_find_next_num(&p_flagged, msginfo->msgnum) == msginfo->msgnum)
4510                                 flags |= MSG_MARKED;
4511                         else
4512                                 flags &= ~MSG_MARKED;
4513
4514                         if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
4515                                 if (gslist_find_next_num(&p_answered, msginfo->msgnum) == msginfo->msgnum)
4516                                         flags |= MSG_REPLIED;
4517                                 else
4518                                         flags &= ~MSG_REPLIED;
4519                                 if (gslist_find_next_num(&p_deleted, msginfo->msgnum) == msginfo->msgnum)
4520                                         flags |= MSG_DELETED;
4521                                 else
4522                                         flags &= ~MSG_DELETED;
4523                         }
4524                 } else {
4525                         if (flags_hash != NULL) {
4526                                 gint * puid;
4527
4528                                 puid = malloc(sizeof(* puid));
4529                                 * puid = msginfo->msgnum;
4530
4531                                 flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash, puid));
4532                                 free(puid);
4533                         }
4534
4535                         if ((flags & MSG_UNREAD) == 0)
4536                                 flags &= ~MSG_NEW;
4537                         else if (wasnew)
4538                                 flags |= MSG_NEW;
4539                         flags |= oldflags;
4540                 }
4541
4542                 g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
4543         }
4544         
4545         if (flags_hash)
4546                 g_hash_table_destroy(flags_hash);
4547
4548         imap_lep_set_free(seq_list);
4549         g_slist_free(flagged);
4550         g_slist_free(deleted);
4551         g_slist_free(answered);
4552         g_slist_free(unseen);
4553         g_slist_free(sorted_list);
4554
4555         stuff->done = TRUE;
4556         return GINT_TO_POINTER(0);
4557 }
4558
4559 static gint imap_get_flags(Folder *folder, FolderItem *item,
4560                            MsgInfoList *msginfo_list, GRelation *msgflags)
4561 {
4562         gint result;
4563         get_flags_data *data = g_new0(get_flags_data, 1);
4564         data->done = FALSE;
4565         data->folder = folder;
4566         data->item = item;
4567         data->msginfo_list = msginfo_list;
4568         data->msgflags = msgflags;
4569         data->full_search = FALSE;
4570
4571         GSList *tmp = NULL, *cur;
4572         
4573         if (prefs_common.work_offline && 
4574             !inc_offline_should_override(FALSE,
4575                 _("Claws Mail needs network access in order "
4576                   "to access the IMAP server."))) {
4577                 g_free(data);
4578                 return -1;
4579         }
4580
4581         tmp = folder_item_get_msg_list(item);
4582
4583         if (g_slist_length(tmp) <= g_slist_length(msginfo_list))
4584                 data->full_search = TRUE;
4585         
4586         for (cur = tmp; cur; cur = cur->next)
4587                 procmsg_msginfo_free((MsgInfo *)cur->data);
4588         
4589         g_slist_free(tmp);
4590
4591         result = GPOINTER_TO_INT(imap_get_flags_thread(data));
4592         
4593         g_free(data);
4594         return result;
4595
4596 }
4597
4598 static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
4599 {
4600         gboolean flags_set = GPOINTER_TO_INT(user_data);
4601         gint flags_value = GPOINTER_TO_INT(key);
4602         hashtable_data *data = (hashtable_data *)value;
4603         IMAPFolderItem *_item = data->item;
4604         FolderItem *item = (FolderItem *)_item;
4605         gint ok = MAILIMAP_ERROR_BAD_STATE;
4606         IMAPSession *session = NULL;
4607         
4608         debug_print("getting session...\n");
4609         session = imap_session_get(item->folder);
4610
4611         data->msglist = g_slist_reverse(data->msglist);
4612         
4613         debug_print("IMAP %ssetting flags to %d for %d messages\n",
4614                 flags_set?"":"un",
4615                 flags_value,
4616                 g_slist_length(data->msglist));
4617         
4618         lock_session(session);
4619         if (session) {
4620                 ok = imap_select(session, IMAP_FOLDER(item->folder), item->path,
4621                          NULL, NULL, NULL, NULL, FALSE);
4622         }
4623         if (ok == MAILIMAP_NO_ERROR) {
4624                 ok = imap_set_message_flags(session, data->msglist, flags_value, flags_set);
4625         } else {
4626                 g_warning("can't select mailbox %s\n", item->path);
4627         }
4628
4629         if (!is_fatal(ok))
4630                 unlock_session(session);
4631
4632         g_slist_free(data->msglist);    
4633         g_free(data);
4634         return TRUE;
4635 }
4636
4637 static void process_hashtable(IMAPFolderItem *item)
4638 {
4639         if (item->flags_set_table) {
4640                 g_hash_table_foreach_remove(item->flags_set_table, process_flags, GINT_TO_POINTER(TRUE));
4641                 g_hash_table_destroy(item->flags_set_table);
4642                 item->flags_set_table = NULL;
4643         }
4644         if (item->flags_unset_table) {
4645                 g_hash_table_foreach_remove(item->flags_unset_table, process_flags, GINT_TO_POINTER(FALSE));
4646                 g_hash_table_destroy(item->flags_unset_table);
4647                 item->flags_unset_table = NULL;
4648         }
4649         
4650 }
4651
4652 static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
4653 {
4654         IMAPFolderItem *item = (IMAPFolderItem *)_item;
4655         IMAPSession *session;
4656
4657         g_return_if_fail(item != NULL);
4658         
4659         if (item->batching == batch)
4660                 return;
4661         
4662         if (batch) {
4663                 item->batching = TRUE;
4664                 debug_print("IMAP switching to batch mode\n");
4665                 if (!item->flags_set_table) {
4666                         item->flags_set_table = g_hash_table_new(NULL, g_direct_equal);
4667                 }
4668                 if (!item->flags_unset_table) {
4669                         item->flags_unset_table = g_hash_table_new(NULL, g_direct_equal);
4670                 }
4671                 session = imap_session_get(folder);
4672                 if (session) {
4673                         imap_refresh_sensitivity(session);
4674                         session->sens_update_block = TRUE;
4675                 }
4676         } else {
4677                 debug_print("IMAP switching away from batch mode\n");
4678                 /* process stuff */
4679                 process_hashtable(item);
4680                 item->batching = FALSE;
4681                 session = imap_session_get(folder);
4682                 if (session) {
4683                         session->sens_update_block = FALSE;
4684                         imap_refresh_sensitivity(session);
4685                 }
4686         }
4687 }
4688
4689
4690
4691 /* data types conversion libetpan <-> claws */
4692
4693
4694
4695 #define ETPAN_IMAP_MB_MARKED      1
4696 #define ETPAN_IMAP_MB_UNMARKED    2
4697 #define ETPAN_IMAP_MB_NOSELECT    4
4698 #define ETPAN_IMAP_MB_NOINFERIORS 8
4699
4700 static int imap_flags_to_flags(struct mailimap_mbx_list_flags * imap_flags)
4701 {
4702   int flags;
4703   clistiter * cur;
4704   
4705   flags = 0;
4706   if (imap_flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
4707     switch (imap_flags->mbf_sflag) {
4708     case MAILIMAP_MBX_LIST_SFLAG_MARKED:
4709       flags |= ETPAN_IMAP_MB_MARKED;
4710       break;
4711     case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
4712       flags |= ETPAN_IMAP_MB_NOSELECT;
4713       break;
4714     case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
4715       flags |= ETPAN_IMAP_MB_UNMARKED;
4716       break;
4717     }
4718   }
4719   
4720   for(cur = clist_begin(imap_flags->mbf_oflags) ; cur != NULL ;
4721       cur = clist_next(cur)) {
4722     struct mailimap_mbx_list_oflag * oflag;
4723     
4724     oflag = clist_content(cur);
4725     
4726     switch (oflag->of_type) {
4727     case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
4728       flags |= ETPAN_IMAP_MB_NOINFERIORS;
4729       break;
4730     }
4731   }
4732   
4733   return flags;
4734 }
4735
4736 static GSList * imap_list_from_lep(IMAPFolder * folder,
4737                                    clist * list, const gchar * real_path, gboolean all)
4738 {
4739         clistiter * iter;
4740         GSList * item_list = NULL, *llast = NULL;
4741         
4742         for(iter = clist_begin(list) ; iter != NULL ;
4743             iter = clist_next(iter)) {
4744                 struct mailimap_mailbox_list * mb;
4745                 int flags;
4746                 char delimiter;
4747                 char * name;
4748                 char * dup_name;
4749                 gchar * base;
4750                 gchar * loc_name;
4751                 gchar * loc_path;
4752                 FolderItem *new_item;
4753                 
4754                 mb = clist_content(iter);
4755
4756                 if (mb == NULL)
4757                         continue;
4758
4759                 flags = 0;
4760                 if (mb->mb_flag != NULL)
4761                         flags = imap_flags_to_flags(mb->mb_flag);
4762                 
4763                 delimiter = mb->mb_delimiter;
4764                 name = mb->mb_name;
4765                 
4766                 dup_name = strdup(name);                
4767                 if (delimiter != '\0')
4768                         subst_char(dup_name, delimiter, '/');
4769                 
4770                 base = g_path_get_basename(dup_name);
4771                 if (base[0] == '.') {
4772                         g_free(base);
4773                         free(dup_name);
4774                         continue;
4775                 }
4776                 if (!all && path_cmp(name, real_path) == 0) {
4777                         g_free(base);
4778                         free(dup_name);
4779                         continue;
4780                 }
4781
4782                 if (!all && dup_name[strlen(dup_name)-1] == '/') {
4783                         dup_name[strlen(dup_name)-1] = '\0';
4784                 }
4785                 
4786                 loc_name = imap_modified_utf7_to_utf8(base);
4787                 loc_path = imap_modified_utf7_to_utf8(dup_name);
4788                 
4789                 new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
4790                 if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
4791                         new_item->no_sub = TRUE;
4792                 if (strcmp(dup_name, "INBOX") != 0 &&
4793                     ((flags & ETPAN_IMAP_MB_NOSELECT) != 0))
4794                         new_item->no_select = TRUE;
4795                 
4796                 if (item_list == NULL)
4797                         llast = item_list = g_slist_append(item_list, new_item);
4798                 else {
4799                         llast = g_slist_append(llast, new_item);
4800                         llast = llast->next;
4801                 }
4802                 debug_print("folder '%s' found.\n", loc_path);
4803                 g_free(base);
4804                 g_free(loc_path);
4805                 g_free(loc_name);
4806                 
4807                 free(dup_name);
4808         }
4809         
4810         return item_list;
4811 }
4812
4813 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist)
4814 {
4815         GSList *sorted_list, *cur;
4816         guint first, last, next;
4817         GSList *ret_list = NULL, *llast = NULL;
4818         struct mailimap_set * current_set;
4819         unsigned int item_count;
4820         
4821         if (numlist == NULL)
4822                 return NULL;
4823         
4824         current_set = mailimap_set_new_empty();
4825         
4826         sorted_list = g_slist_copy(numlist);
4827         sorted_list = g_slist_sort(sorted_list, g_int_compare);
4828
4829         first = GPOINTER_TO_INT(sorted_list->data);
4830         
4831         item_count = 0;
4832         for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
4833                 if (GPOINTER_TO_INT(cur->data) == 0)
4834                         continue;
4835                 
4836                 item_count ++;
4837
4838                 last = GPOINTER_TO_INT(cur->data);
4839                 if (cur->next)
4840                         next = GPOINTER_TO_INT(cur->next->data);
4841                 else
4842                         next = 0;
4843
4844                 if (last + 1 != next || next == 0 || item_count >= folder->max_set_size) {
4845
4846                         struct mailimap_set_item * item;
4847                         item = mailimap_set_item_new(first, last);
4848                         mailimap_set_add(current_set, item);
4849                         
4850                         first = next;
4851
4852                         if (item_count >= folder->max_set_size) {
4853                                 if (ret_list == NULL)
4854                                         llast = ret_list = g_slist_append(ret_list,
4855                                                           current_set);
4856                                 else {
4857                                         llast = g_slist_append(llast, current_set);
4858                                         llast = llast->next;
4859                                 }
4860
4861                                 current_set = mailimap_set_new_empty();
4862                                 item_count = 0;
4863                         }
4864                 } 
4865         }
4866         
4867         if (clist_count(current_set->set_list) > 0) {
4868                 ret_list = g_slist_append(ret_list,
4869                                           current_set);
4870         }
4871         
4872         g_slist_free(sorted_list);
4873
4874         return ret_list;
4875 }
4876
4877 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist)
4878 {
4879         MsgNumberList *numlist = NULL;
4880         MsgInfoList *cur;
4881         GSList *seq_list;
4882
4883         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
4884                 MsgInfo *msginfo = (MsgInfo *) cur->data;
4885
4886                 numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
4887         }
4888         numlist = g_slist_reverse(numlist);
4889         seq_list = imap_get_lep_set_from_numlist(folder, numlist);
4890         g_slist_free(numlist);
4891
4892         return seq_list;
4893 }
4894
4895 static GSList * imap_uid_list_from_lep(clist * list)
4896 {
4897         clistiter * iter;
4898         GSList * result;
4899         
4900         result = NULL;
4901         
4902         for(iter = clist_begin(list) ; iter != NULL ;
4903             iter = clist_next(iter)) {
4904                 uint32_t * puid;
4905                 
4906                 puid = clist_content(iter);
4907                 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
4908         }
4909         
4910         result = g_slist_reverse(result);
4911         return result;
4912 }
4913
4914 static GSList * imap_uid_list_from_lep_tab(carray * list)
4915 {
4916         unsigned int i;
4917         GSList * result;
4918         
4919         result = NULL;
4920         
4921         for(i = 0 ; i < carray_count(list) ; i ++) {
4922                 uint32_t * puid;
4923                 
4924                 puid = carray_get(list, i);
4925                 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
4926         }
4927         result = g_slist_reverse(result);
4928         return result;
4929 }
4930
4931 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
4932                                                    GHashTable * hash)
4933 {
4934         unsigned int i;
4935         GSList * result;
4936         
4937         result = NULL;
4938         
4939         for(i = 0 ; i < carray_count(list) ; i += 2) {
4940                 uint32_t * puid;
4941                 int * pflags;
4942                 gint * pguid;
4943                 
4944                 puid = carray_get(list, i);
4945                 pflags = carray_get(list, i + 1);
4946                 pguid = malloc(sizeof(* pguid));
4947                 * pguid = * puid;
4948                 
4949                 g_hash_table_insert(hash, pguid, GINT_TO_POINTER(* pflags));
4950         }
4951 }
4952
4953 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
4954                                        FolderItem *item)
4955 {
4956         MsgInfo *msginfo = NULL;
4957         guint32 uid = 0;
4958         size_t size = 0;
4959         MsgFlags flags = {0, 0};
4960         
4961         if (info->headers == NULL)
4962                 return NULL;
4963
4964         MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
4965         if (folder_has_parent_of_type(item, F_QUEUE)) {
4966                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
4967         } else if (folder_has_parent_of_type(item, F_DRAFT)) {
4968                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
4969         }
4970         flags.perm_flags = info->flags;
4971         
4972         uid = info->uid;
4973         size = info->size;
4974         msginfo = procheader_parse_str(info->headers, flags, FALSE, FALSE);
4975         
4976         if (msginfo) {
4977                 msginfo->msgnum = uid;
4978                 msginfo->size = size;
4979         }
4980
4981         return msginfo;
4982 }
4983
4984 static void imap_lep_set_free(GSList *seq_list)
4985 {
4986         GSList * cur;
4987         
4988         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
4989                 struct mailimap_set * imapset;
4990                 
4991                 imapset = cur->data;
4992                 mailimap_set_free(imapset);
4993         }
4994         g_slist_free(seq_list);
4995 }
4996
4997 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags)
4998 {
4999         struct mailimap_flag_list * flag_list;
5000         
5001         flag_list = mailimap_flag_list_new_empty();
5002         
5003         if (IMAP_IS_SEEN(flags))
5004                 mailimap_flag_list_add(flag_list,
5005                                        mailimap_flag_new_seen());
5006         if (IMAP_IS_ANSWERED(flags))
5007                 mailimap_flag_list_add(flag_list,
5008                                        mailimap_flag_new_answered());
5009         if (IMAP_IS_FLAGGED(flags))
5010                 mailimap_flag_list_add(flag_list,
5011                                        mailimap_flag_new_flagged());
5012         if (IMAP_IS_DELETED(flags))
5013                 mailimap_flag_list_add(flag_list,
5014                                        mailimap_flag_new_deleted());
5015         if (IMAP_IS_DRAFT(flags))
5016                 mailimap_flag_list_add(flag_list,
5017                                        mailimap_flag_new_draft());
5018         
5019         return flag_list;
5020 }
5021
5022 guint imap_folder_get_refcnt(Folder *folder)
5023 {
5024         return ((IMAPFolder *)folder)->refcnt;
5025 }
5026
5027 void imap_folder_ref(Folder *folder)
5028 {
5029         ((IMAPFolder *)folder)->refcnt++;
5030 }
5031
5032 void imap_disconnect_all(void)
5033 {
5034         GList *list;
5035         for (list = account_get_list(); list != NULL; list = list->next) {
5036                 PrefsAccount *account = list->data;
5037                 if (account->protocol == A_IMAP4) {
5038                         RemoteFolder *folder = (RemoteFolder *)account->folder;
5039                         if (folder && folder->session) {
5040                                 IMAPSession *session = (IMAPSession *)folder->session;
5041                                 imap_threaded_disconnect(FOLDER(folder));
5042                                 SESSION(session)->state = SESSION_DISCONNECTED;
5043                                 session_destroy(SESSION(session));
5044                                 folder->session = NULL;
5045                         }
5046                 }
5047         }
5048 }
5049
5050 void imap_folder_unref(Folder *folder)
5051 {
5052         if (((IMAPFolder *)folder)->refcnt > 0)
5053                 ((IMAPFolder *)folder)->refcnt--;
5054 }
5055
5056 void imap_cancel_all(void)
5057 {
5058         GList *folderlist;
5059         GList *cur;
5060         
5061         folderlist = folder_get_list();
5062         for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
5063                 Folder *folder = (Folder *) cur->data;
5064
5065                 if (folder->klass == &imap_class) {
5066                         if (imap_is_busy(folder)) {
5067                                 IMAPSession *imap_session;
5068                                 RemoteFolder *rfolder;
5069                                 
5070                                 g_printerr("cancelled\n");
5071                                 imap_threaded_cancel(folder);
5072                                 rfolder = (RemoteFolder *) folder;
5073                                 imap_session = (IMAPSession *) rfolder->session;
5074                                 if (imap_session)
5075                                         imap_session->cancelled = 1;
5076                         }
5077                 }
5078         }
5079 }
5080
5081 gboolean imap_cancel_all_enabled(void)
5082 {
5083         GList *folderlist;
5084         GList *cur;
5085         
5086         folderlist = folder_get_list();
5087         for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
5088                 Folder *folder = (Folder *) cur->data;
5089
5090                 if (folder->klass == &imap_class) {
5091                         if (imap_is_busy(folder)) {
5092                                 return TRUE;
5093                         }
5094                 }
5095         }
5096         
5097         return FALSE;
5098 }
5099
5100 static gboolean imap_is_busy(Folder *folder)
5101 {
5102         IMAPSession *imap_session;
5103         RemoteFolder *rfolder;
5104         
5105         rfolder = (RemoteFolder *) folder;
5106         imap_session = (IMAPSession *) rfolder->session;
5107         if (imap_session == NULL)
5108                 return FALSE;
5109         
5110         return imap_session->busy;
5111 }
5112
5113 #else /* HAVE_LIBETPAN */
5114
5115 static FolderClass imap_class;
5116
5117 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
5118 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
5119
5120 static Folder   *imap_folder_new        (const gchar    *name,
5121                                          const gchar    *path)
5122 {
5123         static gboolean missing_imap_warning = TRUE;
5124         if (missing_imap_warning) {
5125                 missing_imap_warning = FALSE;
5126                 alertpanel_error(
5127                         _("You have one or more IMAP accounts "
5128                           "defined. However this version of "
5129                           "Claws Mail has been built without "
5130                           "IMAP support; your IMAP account(s) are "
5131                           "disabled.\n\n"
5132                           "You probably need to "
5133                           "install libetpan and recompile "
5134                           "Claws Mail."));
5135         }
5136         return NULL;
5137 }
5138 static gint     imap_create_tree        (Folder         *folder)
5139 {
5140         return -1;
5141 }
5142 static FolderItem *imap_create_folder   (Folder         *folder,
5143                                          FolderItem     *parent,
5144                                          const gchar    *name)
5145 {
5146         return NULL;
5147 }
5148 static gint     imap_rename_folder      (Folder         *folder,
5149                                          FolderItem     *item, 
5150                                          const gchar    *name)
5151 {
5152         return -1;
5153 }
5154
5155 gchar imap_get_path_separator_for_item(FolderItem *item)
5156 {
5157         return '/';
5158 }
5159
5160 FolderClass *imap_get_class(void)
5161 {
5162         if (imap_class.idstr == NULL) {
5163                 imap_class.type = F_IMAP;
5164                 imap_class.idstr = "imap";
5165                 imap_class.uistr = "IMAP4";
5166
5167                 imap_class.new_folder = imap_folder_new;
5168                 imap_class.create_tree = imap_create_tree;
5169                 imap_class.create_folder = imap_create_folder;
5170                 imap_class.rename_folder = imap_rename_folder;
5171
5172                 imap_class.set_xml = folder_set_xml;
5173                 imap_class.get_xml = folder_get_xml;
5174                 imap_class.item_set_xml = imap_item_set_xml;
5175                 imap_class.item_get_xml = imap_item_get_xml;
5176                 /* nothing implemented */
5177         }
5178
5179         return &imap_class;
5180 }
5181
5182 void imap_disconnect_all(void)
5183 {
5184 }
5185
5186 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
5187 {
5188         return -1;
5189 }
5190
5191 GList * imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
5192 {
5193         return NULL;
5194 }
5195
5196 void imap_cache_msg(FolderItem *item, gint msgnum)
5197 {
5198 }
5199
5200 void imap_cancel_all(void)
5201 {
5202 }
5203
5204 gboolean imap_cancel_all_enabled(void)
5205 {
5206         return FALSE;
5207 }
5208
5209 #endif
5210
5211 #ifdef HAVE_LIBETPAN
5212 static void imap_synchronise(FolderItem *item, gint days) 
5213 {
5214         if (IMAP_FOLDER_ITEM(item)->last_sync == IMAP_FOLDER_ITEM(item)->last_change) {
5215                 debug_print("%s already synced\n", item->path?item->path:item->name);
5216                 return;
5217         }
5218         debug_print("syncing %s\n", item->path?item->path:item->name);
5219         imap_gtk_synchronise(item, days);
5220         IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
5221 }
5222 #endif
5223
5224 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
5225 {
5226 #ifdef HAVE_LIBETPAN
5227         GList *cur;
5228 #endif
5229         folder_item_set_xml(folder, item, tag);
5230         
5231 #ifdef HAVE_LIBETPAN
5232         for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
5233                 XMLAttr *attr = (XMLAttr *) cur->data;
5234
5235                 if (!attr || !attr->name || !attr->value) continue;
5236                 if (!strcmp(attr->name, "uidnext"))
5237                         IMAP_FOLDER_ITEM(item)->uid_next = atoi(attr->value);
5238                 if (!strcmp(attr->name, "last_sync"))
5239                         IMAP_FOLDER_ITEM(item)->last_sync = atoi(attr->value);
5240                 if (!strcmp(attr->name, "last_change"))
5241                         IMAP_FOLDER_ITEM(item)->last_change = atoi(attr->value);
5242         }
5243         if (IMAP_FOLDER_ITEM(item)->last_change == 0)
5244                 IMAP_FOLDER_ITEM(item)->last_change = time(NULL);
5245 #endif
5246 }
5247
5248 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
5249 {
5250         XMLTag *tag;
5251
5252         tag = folder_item_get_xml(folder, item);
5253
5254 #ifdef HAVE_LIBETPAN
5255         xml_tag_add_attr(tag, xml_attr_new_int("uidnext", 
5256                         IMAP_FOLDER_ITEM(item)->uid_next));
5257         xml_tag_add_attr(tag, xml_attr_new_int("last_sync", 
5258                         IMAP_FOLDER_ITEM(item)->last_sync));
5259         xml_tag_add_attr(tag, xml_attr_new_int("last_change", 
5260                         IMAP_FOLDER_ITEM(item)->last_change));
5261
5262 #endif
5263         return tag;
5264 }