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