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