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