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