don't translate strings in debug_print(), log_print(), log_message(), and log_warning()
[claws.git] / src / imap.c
index 10ea45dcd4560c4bd1e92e92c225242352677d02..18df07dec96154c0dd5049e1bfd021576072dc4d 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
- * Copyright (C) 1999-2003 Hiroyuki Yamamoto
+ * Copyright (C) 1999-2004 Hiroyuki Yamamoto
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
 #include "md5.h"
 #include "base64.h"
 #include "utils.h"
+#include "prefs_common.h"
 #include "inputdialog.h"
 #include "log.h"
+#include "remotefolder.h"
+#include "alertpanel.h"
 
 typedef struct _IMAPFolder     IMAPFolder;
 typedef struct _IMAPSession    IMAPSession;
@@ -63,6 +66,7 @@ typedef struct _IMAPFolderItem        IMAPFolderItem;
 #include "prefs_account.h"
 
 #define IMAP_FOLDER(obj)       ((IMAPFolder *)obj)
+#define IMAP_FOLDER_ITEM(obj)  ((IMAPFolderItem *)obj)
 #define IMAP_SESSION(obj)      ((IMAPSession *)obj)
 
 struct _IMAPFolder
@@ -79,11 +83,16 @@ struct _IMAPSession
 {
        Session session;
 
+       gboolean authenticated;
+
        gchar **capability;
+       gboolean uidplus;
+
        gchar *mbox;
-       time_t last_access_time;
-       gboolean authenticated;
        guint cmd_count;
+
+       /* CLAWS */
+       time_t last_access_time;
        gboolean folder_content_changed;
        guint exists;
 };
@@ -153,57 +162,72 @@ struct _IMAPFolderItem
        GSList *uid_list;
 };
 
-static Folder *imap_folder_new(const gchar * name, const gchar * path);
-static void imap_folder_destroy(Folder * folder);
-
-static IMAPSession *imap_session_new(const PrefsAccount * account);
-static void imap_session_authenticate(IMAPSession * session,
-                                     const PrefsAccount * account);
-static void imap_session_destroy(Session * session);
-
-static gchar *imap_fetch_msg(Folder * folder, FolderItem * item, gint uid);
-static gint imap_add_msg(Folder * folder,
-                        FolderItem * dest,
-                        const gchar * file, MsgFlags * flags);
-static gint imap_add_msgs(Folder * folder, FolderItem * dest,
-                         GSList * file_list,
-                         GRelation *relation);
-
-static gint imap_copy_msg(Folder * folder,
-                         FolderItem * dest, MsgInfo * msginfo);
-static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
-                   MsgInfoList *msglist, GRelation *relation);
-
-static gint imap_remove_msg(Folder * folder, FolderItem * item, gint uid);
-static gint imap_remove_all_msg(Folder * folder, FolderItem * item);
-
-static gboolean imap_is_msg_changed(Folder * folder,
-                                   FolderItem * item, MsgInfo * msginfo);
-
-static gint imap_close(Folder * folder, FolderItem * item);
-
-static void imap_scan_tree(Folder * folder);
-
-static gint imap_create_tree(Folder * folder);
-
-static FolderItem *imap_create_folder(Folder * folder,
-                                     FolderItem * parent,
-                                     const gchar * name);
-static gint imap_rename_folder(Folder * folder,
-                              FolderItem * item, const gchar * name);
-static gint imap_remove_folder(Folder * folder, FolderItem * item);
-
-
 static void imap_folder_init           (Folder         *folder,
                                         const gchar    *name,
                                         const gchar    *path);
 
+static Folder  *imap_folder_new        (const gchar    *name,
+                                        const gchar    *path);
+static void     imap_folder_destroy    (Folder         *folder);
+
+static IMAPSession *imap_session_new   (const PrefsAccount     *account);
+static void    imap_session_authenticate(IMAPSession           *session,
+                                         const PrefsAccount    *account);
+static void    imap_session_destroy    (Session        *session);
+
+static gchar   *imap_fetch_msg         (Folder         *folder, 
+                                        FolderItem     *item, 
+                                        gint            uid);
+static gint    imap_add_msg            (Folder         *folder,
+                                        FolderItem     *dest,
+                                        const gchar    *file, 
+                                        MsgFlags       *flags);
+static gint    imap_add_msgs           (Folder         *folder, 
+                                        FolderItem     *dest,
+                                        GSList         *file_list,
+                                        GRelation      *relation);
+
+static gint    imap_copy_msg           (Folder         *folder,
+                                        FolderItem     *dest, 
+                                        MsgInfo        *msginfo);
+static gint    imap_copy_msgs          (Folder         *folder, 
+                                        FolderItem     *dest, 
+                                        MsgInfoList    *msglist, 
+                                        GRelation      *relation);
+
+static gint    imap_remove_msg         (Folder         *folder, 
+                                        FolderItem     *item, 
+                                        gint            uid);
+static gint    imap_remove_all_msg     (Folder         *folder, 
+                                        FolderItem     *item);
+
+static gboolean imap_is_msg_changed    (Folder         *folder,
+                                        FolderItem     *item, 
+                                        MsgInfo        *msginfo);
+
+static gint    imap_close              (Folder         *folder, 
+                                        FolderItem     *item);
+
+static gint    imap_scan_tree          (Folder         *folder);
+
+static gint    imap_create_tree        (Folder         *folder);
+
+static FolderItem *imap_create_folder  (Folder         *folder,
+                                        FolderItem     *parent,
+                                        const gchar    *name);
+static gint    imap_rename_folder      (Folder         *folder,
+                                        FolderItem     *item, 
+                                        const gchar    *name);
+static gint    imap_remove_folder      (Folder         *folder, 
+                                        FolderItem     *item);
+
 static FolderItem *imap_folder_item_new        (Folder         *folder);
 static void imap_folder_item_destroy   (Folder         *folder,
                                         FolderItem     *item);
 
 static IMAPSession *imap_session_get   (Folder         *folder);
 
+static gint imap_greeting              (IMAPSession    *session);
 static gint imap_auth                  (IMAPSession    *session,
                                         const gchar    *user,
                                         const gchar    *pass,
@@ -216,7 +240,7 @@ static GSList *imap_parse_list              (IMAPFolder     *folder,
                                         const gchar    *real_path,
                                         gchar          *separator);
 
-static void imap_create_missing_folders        (Folder                 *folder);
+static void imap_create_missing_folders        (Folder         *folder);
 static FolderItem *imap_create_special_folder
                                        (Folder                 *folder,
                                         SpecialFolderItemType   stype,
@@ -294,10 +318,10 @@ static MsgFlags imap_parse_flags  (const gchar    *flag_str);
 static MsgInfo *imap_parse_envelope    (SockInfo       *sock,
                                         FolderItem     *item,
                                         GString        *line_str);
-static gint imap_greeting              (IMAPSession    *session);
+
 static gboolean imap_has_capability    (IMAPSession    *session,
                                         const gchar    *cap);
-void imap_free_capabilities            (IMAPSession    *session);
+static void imap_free_capabilities     (IMAPSession    *session);
 
 /* low-level IMAP4rev1 commands */
 static gint imap_cmd_authenticate
@@ -305,32 +329,32 @@ static gint imap_cmd_authenticate
                                 const gchar    *user,
                                 const gchar    *pass,
                                 IMAPAuthType    type);
-static gint imap_cmd_login     (IMAPSession    *sock,
+static gint imap_cmd_login     (IMAPSession    *session,
                                 const gchar    *user,
                                 const gchar    *pass);
-static gint imap_cmd_logout    (IMAPSession    *sock);
-static gint imap_cmd_noop      (IMAPSession    *sock);
-static gint imap_cmd_starttls  (IMAPSession    *sock);
-static gint imap_cmd_namespace (IMAPSession    *sock,
+static gint imap_cmd_logout    (IMAPSession    *session);
+static gint imap_cmd_noop      (IMAPSession    *session);
+static gint imap_cmd_starttls  (IMAPSession    *session);
+static gint imap_cmd_namespace (IMAPSession    *session,
                                 gchar         **ns_str);
 static gint imap_cmd_list      (IMAPSession    *session,
                                 const gchar    *ref,
                                 const gchar    *mailbox,
                                 GPtrArray      *argbuf);
-static gint imap_cmd_do_select (IMAPSession    *sock,
+static gint imap_cmd_do_select (IMAPSession    *session,
                                 const gchar    *folder,
                                 gboolean        examine,
                                 gint           *exists,
                                 gint           *recent,
                                 gint           *unseen,
                                 guint32        *uid_validity);
-static gint imap_cmd_select    (IMAPSession    *sock,
+static gint imap_cmd_select    (IMAPSession    *session,
                                 const gchar    *folder,
                                 gint           *exists,
                                 gint           *recent,
                                 gint           *unseen,
                                 guint32        *uid_validity);
-static gint imap_cmd_examine   (IMAPSession    *sock,
+static gint imap_cmd_examine   (IMAPSession    *session,
                                 const gchar    *folder,
                                 gint           *exists,
                                 gint           *recent,
@@ -341,9 +365,9 @@ static gint imap_cmd_create (IMAPSession    *sock,
 static gint imap_cmd_rename    (IMAPSession    *sock,
                                 const gchar    *oldfolder,
                                 const gchar    *newfolder);
-static gint imap_cmd_delete    (IMAPSession    *sock,
+static gint imap_cmd_delete    (IMAPSession    *session,
                                 const gchar    *folder);
-static gint imap_cmd_envelope  (IMAPSession    *sock,
+static gint imap_cmd_envelope  (IMAPSession    *session,
                                 IMAPSet         set);
 static gint imap_cmd_fetch     (IMAPSession    *sock,
                                 guint32         uid,
@@ -352,22 +376,23 @@ static gint imap_cmd_append       (IMAPSession    *session,
                                 const gchar    *destfolder,
                                 const gchar    *file,
                                 IMAPFlags       flags,
-                                gint32         *newuid);
+                                guint32        *new_uid);
 static gint imap_cmd_copy       (IMAPSession    *session, 
                                  const gchar    *seq_set, 
                                  const gchar    *destfolder,
                                 GRelation      *uid_mapping);
-static gint imap_cmd_store     (IMAPSession    *sock,
+static gint imap_cmd_store     (IMAPSession    *session,
                                 IMAPSet         set,
                                 gchar          *sub_cmd);
-static gint imap_cmd_expunge   (IMAPSession    *sock);
-static gint imap_cmd_close     (IMAPSession    *session);
+static gint imap_cmd_expunge   (IMAPSession    *session,
+                                IMAPSet         seq_set);
+static gint imap_cmd_close      (IMAPSession    *session);
 
 static gint imap_cmd_ok                (IMAPSession    *session,
                                 GPtrArray      *argbuf);
-static void imap_gen_send      (IMAPSession    *sock,
+static void imap_gen_send      (IMAPSession    *session,
                                 const gchar    *format, ...);
-static gint imap_gen_recv      (IMAPSession    *sock,
+static gint imap_gen_recv      (IMAPSession    *session,
                                 gchar         **ret);
 
 /* misc utility functions */
@@ -397,69 +422,73 @@ static gboolean imap_rename_folder_func           (GNode          *node,
                                                 gpointer        data);
 static gint imap_get_num_list                  (Folder         *folder,
                                                 FolderItem     *item,
-                                                GSList        **list);
+                                                GSList        **list,
+                                                gboolean       *old_uids_valid);
 static GSList *imap_get_msginfos               (Folder         *folder,
                                                 FolderItem     *item,
                                                 GSList         *msgnum_list);
 static MsgInfo *imap_get_msginfo               (Folder         *folder,
                                                 FolderItem     *item,
                                                 gint            num);
-static gboolean imap_check_msgnum_validity     (Folder         *folder,
+static gboolean imap_scan_required             (Folder         *folder,
                                                 FolderItem     *item);
 static void imap_change_flags                  (Folder         *folder,
                                                 FolderItem     *item,
                                                 MsgInfo        *msginfo,
-                                                MsgPermFlags   newflags);
+                                                MsgPermFlags    newflags);
+static gint imap_get_flags                     (Folder         *folder,
+                                                FolderItem     *item,
+                                                MsgInfoList    *msglist,
+                                                GRelation      *msgflags);
 static gchar *imap_folder_get_path             (Folder         *folder);
 static gchar *imap_item_get_path               (Folder         *folder,
                                                 FolderItem     *item);
 
-FolderClass imap_class =
-{
-       F_IMAP,
-       "imap",
-       "IMAP4",
-
-       /* Folder functions */
-       imap_folder_new,
-       imap_folder_destroy,
-       imap_scan_tree,
-       imap_create_tree,
-
-       /* FolderItem functions */
-       imap_folder_item_new,
-       imap_folder_item_destroy,
-       imap_item_get_path,
-       imap_create_folder,
-       imap_rename_folder,
-       imap_remove_folder,
-       imap_close,
-       imap_get_num_list,
-       NULL,
-       NULL,
-       NULL,
-       imap_check_msgnum_validity,
-
-       /* Message functions */
-       imap_get_msginfo,
-       imap_get_msginfos,
-       imap_fetch_msg,
-       imap_add_msg,
-       imap_add_msgs,
-       imap_copy_msg,
-       imap_copy_msgs,
-       imap_remove_msg,
-       imap_remove_all_msg,
-       imap_is_msg_changed,
-       imap_change_flags,
-};
+static FolderClass imap_class;
 
 FolderClass *imap_get_class(void)
 {
+       if (imap_class.idstr == NULL) {
+               imap_class.type = F_IMAP;
+               imap_class.idstr = "imap";
+               imap_class.uistr = "IMAP4";
+
+               /* Folder functions */
+               imap_class.new_folder = imap_folder_new;
+               imap_class.destroy_folder = imap_folder_destroy;
+               imap_class.scan_tree = imap_scan_tree;
+               imap_class.create_tree = imap_create_tree;
+
+               /* FolderItem functions */
+               imap_class.item_new = imap_folder_item_new;
+               imap_class.item_destroy = imap_folder_item_destroy;
+               imap_class.item_get_path = imap_item_get_path;
+               imap_class.create_folder = imap_create_folder;
+               imap_class.rename_folder = imap_rename_folder;
+               imap_class.remove_folder = imap_remove_folder;
+               imap_class.close = imap_close;
+               imap_class.get_num_list = imap_get_num_list;
+               imap_class.scan_required = imap_scan_required;
+
+               /* Message functions */
+               imap_class.get_msginfo = imap_get_msginfo;
+               imap_class.get_msginfos = imap_get_msginfos;
+               imap_class.fetch_msg = imap_fetch_msg;
+               imap_class.add_msg = imap_add_msg;
+               imap_class.add_msgs = imap_add_msgs;
+               imap_class.copy_msg = imap_copy_msg;
+               imap_class.copy_msgs = imap_copy_msgs;
+               imap_class.remove_msg = imap_remove_msg;
+               imap_class.remove_all_msg = imap_remove_all_msg;
+               imap_class.is_msg_changed = imap_is_msg_changed;
+               imap_class.change_flags = imap_change_flags;
+               imap_class.get_flags = imap_get_flags;
+       }
+       
        return &imap_class;
 }
 
-Folder *imap_folder_new(const gchar *name, const gchar *path)
+static Folder *imap_folder_new(const gchar *name, const gchar *path)
 {
        Folder *folder;
 
@@ -470,7 +499,7 @@ Folder *imap_folder_new(const gchar *name, const gchar *path)
        return folder;
 }
 
-void imap_folder_destroy(Folder *folder)
+static void imap_folder_destroy(Folder *folder)
 {
        gchar *dir;
 
@@ -531,13 +560,53 @@ static void imap_reset_uid_lists(Folder *folder)
        g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL); 
 }
 
+/* Send CAPABILITY, and examine the server's response to see whether this
+ * connection is pre-authenticated or not and build a list of CAPABILITIES. */
+static gint imap_greeting(IMAPSession *session)
+{
+       gchar *capstr;
+       GPtrArray *argbuf;
+
+       imap_gen_send(session, "CAPABILITY");
+       
+       argbuf = g_ptr_array_new();
+
+       if (imap_cmd_ok(session, argbuf) != IMAP_SUCCESS ||
+           ((capstr = search_array_str(argbuf, "CAPABILITY ")) == NULL)) {
+               ptr_array_free_strings(argbuf);
+               g_ptr_array_free(argbuf, TRUE);
+               return -1;
+       }
+
+       session->authenticated = search_array_str(argbuf, "PREAUTH") != NULL;
+       
+       capstr += strlen("CAPABILITY ");
+
+       IMAP_SESSION(session)->capability = g_strsplit(capstr, " ", 0);
+       
+       ptr_array_free_strings(argbuf);
+       g_ptr_array_free(argbuf, TRUE);
+
+       if (imap_has_capability(session, "UIDPLUS")) 
+               session->uidplus = TRUE; 
+
+       return 0;
+}
+
 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
                      IMAPAuthType type)
 {
+       gint ok;
+
        if (type == 0 || type == IMAP_AUTH_LOGIN)
-               return imap_cmd_login(session, user, pass);
+               ok = imap_cmd_login(session, user, pass);
        else
-               return imap_cmd_authenticate(session, user, pass, type);
+               ok = imap_cmd_authenticate(session, user, pass, type);
+
+       if (ok == IMAP_SUCCESS)
+               session->authenticated = TRUE;
+
+       return ok;
 }
 
 static IMAPSession *imap_session_get(Folder *folder)
@@ -548,6 +617,9 @@ static IMAPSession *imap_session_get(Folder *folder)
        g_return_val_if_fail(folder != NULL, NULL);
        g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
        g_return_val_if_fail(folder->account != NULL, NULL);
+       
+       if (prefs_common.work_offline)
+               return NULL;
 
        /* Make sure we have a session */
        if (rfolder->session != NULL) {
@@ -593,13 +665,13 @@ static IMAPSession *imap_session_get(Folder *folder)
                        /* Check if this is the first try to establish a
                           connection, if yes we don't try to reconnect */
                        if (rfolder->session == NULL) {
-                               log_warning(_("Connecting %s failed"),
+                               log_warning("Connecting %s failed",
                                            folder->account->recv_server);
                                session_destroy(SESSION(session));
                                session = NULL;
                        } else {
-                               log_warning(_("IMAP4 connection to %s has been"
-                                             " disconnected. Reconnecting...\n"),
+                               log_warning("IMAP4 connection to %s has been"
+                                           " disconnected. Reconnecting...\n",
                                            folder->account->recv_server);
                                session_destroy(SESSION(session));
                                /* Clear folders session to make imap_session_get create
@@ -619,7 +691,7 @@ static IMAPSession *imap_session_get(Folder *folder)
        return IMAP_SESSION(session);
 }
 
-IMAPSession *imap_session_new(const PrefsAccount *account)
+static IMAPSession *imap_session_new(const PrefsAccount *account)
 {
        IMAPSession *session;
        SockInfo *imap_sock;
@@ -638,7 +710,7 @@ IMAPSession *imap_session_new(const PrefsAccount *account)
 #endif
 
        if (account->set_tunnelcmd) {
-               log_message(_("creating tunneled IMAP4 connection\n"));
+               log_message("creating tunneled IMAP4 connection\n");
 #if USE_OPENSSL
                if ((imap_sock = imap_open_tunnel(account->recv_server, 
                                                  account->tunnelcmd,
@@ -651,7 +723,7 @@ IMAPSession *imap_session_new(const PrefsAccount *account)
        } else {
                g_return_val_if_fail(account->recv_server != NULL, NULL);
 
-               log_message(_("creating IMAP4 connection to %s:%d ...\n"),
+               log_message("creating IMAP4 connection to %s:%d ...\n",
                            account->recv_server, port);
                
 #if USE_OPENSSL
@@ -673,8 +745,8 @@ IMAPSession *imap_session_new(const PrefsAccount *account)
 
        session->capability = NULL;
 
-       session->mbox = NULL;
        session->authenticated = FALSE;
+       session->mbox = NULL;
        session->cmd_count = 0;
 
        /* Only need to log in if the connection was not PREAUTH */
@@ -684,22 +756,25 @@ IMAPSession *imap_session_new(const PrefsAccount *account)
        }
 
 #if USE_OPENSSL
-       if (account->ssl_imap == SSL_STARTTLS && imap_has_capability(session, "STARTTLS")) {
+       if (account->ssl_imap == SSL_STARTTLS && 
+           imap_has_capability(session, "STARTTLS")) {
                gint ok;
 
                ok = imap_cmd_starttls(session);
                if (ok != IMAP_SUCCESS) {
-                       log_warning(_("Can't start TLS session.\n"));
+                       log_warning("Can't start TLS session.\n");
                        session_destroy(SESSION(session));
                        return NULL;
                }
-               if (!ssl_init_socket_with_method(SESSION(session)->sock, SSL_METHOD_TLSv1)) {
+               if (!ssl_init_socket_with_method(SESSION(session)->sock, 
+                   SSL_METHOD_TLSv1)) {
                        session_destroy(SESSION(session));
                        return NULL;
                }
 
                imap_free_capabilities(session);
                session->authenticated = FALSE;
+               session->uidplus = FALSE;
                session->cmd_count = 1;
 
                if (imap_greeting(session) != IMAP_SUCCESS) {
@@ -714,7 +789,8 @@ IMAPSession *imap_session_new(const PrefsAccount *account)
        return session;
 }
 
-void imap_session_authenticate(IMAPSession *session, const PrefsAccount *account)
+static void imap_session_authenticate(IMAPSession *session, 
+                                     const PrefsAccount *account)
 {
        gchar *pass;
 
@@ -738,16 +814,15 @@ void imap_session_authenticate(IMAPSession *session, const PrefsAccount *account
        session->authenticated = TRUE;
 }
 
-void imap_session_destroy(Session *session)
+static void imap_session_destroy(Session *session)
 {
+       imap_free_capabilities(IMAP_SESSION(session));
+       g_free(IMAP_SESSION(session)->mbox);
        sock_close(session->sock);
        session->sock = NULL;
-
-       g_free(IMAP_SESSION(session)->mbox);
-       imap_free_capabilities(IMAP_SESSION(session));
 }
 
-gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
+static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
 {
        gchar *path, *filename;
        IMAPSession *session;
@@ -761,7 +836,7 @@ gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
                make_dir_hier(path);
        filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
        g_free(path);
+
        if (is_file_exist(filename)) {
                debug_print("message %d has been already cached.\n", uid);
                return filename;
@@ -793,7 +868,8 @@ gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
        return filename;
 }
 
-gint imap_add_msg(Folder *folder, FolderItem *dest, const gchar *file, MsgFlags *flags)
+static gint imap_add_msg(Folder *folder, FolderItem *dest, 
+                        const gchar *file, MsgFlags *flags)
 {
        gint ret;
        GSList file_list;
@@ -811,7 +887,7 @@ gint imap_add_msg(Folder *folder, FolderItem *dest, const gchar *file, MsgFlags
        return ret;
 }
 
-gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
+static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                   GRelation *relation)
 {
        gchar *destdir;
@@ -819,7 +895,7 @@ gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
        guint32 last_uid = 0;
        GSList *cur;
        MsgFileInfo *fileinfo;
-       gint ok, newnum;
+       gint ok;
 
        g_return_val_if_fail(folder != NULL, -1);
        g_return_val_if_fail(dest != NULL, -1);
@@ -832,6 +908,7 @@ gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
 
        for (cur = file_list; cur != NULL; cur = cur->next) {
                IMAPFlags iflags = 0;
+               guint32 new_uid = 0;
 
                fileinfo = (MsgFileInfo *)cur->data;
 
@@ -850,7 +927,8 @@ gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                    dest->stype == F_TRASH)
                        iflags |= IMAP_FLAG_SEEN;
 
-               ok = imap_cmd_append(session, destdir, fileinfo->file, iflags, &newnum);
+               ok = imap_cmd_append(session, destdir, fileinfo->file, iflags, 
+                                    &new_uid);
 
                if (ok != IMAP_SUCCESS) {
                        g_warning("can't append message %s\n", fileinfo->file);
@@ -860,10 +938,10 @@ gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
 
                if (relation != NULL)
                        g_relation_insert(relation, fileinfo->msginfo != NULL ? 
-                                         fileinfo->msginfo : fileinfo,
+                                         (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
                                          GINT_TO_POINTER(dest->last_num + 1));
-               if (newnum > last_uid)
-                       last_uid = newnum;
+               if (last_uid < new_uid)
+                       last_uid = new_uid;
        }
 
        g_free(destdir);
@@ -874,6 +952,7 @@ gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
                              MsgInfoList *msglist, GRelation *relation)
 {
+       FolderItem *src;
        gchar *destdir;
        GSList *seq_list, *cur;
        MsgInfo *msginfo;
@@ -890,11 +969,18 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
        if (!session) return -1;
 
        msginfo = (MsgInfo *)msglist->data;
-       if (msginfo->folder == dest) {
+
+       src = msginfo->folder;
+       if (src == dest) {
                g_warning("the src folder is identical to the dest.\n");
                return -1;
        }
 
+       ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
+                        NULL, NULL, NULL, NULL);
+       if (ok != IMAP_SUCCESS)
+               return ok;
+
        destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
        seq_list = imap_get_seq_set_from_msglist(msglist);
        uid_mapping = g_relation_new(2);
@@ -904,7 +990,7 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                gchar *seq_set = (gchar *)cur->data;
 
                debug_print("Copying message %s%c[%s] to %s ...\n",
-                           msginfo->folder->path, G_DIR_SEPARATOR,
+                           src->path, G_DIR_SEPARATOR,
                            seq_set, destdir);
 
                ok = imap_cmd_copy(session, seq_set, destdir, uid_mapping);
@@ -918,7 +1004,7 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
        for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
                MsgInfo *msginfo = (MsgInfo *)cur->data;
                GTuples *tuples;
-               
+
                tuples = g_relation_select(uid_mapping, 
                                           GINT_TO_POINTER(msginfo->msgnum),
                                           0);
@@ -933,7 +1019,8 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                                          GPOINTER_TO_INT(0));
                g_tuples_destroy(tuples);
        }
-       
+
+       g_relation_destroy(uid_mapping);
        imap_seq_set_free(seq_list);
 
        g_free(destdir);
@@ -944,7 +1031,7 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                return -1;
 }
 
-gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
+static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
 {
        GSList msglist;
 
@@ -956,7 +1043,7 @@ gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
        return imap_copy_msgs(folder, dest, &msglist, NULL);
 }
 
-gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
+static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
                    MsgInfoList *msglist, GRelation *relation)
 {
        MsgInfo *msginfo;
@@ -983,7 +1070,7 @@ gint imap_copy_msgs(Folder *folder, FolderItem *dest,
        return ret;
 }
 
-gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
+static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
 {
        gint ok;
        IMAPSession *session;
@@ -1009,16 +1096,26 @@ gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
                (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
                &numlist, IMAP_FLAG_DELETED, TRUE);
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't set deleted flags: %d\n"), uid);
+               log_warning("can't set deleted flags: %d\n", uid);
                return ok;
        }
 
-       ok = imap_cmd_expunge(session);
+       if (!session->uidplus) {
+               ok = imap_cmd_expunge(session, NULL);
+       } else {
+               gchar *uidstr;
+
+               uidstr = g_strdup_printf("%u", uid);
+               ok = imap_cmd_expunge(session, uidstr);
+               g_free(uidstr);
+       }
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't expunge\n"));
+               log_warning("can't expunge\n");
                return ok;
        }
 
+       IMAP_FOLDER_ITEM(item)->uid_list = g_slist_remove(
+           IMAP_FOLDER_ITEM(item)->uid_list, numlist.data);
        dir = folder_item_get_path(item);
        if (is_dir_exist(dir))
                remove_numbered_files(dir, uid, uid);
@@ -1027,10 +1124,8 @@ gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
        return IMAP_SUCCESS;
 }
 
-gint imap_remove_all_msg(Folder *folder, FolderItem *item)
+static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
 {
-        gint exists, recent, unseen;
-        guint32 uid_validity;
        gint ok;
        IMAPSession *session;
        gchar *dir;
@@ -1042,23 +1137,20 @@ gint imap_remove_all_msg(Folder *folder, FolderItem *item)
        if (!session) return -1;
 
        ok = imap_select(session, IMAP_FOLDER(folder), item->path,
-                        &exists, &recent, &unseen, &uid_validity);
+                        NULL, NULL, NULL, NULL);
        if (ok != IMAP_SUCCESS)
                return ok;
-       if (exists == 0)
-               return IMAP_SUCCESS;
 
-       imap_gen_send(session,
-                     "STORE 1:%d +FLAGS.SILENT (\\Deleted)", exists);
+       imap_gen_send(session, "STORE 1:* +FLAGS.SILENT (\\Deleted)");
        ok = imap_cmd_ok(session, NULL);
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't set deleted flags: 1:%d\n"), exists);
+               log_warning("can't set deleted flags: 1:*\n");
                return ok;
        }
 
-       ok = imap_cmd_expunge(session);
+       ok = imap_cmd_expunge(session, NULL);
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't expunge\n"));
+               log_warning("can't expunge\n");
                return ok;
        }
 
@@ -1070,26 +1162,31 @@ gint imap_remove_all_msg(Folder *folder, FolderItem *item)
        return IMAP_SUCCESS;
 }
 
-gboolean imap_is_msg_changed(Folder *folder, FolderItem *item, MsgInfo *msginfo)
+static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
+                                   MsgInfo *msginfo)
 {
        /* TODO: properly implement this method */
        return FALSE;
 }
 
-gint imap_close(Folder *folder, FolderItem *item)
+static gint imap_close(Folder *folder, FolderItem *item)
 {
        gint ok;
        IMAPSession *session;
 
        g_return_val_if_fail(folder != NULL, -1);
+       g_return_val_if_fail(item != NULL, -1);
+       g_return_val_if_fail(item->path != NULL, -1);
 
        session = imap_session_get(folder);
        if (!session) return -1;
 
        if (session->mbox) {
+               if (strcmp2(session->mbox, item->path) != 0) return -1;
+
                ok = imap_cmd_close(session);
                if (ok != IMAP_SUCCESS)
-                       log_warning(_("can't close folder\n"));
+                       log_warning("can't close folder\n");
 
                g_free(session->mbox);
                session->mbox = NULL;
@@ -1100,14 +1197,14 @@ gint imap_close(Folder *folder, FolderItem *item)
        return 0;
 }
 
-void imap_scan_tree(Folder *folder)
+static gint imap_scan_tree(Folder *folder)
 {
-       FolderItem *item;
+       FolderItem *item = NULL;
        IMAPSession *session;
        gchar *root_folder = NULL;
 
-       g_return_if_fail(folder != NULL);
-       g_return_if_fail(folder->account != NULL);
+       g_return_val_if_fail(folder != NULL, -1);
+       g_return_val_if_fail(folder->account != NULL, -1);
 
        session = imap_session_get(folder);
        if (!session) {
@@ -1115,25 +1212,61 @@ void imap_scan_tree(Folder *folder)
                        folder_tree_destroy(folder);
                        item = folder_item_new(folder, folder->name, NULL);
                        item->folder = folder;
-                       folder->node = g_node_new(item);
+                       folder->node = item->node = g_node_new(item);
                }
-               return;
+               return -1;
        }
 
        if (folder->account->imap_dir && *folder->account->imap_dir) {
-               Xstrdup_a(root_folder, folder->account->imap_dir, return);
+               gchar *real_path;
+               GPtrArray *argbuf;
+               gint ok;
+
+               Xstrdup_a(root_folder, folder->account->imap_dir, return -1);
+               extract_quote(root_folder, '"');
+               subst_char(root_folder,
+                          imap_get_path_separator(IMAP_FOLDER(folder),
+                                                  root_folder),
+                          '/');
                strtailchomp(root_folder, '/');
-               debug_print("IMAP root directory: %s\n", root_folder);
-       }
+               real_path = imap_get_real_path
+                       (IMAP_FOLDER(folder), root_folder);
+               debug_print("IMAP root directory: %s\n", real_path);
+
+               /* check if root directory exist */
+               argbuf = g_ptr_array_new();
+               ok = imap_cmd_list(session, NULL, real_path, argbuf);
+               if (ok != IMAP_SUCCESS ||
+                   search_array_str(argbuf, "LIST ") == NULL) {
+                       log_warning("root folder %s does not exist\n", real_path);
+                       g_ptr_array_free(argbuf, TRUE);
+                       g_free(real_path);
 
-       item = folder_item_new(folder, folder->name, root_folder);
-       item->folder = folder;
-       item->no_select = TRUE;
-       folder->node = g_node_new(item);
+                       if (!folder->node) {
+                               item = folder_item_new(folder, folder->name, NULL);
+                               item->folder = folder;
+                               folder->node = item->node = g_node_new(item);
+                       }
+                       return -1;
+               }
+               g_ptr_array_free(argbuf, TRUE);
+               g_free(real_path);
+       }
 
-       imap_scan_tree_recursive(session, item);
+       if (folder->node)
+               item = FOLDER_ITEM(folder->node->data);
+       if (!item || ((item->path || root_folder) &&
+                     strcmp2(item->path, root_folder) != 0)) {
+               folder_tree_destroy(folder);
+               item = folder_item_new(folder, folder->name, root_folder);
+               item->folder = folder;
+               folder->node = item->node = g_node_new(item);
+       }
 
+       imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data));
        imap_create_missing_folders(folder);
+
+       return 0;
 }
 
 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
@@ -1142,6 +1275,7 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
        IMAPFolder *imapfolder;
        FolderItem *new_item;
        GSList *item_list, *cur;
+       GNode *node;
        gchar *real_path;
        gchar *wildcard_path;
        gchar separator;
@@ -1151,13 +1285,13 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
        g_return_val_if_fail(item->folder != NULL, -1);
        g_return_val_if_fail(item->no_sub == FALSE, -1);
 
-       folder = FOLDER(item->folder);
+       folder = item->folder;
        imapfolder = IMAP_FOLDER(folder);
 
        separator = imap_get_path_separator(imapfolder, item->path);
 
-       if (item->folder->ui_func)
-               item->folder->ui_func(folder, item, folder->ui_func_data);
+       if (folder->ui_func)
+               folder->ui_func(folder, item, folder->ui_func_data);
 
        if (item->path) {
                wildcard[0] = separator;
@@ -1181,17 +1315,60 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
        item_list = imap_parse_list(imapfolder, session, real_path, NULL);
        g_free(real_path);
 
+       node = item->node->children;
+       while (node != NULL) {
+               FolderItem *old_item = FOLDER_ITEM(node->data);
+               GNode *next = node->next;
+
+               new_item = NULL;
+               for (cur = item_list; cur != NULL; cur = cur->next) {
+                       FolderItem *cur_item = FOLDER_ITEM(cur->data);
+                       if (!strcmp2(old_item->path, cur_item->path)) {
+                               new_item = cur_item;
+                               break;
+                       }
+               }
+               if (!new_item) {
+                       debug_print("folder '%s' not found. removing...\n",
+                                   old_item->path);
+                       folder_item_remove(old_item);
+               } else {
+                       old_item->no_sub = new_item->no_sub;
+                       old_item->no_select = new_item->no_select;
+                       if (old_item->no_sub == TRUE && node->children) {
+                               debug_print("folder '%s' doesn't have "
+                                           "subfolders. removing...\n",
+                                           old_item->path);
+                               folder_item_remove_children(old_item);
+                       }
+               }
+
+               node = next;
+       }
+
        for (cur = item_list; cur != NULL; cur = cur->next) {
-               new_item = cur->data;
-               if (!strcmp(new_item->path, "INBOX")) {
-                       if (!folder->inbox) {
-                               new_item->stype = F_INBOX;
-                               item->folder->inbox = new_item;
-                       } else {
-                               folder_item_destroy(new_item);
-                               continue;
+               FolderItem *cur_item = FOLDER_ITEM(cur->data);
+               new_item = NULL;
+               for (node = item->node->children; node != NULL;
+                    node = node->next) {
+                       if (!strcmp2(FOLDER_ITEM(node->data)->path,
+                                    cur_item->path)) {
+                               new_item = FOLDER_ITEM(node->data);
+                               folder_item_destroy(cur_item);
+                               cur_item = NULL;
+                               break;
                        }
-               } else if (!item->parent || item->stype == F_INBOX) {
+               }
+               if (!new_item) {
+                       new_item = cur_item;
+                       debug_print("new folder '%s' found.\n", new_item->path);
+                       folder_item_append(item, new_item);
+               }
+
+               if (!strcmp(new_item->path, "INBOX")) {
+                       new_item->stype = F_INBOX;
+                       folder->inbox = new_item;
+               } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
                        gchar *base;
 
                        base = g_basename(new_item->path);
@@ -1210,11 +1387,13 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
                                folder->trash = new_item;
                        }
                }
-               folder_item_append(item, new_item);
+
                if (new_item->no_sub == FALSE)
                        imap_scan_tree_recursive(session, new_item);
        }
 
+       g_slist_free(item_list);
+
        return IMAP_SUCCESS;
 }
 
@@ -1238,12 +1417,16 @@ static GSList *imap_parse_list(IMAPFolder *folder, IMAPSession *session,
 
        for (;;) {
                if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
-                       log_warning(_("error occurred while getting LIST.\n"));
+                       log_warning("error occurred while getting LIST.\n");
                        break;
                }
                strretchomp(buf);
                if (buf[0] != '*' || buf[1] != ' ') {
                        log_print("IMAP4< %s\n", buf);
+                       if (sscanf(buf, "%*d %16s", buf) < 1 ||
+                           strcmp(buf, "OK") != 0)
+                               log_warning("error occurred while getting LIST.\n");
+                               
                        break;
                }
                debug_print("IMAP4< %s\n", buf);
@@ -1294,7 +1477,7 @@ static GSList *imap_parse_list(IMAPFolder *folder, IMAPSession *session,
 
                item_list = g_slist_append(item_list, new_item);
 
-               debug_print("folder %s has been added.\n", loc_path);
+               debug_print("folder '%s' found.\n", loc_path);
                g_free(loc_path);
                g_free(loc_name);
        }
@@ -1304,7 +1487,7 @@ static GSList *imap_parse_list(IMAPFolder *folder, IMAPSession *session,
        return item_list;
 }
 
-gint imap_create_tree(Folder *folder)
+static gint imap_create_tree(Folder *folder)
 {
        g_return_val_if_fail(folder != NULL, -1);
        g_return_val_if_fail(folder->node != NULL, -1);
@@ -1417,7 +1600,7 @@ static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
        return path;
 }
 
-FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
+static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                               const gchar *name)
 {
        gchar *dirpath, *imap_path;
@@ -1436,7 +1619,7 @@ FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
        session = imap_session_get(folder);
        if (!session) return NULL;
 
-       if (!parent->parent && strcmp(name, "INBOX") == 0)
+       if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0)
                dirpath = g_strdup(name);
        else if (parent->path)
                dirpath = g_strconcat(parent->path, "/", name, NULL);
@@ -1470,7 +1653,7 @@ FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                ok = imap_cmd_list(session, NULL, imap_path,
                                   argbuf);
                if (ok != IMAP_SUCCESS) {
-                       log_warning(_("can't create mailbox: LIST failed\n"));
+                       log_warning("can't create mailbox: LIST failed\n");
                        g_free(imap_path);
                        g_free(dirpath);
                        ptr_array_free_strings(argbuf);
@@ -1492,7 +1675,7 @@ FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                if (!exist) {
                        ok = imap_cmd_create(session, imap_path);
                        if (ok != IMAP_SUCCESS) {
-                               log_warning(_("can't create mailbox\n"));
+                               log_warning("can't create mailbox\n");
                                g_free(imap_path);
                                g_free(dirpath);
                                return NULL;
@@ -1513,13 +1696,13 @@ FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
        return new_item;
 }
 
-gint imap_rename_folder(Folder *folder, FolderItem *item, const gchar *name)
+static gint imap_rename_folder(Folder *folder, FolderItem *item,
+                              const gchar *name)
 {
        gchar *dirpath;
        gchar *newpath;
        gchar *real_oldpath;
        gchar *real_newpath;
-       GNode *node;
        gchar *paths[2];
        gchar *old_cache_dir;
        gchar *new_cache_dir;
@@ -1534,6 +1717,12 @@ gint imap_rename_folder(Folder *folder, FolderItem *item, const gchar *name)
        g_return_val_if_fail(item->path != NULL, -1);
        g_return_val_if_fail(name != NULL, -1);
 
+       if (strchr(name, imap_get_path_separator(IMAP_FOLDER(folder), item->path)) != NULL) {
+               g_warning(_("New folder name must not contain the namespace "
+                           "path separator"));
+               return -1;
+       }
+
        session = imap_session_get(folder);
        if (!session) return -1;
 
@@ -1561,7 +1750,7 @@ gint imap_rename_folder(Folder *folder, FolderItem *item, const gchar *name)
 
        ok = imap_cmd_rename(session, real_oldpath, real_newpath);
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't rename mailbox: %s to %s\n"),
+               log_warning("can't rename mailbox: %s to %s\n",
                            real_oldpath, real_newpath);
                g_free(real_oldpath);
                g_free(newpath);
@@ -1574,11 +1763,9 @@ gint imap_rename_folder(Folder *folder, FolderItem *item, const gchar *name)
 
        old_cache_dir = folder_item_get_path(item);
 
-       node = g_node_find(item->folder->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-                          item);
        paths[0] = g_strdup(item->path);
        paths[1] = newpath;
-       g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
+       g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
                        imap_rename_folder_func, paths);
 
        if (is_dir_exist(old_cache_dir)) {
@@ -1598,7 +1785,7 @@ gint imap_rename_folder(Folder *folder, FolderItem *item, const gchar *name)
        return 0;
 }
 
-gint imap_remove_folder(Folder *folder, FolderItem *item)
+static gint imap_remove_folder(Folder *folder, FolderItem *item)
 {
        gint ok;
        IMAPSession *session;
@@ -1625,7 +1812,7 @@ gint imap_remove_folder(Folder *folder, FolderItem *item)
 
        ok = imap_cmd_delete(session, path);
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't delete mailbox\n"));
+               log_warning("can't delete mailbox\n");
                g_free(path);
                return -1;
        }
@@ -1663,7 +1850,7 @@ static GSList *imap_get_uncached_messages(IMAPSession *session,
 
                if (imap_cmd_envelope(session, imapset)
                    != IMAP_SUCCESS) {
-                       log_warning(_("can't get envelope\n"));
+                       log_warning("can't get envelope\n");
                        continue;
                }
 
@@ -1671,7 +1858,7 @@ static GSList *imap_get_uncached_messages(IMAPSession *session,
 
                for (;;) {
                        if ((tmp = sock_getline(SESSION(session)->sock)) == NULL) {
-                               log_warning(_("error occurred while getting envelope.\n"));
+                               log_warning("error occurred while getting envelope.\n");
                                g_string_free(str, TRUE);
                                break;
                        }
@@ -1693,7 +1880,7 @@ static GSList *imap_get_uncached_messages(IMAPSession *session,
                        msginfo = imap_parse_envelope
                                (SESSION(session)->sock, item, str);
                        if (!msginfo) {
-                               log_warning(_("can't parse envelope: %s\n"), str->str);
+                               log_warning("can't parse envelope: %s\n", str->str);
                                continue;
                        }
                        if (item->stype == F_QUEUE) {
@@ -1749,7 +1936,7 @@ static SockInfo *imap_open_tunnel(const gchar *server,
        SockInfo *sock;
 
        if ((sock = sock_connect_cmd(server, tunnelcmd)) == NULL) {
-               log_warning(_("Can't establish IMAP4 session with: %s\n"),
+               log_warning("Can't establish IMAP4 session with: %s\n",
                            server);
                return NULL;
        }
@@ -1771,14 +1958,14 @@ static SockInfo *imap_open(const gchar *server, gushort port)
        SockInfo *sock;
 
        if ((sock = sock_connect(server, port)) == NULL) {
-               log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
+               log_warning("Can't connect to IMAP4 server: %s:%d\n",
                            server, port);
                return NULL;
        }
 
 #if USE_OPENSSL
        if (ssl_type == SSL_TUNNEL && !ssl_init_socket(sock)) {
-               log_warning(_("Can't establish IMAP4 session with: %s:%d\n"),
+               log_warning("Can't establish IMAP4 session with: %s:%d\n",
                            server, port);
                sock_close(sock);
                return NULL;
@@ -1799,7 +1986,7 @@ static SockInfo *imap_init_sock(SockInfo *sock)
 
 static GList *imap_parse_namespace_str(gchar *str)
 {
-       gchar *p = str;
+       guchar *p = str;
        gchar *name;
        gchar *separator;
        IMAPNameSpace *namespace;
@@ -1868,7 +2055,7 @@ static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
        
        if (imap_cmd_namespace(session, &ns_str)
            != IMAP_SUCCESS) {
-               log_warning(_("can't get namespace\n"));
+               log_warning("can't get namespace\n");
                return;
        }
 
@@ -1922,14 +2109,15 @@ static IMAPNameSpace *imap_find_namespace_from_list(GList *ns_list,
 
        if (!path) path = "";
 
-       Xstrcat_a(tmp_path, path, "/", return NULL);
-
        for (; ns_list != NULL; ns_list = ns_list->next) {
                IMAPNameSpace *tmp_ns = ns_list->data;
 
+               Xstrcat_a(tmp_path, path, "/", return namespace);
                Xstrdup_a(name, tmp_ns->name, return namespace);
-               if (tmp_ns->separator && tmp_ns->separator != '/')
+               if (tmp_ns->separator && tmp_ns->separator != '/') {
+                       subst_char(tmp_path, tmp_ns->separator, '/');
                        subst_char(name, tmp_ns->separator, '/');
+               }
                if (strncmp(tmp_path, name, strlen(name)) == 0)
                        namespace = tmp_ns;
        }
@@ -1990,7 +2178,7 @@ static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
        g_return_val_if_fail(str != NULL, cur_pos);
 
        /* read the next line if the current response buffer is empty */
-       while (isspace(*cur_pos)) cur_pos++;
+       while (isspace(*(guchar *)cur_pos)) cur_pos++;
        while (*cur_pos == '\0') {
                if ((nextline = sock_getline(sock)) == NULL)
                        return cur_pos;
@@ -2001,7 +2189,7 @@ static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
                debug_print("IMAP4< %s\n", nextline);
                g_free(nextline);
 
-               while (isspace(*cur_pos)) cur_pos++;
+               while (isspace(*(guchar *)cur_pos)) cur_pos++;
        }
 
        if (!strncmp(cur_pos, "NIL", 3)) {
@@ -2019,7 +2207,7 @@ static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
 
                cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
                len = atoi(buf);
-               g_return_val_if_fail(len > 0, cur_pos);
+               g_return_val_if_fail(len >= 0, cur_pos);
 
                g_string_truncate(str, 0);
                cur_pos = str->str;
@@ -2056,13 +2244,13 @@ static gchar *imap_get_header(SockInfo *sock, gchar *cur_pos, gchar **headers,
 
        g_return_val_if_fail(str != NULL, cur_pos);
 
-       while (isspace(*cur_pos)) cur_pos++;
+       while (isspace(*(guchar *)cur_pos)) cur_pos++;
 
        g_return_val_if_fail(*cur_pos == '{', cur_pos);
 
        cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
        len = atoi(buf);
-       g_return_val_if_fail(len > 0, cur_pos);
+       g_return_val_if_fail(len >= 0, cur_pos);
 
        g_string_truncate(str, 0);
        cur_pos = str->str;
@@ -2083,7 +2271,7 @@ static gchar *imap_get_header(SockInfo *sock, gchar *cur_pos, gchar **headers,
        *headers = g_strndup(cur_pos, len);
        cur_pos += len;
 
-       while (isspace(*cur_pos)) cur_pos++;
+       while (isspace(*(guchar *)cur_pos)) cur_pos++;
        while (*cur_pos == '\0') {
                if ((nextline = sock_getline(sock)) == NULL)
                        return cur_pos;
@@ -2093,7 +2281,7 @@ static gchar *imap_get_header(SockInfo *sock, gchar *cur_pos, gchar **headers,
                debug_print("IMAP4< %s\n", nextline);
                g_free(nextline);
 
-               while (isspace(*cur_pos)) cur_pos++;
+               while (isspace(*(guchar *)cur_pos)) cur_pos++;
        }
 
        return cur_pos;
@@ -2282,7 +2470,8 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
 {
        gchar *real_path;
        gint ok;
-       gint exists_, recent_, unseen_, uid_validity_;
+       gint exists_, recent_, unseen_;
+       guint32 uid_validity_;
 
        if (!exists || !recent || !unseen || !uid_validity) {
                if (session->mbox && strcmp(session->mbox, path) == 0)
@@ -2300,7 +2489,7 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
        ok = imap_cmd_select(session, real_path,
                             exists, recent, unseen, uid_validity);
        if (ok != IMAP_SUCCESS)
-               log_warning(_("can't select folder: %s\n"), real_path);
+               log_warning("can't select folder: %s\n", real_path);
        else {
                session->mbox = g_strdup(path);
                session->folder_content_changed = FALSE;
@@ -2321,21 +2510,22 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
        gchar *real_path;
        gchar *real_path_;
        gint ok;
-       GPtrArray *argbuf;
+       GPtrArray *argbuf = NULL;
        gchar *str;
 
-       *messages = *recent = *uid_next = *uid_validity = *unseen = 0;
-
-       argbuf = g_ptr_array_new();
+       if (messages && recent && uid_next && uid_validity && unseen) {
+               *messages = *recent = *uid_next = *uid_validity = *unseen = 0;
+               argbuf = g_ptr_array_new();
+       }
 
        real_path = imap_get_real_path(folder, path);
        QUOTE_IF_REQUIRED(real_path_, real_path);
        imap_gen_send(session, "STATUS %s "
-                     "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)",
-                     real_path_);
+                         "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)",
+                         real_path_);
 
        ok = imap_cmd_ok(session, argbuf);
-       if (ok != IMAP_SUCCESS) THROW(ok);
+       if (ok != IMAP_SUCCESS || !argbuf) THROW(ok);
 
        str = search_array_str(argbuf, "STATUS");
        if (!str) THROW(IMAP_ERROR);
@@ -2369,14 +2559,33 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
 
 catch:
        g_free(real_path);
-       ptr_array_free_strings(argbuf);
-       g_ptr_array_free(argbuf, TRUE);
+       if (argbuf) {
+               ptr_array_free_strings(argbuf);
+               g_ptr_array_free(argbuf, TRUE);
+       }
 
        return ok;
 }
 
 #undef THROW
 
+static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
+{
+       gchar **p;
+       
+       for (p = session->capability; *p != NULL; ++p) {
+               if (!g_strcasecmp(*p, cap))
+                       return TRUE;
+       }
+
+       return FALSE;
+}
+
+static void imap_free_capabilities(IMAPSession *session)
+{
+       g_strfreev(session->capability);
+       session->capability = NULL;
+}
 
 /* low-level IMAP4rev1 commands */
 
@@ -2420,7 +2629,7 @@ static gint imap_cmd_authenticate(IMAPSession *session, const gchar *user,
        sock_puts(SESSION(session)->sock, response64);
        ok = imap_cmd_ok(session, NULL);
        if (ok != IMAP_SUCCESS)
-               log_warning(_("IMAP4 authentication failed.\n"));
+               log_warning("IMAP4 authentication failed.\n");
 
        return ok;
 }
@@ -2437,7 +2646,7 @@ static gint imap_cmd_login(IMAPSession *session,
 
        ok = imap_cmd_ok(session, NULL);
        if (ok != IMAP_SUCCESS)
-               log_warning(_("IMAP4 login failed.\n"));
+               log_warning("IMAP4 login failed.\n");
 
        return ok;
 }
@@ -2448,53 +2657,6 @@ static gint imap_cmd_logout(IMAPSession *session)
        return imap_cmd_ok(session, NULL);
 }
 
-/* Send CAPABILITY, and examine the server's response to see whether this
- * connection is pre-authenticated or not and build a list of CAPABILITIES. */
-static gint imap_greeting(IMAPSession *session)
-{
-       gchar *capstr;
-       GPtrArray *argbuf;
-
-       imap_gen_send(session, "CAPABILITY");
-       
-       argbuf = g_ptr_array_new();
-
-       if (imap_cmd_ok(session, argbuf) != IMAP_SUCCESS ||
-           ((capstr = search_array_str(argbuf, "CAPABILITY ")) == NULL)) {
-               ptr_array_free_strings(argbuf);
-               g_ptr_array_free(argbuf, TRUE);
-               return -1;
-       }
-
-       session->authenticated = search_array_str(argbuf, "PREAUTH") != NULL;
-       
-       capstr += strlen("CAPABILITY ");
-
-       IMAP_SESSION(session)->capability = g_strsplit(capstr, " ", 0);
-       
-       ptr_array_free_strings(argbuf);
-       g_ptr_array_free(argbuf, TRUE);
-
-       return 0;
-}
-
-static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
-{
-       gchar **p;
-       
-       for (p = session->capability; *p != NULL; ++p)
-               if (g_strcasecmp(*p, cap) == 0)
-                       return TRUE;
-
-       return FALSE;
-}
-
-void imap_free_capabilities(IMAPSession *session)
-{
-       g_strfreev(session->capability);
-       session->capability = NULL;
-}
-
 static gint imap_cmd_noop(IMAPSession *session)
 {
        imap_gen_send(session, "NOOP");
@@ -2561,6 +2723,7 @@ static gint imap_cmd_do_select(IMAPSession *session, const gchar *folder,
        GPtrArray *argbuf;
        gchar *select_cmd;
        gchar *folder_;
+       unsigned int uid_validity_;
 
        *exists = *recent = *unseen = *uid_validity = 0;
        argbuf = g_ptr_array_new();
@@ -2593,11 +2756,12 @@ static gint imap_cmd_do_select(IMAPSession *session, const gchar *folder,
 
        resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
        if (resp_str) {
-               if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
+               if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", &uid_validity_)
                    != 1) {
                        g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
                        THROW;
                }
+               *uid_validity = uid_validity_;
        }
 
        resp_str = search_array_contain_str(argbuf, "UNSEEN");
@@ -2665,7 +2829,8 @@ static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
        return imap_cmd_ok(session, NULL);
 }
 
-static gint imap_cmd_search(IMAPSession *session, const gchar *criteria, GSList **list)
+static gint imap_cmd_search(IMAPSession *session, const gchar *criteria, 
+                           GSList **list)
 {
        gint ok;
        gchar *uidlist;
@@ -2693,7 +2858,7 @@ static gint imap_cmd_search(IMAPSession *session, const gchar *criteria, GSList
                for (p = strlist; *p != NULL; ++p) {
                        guint msgnum;
 
-                       if (sscanf(*p, "%d", &msgnum) == 1)
+                       if (sscanf(*p, "%u", &msgnum) == 1)
                                *list = g_slist_append(*list, GINT_TO_POINTER(msgnum));
                }
                g_strfreev(strlist);
@@ -2704,7 +2869,8 @@ static gint imap_cmd_search(IMAPSession *session, const gchar *criteria, GSList
        return IMAP_SUCCESS;
 }
 
-static gint imap_cmd_fetch(IMAPSession *session, guint32 uid, const gchar *filename)
+static gint imap_cmd_fetch(IMAPSession *session, guint32 uid, 
+                          const gchar *filename)
 {
        gint ok;
        gchar *buf = NULL;
@@ -2740,7 +2906,7 @@ static gint imap_cmd_fetch(IMAPSession *session, guint32 uid, const gchar *filen
        cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
        RETURN_ERROR_IF_FAIL(cur_pos != NULL);
        size_num = atol(size_str);
-       RETURN_ERROR_IF_FAIL(size_num > 0);
+       RETURN_ERROR_IF_FAIL(size_num >= 0);
 
        RETURN_ERROR_IF_FAIL(*cur_pos == '\0');
 
@@ -2748,7 +2914,8 @@ static gint imap_cmd_fetch(IMAPSession *session, guint32 uid, const gchar *filen
 
        g_free(buf);
 
-       if (recv_bytes_write_to_file(SESSION(session)->sock, size_num, filename) != 0)
+       if (recv_bytes_write_to_file(SESSION(session)->sock,
+                                    size_num, filename) != 0)
                return IMAP_ERROR;
 
        if (imap_gen_recv(session, &buf) != IMAP_SUCCESS) {
@@ -2768,17 +2935,19 @@ static gint imap_cmd_fetch(IMAPSession *session, guint32 uid, const gchar *filen
 }
 
 static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
-                           const gchar *file, IMAPFlags flags, gint32 *new_uid)
+                           const gchar *file, IMAPFlags flags, 
+                           guint32 *new_uid)
 {
        gint ok;
-       gint size, newuid;
+       gint size;
        gchar *destfolder_;
        gchar *flag_str;
+       unsigned int new_uid_;
        gchar *ret = NULL;
        gchar buf[BUFFSIZE];
        FILE *fp;
-       GPtrArray *reply;
-       gchar *okmsginfo;
+       GPtrArray *argbuf;
+       gchar *resp_str;
 
        g_return_val_if_fail(file != NULL, IMAP_ERROR);
 
@@ -2795,14 +2964,14 @@ static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
 
        ok = imap_gen_recv(session, &ret);
        if (ok != IMAP_SUCCESS || ret[0] != '+' || ret[1] != ' ') {
-               log_warning(_("can't append %s to %s\n"), file, destfolder_);
+               log_warning("can't append %s to %s\n", file, destfolder_);
                g_free(ret);
                fclose(fp);
                return IMAP_ERROR;
        }
        g_free(ret);
 
-       log_print("IMAP4> %s\n", _("(sending file...)"));
+       log_print("IMAP4> %s\n", "(sending file...)");
 
        while (fgets(buf, sizeof(buf), fp) != NULL) {
                strretchomp(buf);
@@ -2822,31 +2991,62 @@ static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
 
        fclose(fp);
 
-       reply = g_ptr_array_new();
+       if (new_uid != NULL)
+               *new_uid = 0;
+
+       if (new_uid != NULL && session->uidplus) {
+               argbuf = g_ptr_array_new();
+
+               ok = imap_cmd_ok(session, argbuf);
+               if ((ok == IMAP_SUCCESS) && (argbuf->len > 0)) {
+                       resp_str = g_ptr_array_index(argbuf, argbuf->len - 1);
+                       if (resp_str &&
+                           sscanf(resp_str, "%*u OK [APPENDUID %*u %u]",
+                                  &new_uid_) == 1) {
+                               *new_uid = new_uid_;
+                       }
+               }
+
+               ptr_array_free_strings(argbuf);
+               g_ptr_array_free(argbuf, TRUE);
+       } else
+               ok = imap_cmd_ok(session, NULL);
 
-       *new_uid = 0;
-       ok = imap_cmd_ok(session, reply);
        if (ok != IMAP_SUCCESS)
-               log_warning(_("can't append message to %s\n"), destfolder_);
-       else if (
-           (new_uid != NULL) && 
-           (imap_has_capability(session, "UIDPLUS") && reply->len > 0) &&
-           ((okmsginfo = g_ptr_array_index(reply, reply->len - 1)) != NULL) &&
-           (sscanf(okmsginfo, "%*u OK [APPENDUID %*u %u]", &newuid) == 1)) {
-               *new_uid = newuid;
-       }
+               log_warning("can't append message to %s\n",
+                           destfolder_);
 
-       ptr_array_free_strings(reply);
-       g_ptr_array_free(reply, TRUE);
        return ok;
 }
 
+static MsgNumberList *imapset_to_numlist(IMAPSet imapset)
+{
+       gchar **ranges, **range;
+       unsigned int low, high;
+       MsgNumberList *uids = NULL;
+       
+       ranges = g_strsplit(imapset, ",", 0);
+       for (range = ranges; *range != NULL; range++) {
+               printf("%s\n", *range);
+               if (sscanf(*range, "%u:%u", &low, &high) == 1)
+                       uids = g_slist_prepend(uids, GINT_TO_POINTER(low));
+               else {
+                       int i;
+                       for (i = low; i <= high; i++)
+                               uids = g_slist_prepend(uids, GINT_TO_POINTER(i));
+               }
+       }
+       uids = g_slist_reverse(uids);
+       g_strfreev(ranges);
+
+       return uids;
+}
+
 static gint imap_cmd_copy(IMAPSession *session, const gchar *seq_set,
                          const gchar *destfolder, GRelation *uid_mapping)
 {
        gint ok;
        gchar *destfolder_;
-       GPtrArray *reply;
        
        g_return_val_if_fail(session != NULL, IMAP_ERROR);
        g_return_val_if_fail(seq_set != NULL, IMAP_ERROR);
@@ -2855,25 +3055,48 @@ static gint imap_cmd_copy(IMAPSession *session, const gchar *seq_set,
        QUOTE_IF_REQUIRED(destfolder_, destfolder);
        imap_gen_send(session, "UID COPY %s %s", seq_set, destfolder_);
 
-       reply = g_ptr_array_new();
+       if (uid_mapping != NULL && session->uidplus) {
+               GPtrArray *reply;               
+               gchar *resp_str = NULL, *olduids_str, *newuids_str;
+               MsgNumberList *olduids, *old_cur, *newuids, *new_cur;
+
+               reply = g_ptr_array_new();
+               ok = imap_cmd_ok(session, reply);
+               if ((ok == IMAP_SUCCESS) && (reply->len > 0)) {
+                       resp_str = g_ptr_array_index(reply, reply->len - 1);
+                       if (resp_str) {
+                               olduids_str = g_new0(gchar, strlen(resp_str));
+                               newuids_str = g_new0(gchar, strlen(resp_str));
+                               if (sscanf(resp_str, "%*s OK [COPYUID %*u %[0-9,:] %[0-9,:]]",
+                                          olduids_str, newuids_str) == 2) {
+                                       olduids = imapset_to_numlist(olduids_str);
+                                       newuids = imapset_to_numlist(newuids_str);
+
+                                       old_cur = olduids;
+                                       new_cur = newuids;
+                                       while(old_cur != NULL && new_cur != NULL) {
+                                               g_relation_insert(uid_mapping, 
+                                                                 GPOINTER_TO_INT(old_cur->data),
+                                                                 GPOINTER_TO_INT(new_cur->data));
+                                               old_cur = g_slist_next(old_cur);
+                                               new_cur = g_slist_next(new_cur);
+                                       }
+
+                                       g_slist_free(olduids);
+                                       g_slist_free(newuids);
+                               }
+                               g_free(olduids_str);
+                               g_free(newuids_str);
+                       }
+               }
+               ptr_array_free_strings(reply);
+               g_ptr_array_free(reply, TRUE);
+       } else
+               ok = imap_cmd_ok(session, NULL);
 
-       ok = imap_cmd_ok(session, reply);
        if (ok != IMAP_SUCCESS)
-               log_warning(_("can't copy %s to %s\n"), seq_set, destfolder_);
-/*
-       TODO: UIDPLUS
-       
-       - split IMAPSets into uids
-       - g_relation_insert(uid_mapping, olduid, newuid);
-
-       else if (imap_has_capability(session, "UIDPLUS") && reply->len > 0)
-               if ((okmsginfo = g_ptr_array_index(reply, reply->len - 1)) != NULL &&
-                   sscanf(okmsginfo, "%*u OK [COPYUID %*u %u %u]", &olduid, &newuid) == 2 &&
-                   olduid == msgnum)
-                       *new_uid = newuid;
-*/
-       ptr_array_free_strings(reply);
-       g_ptr_array_free(reply, TRUE);
+               log_warning("can't copy %s to %s\n", seq_set, destfolder_);
+
        return ok;
 }
 
@@ -2922,7 +3145,7 @@ static gint imap_cmd_store(IMAPSession *session, IMAPSet seq_set,
        imap_gen_send(session, "UID STORE %s %s", seq_set, sub_cmd);
 
        if ((ok = imap_cmd_ok(session, NULL)) != IMAP_SUCCESS) {
-               log_warning(_("error while imap command: STORE %s %s\n"),
+               log_warning("error while imap command: STORE %s %s\n",
                            seq_set, sub_cmd);
                return ok;
        }
@@ -2930,13 +3153,16 @@ static gint imap_cmd_store(IMAPSession *session, IMAPSet seq_set,
        return IMAP_SUCCESS;
 }
 
-static gint imap_cmd_expunge(IMAPSession *session)
+static gint imap_cmd_expunge(IMAPSession *session, IMAPSet seq_set)
 {
        gint ok;
 
-       imap_gen_send(session, "EXPUNGE");
+       if (seq_set && session->uidplus)
+               imap_gen_send(session, "UID EXPUNGE %s", seq_set);
+       else    
+               imap_gen_send(session, "EXPUNGE");
        if ((ok = imap_cmd_ok(session, NULL)) != IMAP_SUCCESS) {
-               log_warning(_("error while imap command: EXPUNGE\n"));
+               log_warning("error while imap command: EXPUNGE\n");
                return ok;
        }
 
@@ -2949,7 +3175,7 @@ static gint imap_cmd_close(IMAPSession *session)
 
        imap_gen_send(session, "CLOSE");
        if ((ok = imap_cmd_ok(session, NULL)) != IMAP_SUCCESS)
-               log_warning(_("error while imap command: CLOSE\n"));
+               log_warning("error while imap command: CLOSE\n");
 
        return ok;
 }
@@ -3275,7 +3501,7 @@ static gchar *imap_locale_to_modified_utf7(const gchar *from)
                        norm_utf7_len -= 2;
                        from_tmp++;
                        from_len--;
-               } else if (IS_PRINT(*from_tmp)) {
+               } else if (IS_PRINT(*(guchar *)from_tmp)) {
                        /* printable ascii char */
                        *norm_utf7_p = *from_tmp;
                        norm_utf7_p++;
@@ -3287,7 +3513,7 @@ static gchar *imap_locale_to_modified_utf7(const gchar *from)
 
                        /* unprintable char: convert to UTF-7 */
                        p = from_tmp;
-                       while (!IS_PRINT(*p) && conv_len < from_len) {
+                       while (!IS_PRINT(*(guchar *)p) && conv_len < from_len) {
                                mb_len = mblen(p, MB_LEN_MAX);
                                if (mb_len <= 0) {
                                        g_warning("wrong multibyte sequence\n");
@@ -3534,11 +3760,11 @@ static gint get_list_of_uids(Folder *folder, IMAPFolderItem *item, GSList **msgn
        return nummsgs;
 }
 
-gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list)
+gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)
 {
        IMAPFolderItem *item = (IMAPFolderItem *)_item;
        IMAPSession *session;
-       gint ok, nummsgs = 0, exists, recent, unseen, uid_val, uid_next;
+       gint ok, nummsgs = 0, exists, recent, uid_val, uid_next, unseen;
        GSList *uidlist;
        gchar *dir;
        gboolean selected_folder;
@@ -3559,13 +3785,33 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list)
                if (ok != IMAP_SUCCESS)
                        return -1;
                exists = session->exists;
+
+               *old_uids_valid = TRUE;
        } else {
                ok = imap_status(session, IMAP_FOLDER(folder), item->item.path,
                                 &exists, &recent, &uid_next, &uid_val, &unseen);
                if (ok != IMAP_SUCCESS)
                        return -1;
+
+               if(item->item.mtime == uid_val)
+                       *old_uids_valid = TRUE;
+               else {
+                       *old_uids_valid = FALSE;
+
+                       debug_print("Freeing imap uid cache\n");
+                       item->lastuid = 0;
+                       g_slist_free(item->uid_list);
+                       item->uid_list = NULL;
+               
+                       item->item.mtime = uid_val;
+
+                       imap_delete_all_cached_messages((FolderItem *)item);
+               }
        }
 
+       if (!selected_folder)
+               item->uid_next = uid_next;
+
        /* If old uid_next matches new uid_next we can be sure no message
           was added to the folder */
        if (( selected_folder && !session->folder_content_changed) ||
@@ -3587,8 +3833,6 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list)
                        item->uid_list = NULL;
                }
        }
-       if (!selected_folder)
-               item->uid_next = uid_next;
 
        if (exists == 0) {
                *msgnum_list = NULL;
@@ -3731,37 +3975,43 @@ MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
        return msginfo;
 }
 
-gboolean imap_check_msgnum_validity(Folder *folder, FolderItem *_item)
+gboolean imap_scan_required(Folder *folder, FolderItem *_item)
 {
        IMAPSession *session;
        IMAPFolderItem *item = (IMAPFolderItem *)_item;
        gint ok, exists = 0, recent = 0, unseen = 0;
-       guint32 uid_next, uid_validity = 0;
+       guint32 uid_next, uid_val = 0;
+       gboolean selected_folder;
        
        g_return_val_if_fail(folder != NULL, FALSE);
        g_return_val_if_fail(item != NULL, FALSE);
        g_return_val_if_fail(item->item.folder != NULL, FALSE);
        g_return_val_if_fail(FOLDER_CLASS(item->item.folder) == &imap_class, FALSE);
 
+       if (item->item.path == NULL)
+               return FALSE;
+
        session = imap_session_get(folder);
        g_return_val_if_fail(session != NULL, FALSE);
 
-       ok = imap_status(session, IMAP_FOLDER(folder), item->item.path,
-                        &exists, &recent, &uid_next, &uid_validity, &unseen);
-       if (ok != IMAP_SUCCESS)
-               return FALSE;
-
-       if(item->item.mtime == uid_validity)
-               return TRUE;
+       selected_folder = (session->mbox != NULL) &&
+                         (!strcmp(session->mbox, item->item.path));
+       if (selected_folder) {
+               ok = imap_cmd_noop(session);
+               if (ok != IMAP_SUCCESS)
+                       return FALSE;
 
-       debug_print("Freeing imap uid cache\n");
-       item->lastuid = 0;
-       g_slist_free(item->uid_list);
-       item->uid_list = NULL;
-               
-       item->item.mtime = uid_validity;
+               if (session->folder_content_changed)
+                       return TRUE;
+       } else {
+               ok = imap_status(session, IMAP_FOLDER(folder), item->item.path,
+                                &exists, &recent, &uid_next, &uid_val, &unseen);
+               if (ok != IMAP_SUCCESS)
+                       return FALSE;
 
-       imap_delete_all_cached_messages((FolderItem *)item);
+               if ((uid_next != item->uid_next) || (exists < item->item.total_msgs))
+                       return TRUE;
+       }
 
        return FALSE;
 }
@@ -3819,3 +4069,151 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
 
        return;
 }
+
+static gint compare_msginfo(gconstpointer a, gconstpointer b)
+{
+       return ((MsgInfo *)a)->msgnum - ((MsgInfo *)b)->msgnum;
+}
+
+static guint gslist_find_next_num(MsgNumberList **list, guint num)
+{
+       GSList *elem;
+
+       g_return_val_if_fail(list != NULL, -1);
+
+       for (elem = *list; elem != NULL; elem = g_slist_next(elem))
+               if (GPOINTER_TO_INT(elem->data) >= num)
+                       break;
+       *list = elem;
+       return elem != NULL ? GPOINTER_TO_INT(elem->data) : (gint)-1;
+}
+
+/*
+ * NEW and DELETED flags are not syncronized
+ * - The NEW/RECENT flags in IMAP folders can not really be directly
+ *   modified by Sylpheed
+ * - The DELETE/DELETED flag in IMAP and Sylpheed don't have the same
+ *   meaning, in IMAP it always removes the messages from the FolderItem
+ *   in Sylpheed it can mean to move the message to trash
+ */
+static gint imap_get_flags(Folder *folder, FolderItem *item,
+                           MsgInfoList *msginfo_list, GRelation *msgflags)
+{
+       IMAPSession *session;
+       GSList *sorted_list;
+       /*
+       GSList *new = NULL, *p_new;
+       GSList *deleted = NULL, *p_deleted;
+       */
+       GSList *unseen = NULL, *answered = NULL, *flagged = NULL;
+       GSList *p_unseen, *p_answered, *p_flagged;
+       GSList *elem;
+       GSList *seq_list, *cur;
+       gboolean reverse_seen = FALSE;
+       GString *cmd_buf;
+       gint ok;
+       gint exists_cnt, recent_cnt, unseen_cnt, uid_next;
+       guint32 uidvalidity;
+
+       g_return_val_if_fail(folder != NULL, -1);
+       g_return_val_if_fail(item != NULL, -1);
+       g_return_val_if_fail(msginfo_list != NULL, -1);
+
+       session = imap_session_get(folder);
+       g_return_val_if_fail(session != NULL, -1);
+
+       ok = imap_select(session, IMAP_FOLDER(folder), item->path,
+                       NULL, NULL, NULL, NULL);
+       if (ok != IMAP_SUCCESS)
+               return -1;
+
+       ok = imap_status(session, IMAP_FOLDER(folder), item->path,
+                        &exists_cnt, &recent_cnt, &uid_next, &uidvalidity, &unseen_cnt);
+
+       if (unseen_cnt > exists_cnt / 2)
+               reverse_seen = TRUE;
+
+       cmd_buf = g_string_new(NULL);
+
+       sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
+
+       seq_list = imap_get_seq_set_from_msglist(msginfo_list);
+
+       for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
+               IMAPSet imapset = cur->data;
+/*
+               g_string_sprintf(cmd_buf, "RECENT UID %s", imapset);
+               imap_cmd_search(session, cmd_buf->str, &p_new);
+               new = g_slist_concat(new, p_new);
+*/
+               g_string_sprintf(cmd_buf, "%sSEEN UID %s", reverse_seen ? "" : "UN", imapset);
+               imap_cmd_search(session, cmd_buf->str, &p_unseen);
+               unseen = g_slist_concat(unseen, p_unseen);
+
+               g_string_sprintf(cmd_buf, "ANSWERED UID %s", imapset);
+               imap_cmd_search(session, cmd_buf->str, &p_answered);
+               answered = g_slist_concat(answered, p_answered);
+
+               g_string_sprintf(cmd_buf, "FLAGGED UID %s", imapset);
+               imap_cmd_search(session, cmd_buf->str, &p_flagged);
+               flagged = g_slist_concat(flagged, p_flagged);
+/*
+               g_string_sprintf(cmd_buf, "DELETED UID %s", imapset);
+               imap_cmd_search(session, cmd_buf->str, &p_deleted);
+               deleted = g_slist_concat(deleted, p_deleted);
+*/
+       }
+
+/*
+       p_new = new;
+*/
+       p_unseen = unseen;
+       p_answered = answered;
+       p_flagged = flagged;
+/*
+       p_deleted = deleted;
+*/     
+       for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
+               MsgInfo *msginfo;
+               MsgPermFlags flags;
+               gboolean wasnew;
+               
+               msginfo = (MsgInfo *) elem->data;
+               flags = msginfo->flags.perm_flags;
+               wasnew = (flags & MSG_NEW);
+               flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_MARKED);
+               if (reverse_seen)
+                       flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
+               /*
+               if (gslist_find_next_num(&p_new, msginfo->msgnum) == msginfo->msgnum)
+                       flags |= MSG_NEW;
+               */
+               if (gslist_find_next_num(&p_unseen, msginfo->msgnum) == msginfo->msgnum) {
+                       if (!reverse_seen) {
+                               flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
+                       } else {
+                               flags &= ~(MSG_UNREAD | MSG_NEW);
+                       }
+               }
+               if (gslist_find_next_num(&p_answered, msginfo->msgnum) == msginfo->msgnum)
+                       flags |= MSG_REPLIED;
+               if (gslist_find_next_num(&p_flagged, msginfo->msgnum) == msginfo->msgnum)
+                       flags |= MSG_MARKED;
+               /*
+               if (gslist_find_next_num(&p_deleted, msginfo->msgnum) == msginfo->msgnum)
+                       MSG_SET_PERM_FLAGS(msginfo->flags, MSG_DELETED);
+                */
+               g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
+       }
+
+       imap_seq_set_free(seq_list);
+       /* g_slist_free(deleted); */
+       g_slist_free(flagged);
+       g_slist_free(answered);
+       g_slist_free(unseen);
+       /* new not freed in original patch ??? */
+       g_slist_free(sorted_list);
+       g_string_free(cmd_buf, TRUE);
+
+       return 0;
+}