01e49c51f32f201b3e6bf62834306e3cd5ea0cb3
[claws.git] / src / inc.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2016 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 #ifdef HAVE_CONFIG_H
20 #  include "config.h"
21 #include "claws-features.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gtk/gtk.h>
29 #include <stdio.h>
30 #include <unistd.h>
31 #include <string.h>
32
33 #include "main.h"
34 #include "inc.h"
35 #include "mainwindow.h"
36 #include "folderview.h"
37 #include "summaryview.h"
38 #include "prefs_common.h"
39 #include "prefs_account.h"
40 #include "account.h"
41 #include "procmsg.h"
42 #include "proxy.h"
43 #include "socket.h"
44 #include "ssl.h"
45 #include "pop.h"
46 #include "recv.h"
47 #include "mbox.h"
48 #include "file-utils.h"
49 #include "utils.h"
50 #include "gtkutils.h"
51 #include "statusbar.h"
52 #include "msgcache.h"
53 #include "manage_window.h"
54 #include "stock_pixmap.h"
55 #include "progressdialog.h"
56 #include "inputdialog.h"
57 #include "alertpanel.h"
58 #include "folder.h"
59 #include "filtering.h"
60 #include "log.h"
61 #include "hooks.h"
62 #include "logwindow.h"
63 #include "passwordstore.h"
64
65 extern SessionStats session_stats;
66
67 static GList *inc_dialog_list = NULL;
68
69 static time_t inc_offline_overridden_yes = 0;
70 static time_t inc_offline_overridden_no  = 0;
71
72 guint inc_lock_count = 0;
73
74 static GdkPixbuf *currentpix;
75 static GdkPixbuf *errorpix;
76 static GdkPixbuf *okpix;
77
78 #define MESSAGEBUFSIZE  8192
79
80 static void inc_update_stats(gint new_msgs);
81 static void inc_finished                (MainWindow             *mainwin,
82                                          gboolean                new_messages,
83                                          gboolean                autocheck);
84 static gint inc_account_mail_real       (MainWindow             *mainwin,
85                                          PrefsAccount           *account);
86
87 static IncProgressDialog *inc_progress_dialog_create
88                                         (gboolean                autocheck);
89 static void inc_progress_dialog_set_list(IncProgressDialog      *inc_dialog);
90 static void inc_progress_dialog_destroy (IncProgressDialog      *inc_dialog);
91
92 static IncSession *inc_session_new      (PrefsAccount           *account);
93 static void inc_session_destroy         (IncSession             *session);
94 static gint inc_start                   (IncProgressDialog      *inc_dialog);
95 static IncState inc_pop3_session_do     (IncSession             *session);
96
97 static void inc_progress_dialog_update  (IncProgressDialog      *inc_dialog,
98                                          IncSession             *inc_session);
99
100 static void inc_progress_dialog_set_label
101                                         (IncProgressDialog      *inc_dialog,
102                                          IncSession             *inc_session);
103 static void inc_progress_dialog_set_progress
104                                         (IncProgressDialog      *inc_dialog,
105                                          IncSession             *inc_session);
106
107 static void inc_progress_dialog_update_periodic
108                                         (IncProgressDialog      *inc_dialog,
109                                          IncSession             *inc_session);
110
111 static gint inc_recv_data_progressive   (Session        *session,
112                                          guint           cur_len,
113                                          guint           total_len,
114                                          gpointer        data);
115 static gint inc_recv_data_finished      (Session        *session,
116                                          guint           len,
117                                          gpointer        data);
118 static gint inc_recv_message            (Session        *session,
119                                          const gchar    *msg,
120                                          gpointer        data);
121 static gint inc_drop_message            (Pop3Session    *session,
122                                          const gchar    *file);
123
124 static void inc_put_error               (IncState        istate,
125                                          Pop3Session    *session);
126
127 static void inc_showlog_cb              (GtkWidget      *widget,
128                                          gpointer        data);
129 static void inc_cancel_cb               (GtkWidget      *widget,
130                                          gpointer        data);
131 static gint inc_dialog_delete_cb        (GtkWidget      *widget,
132                                          GdkEventAny    *event,
133                                          gpointer        data);
134
135 static gint get_spool                   (FolderItem     *dest,
136                                          const gchar    *mbox,
137                                          PrefsAccount   *account);
138
139 static gint inc_spool_account(PrefsAccount *account);
140 static void inc_autocheck_timer_set_interval    (guint           interval);
141 static gint inc_autocheck_func                  (gpointer        data);
142
143 static void inc_notify_cmd              (gint new_msgs, 
144                                          gboolean notify);
145
146 static void inc_update_stats(gint new_msgs)
147 {
148         /* update session statistics */
149         session_stats.received += new_msgs;
150 }
151
152 /**
153  * inc_finished:
154  * @mainwin: Main window.
155  * @new_messages: TRUE if some messages have been received.
156  * 
157  * Update the folder view and the summary view after receiving
158  * messages.  If @new_messages is FALSE, this function avoids unneeded
159  * updating.
160  **/
161 static void inc_finished(MainWindow *mainwin, gboolean new_messages, gboolean autocheck)
162 {
163         if (prefs_common.scan_all_after_inc)
164                 folderview_check_new(NULL);
165
166         if (!autocheck && new_messages && prefs_common.open_inbox_on_inc) {
167                 FolderItem *item = NULL;
168
169                 if (cur_account && cur_account->inbox)
170                         item = folder_find_item_from_identifier(cur_account->inbox);
171                 if (item == NULL && cur_account && cur_account->folder)
172                         item = cur_account->folder->inbox;
173                 if (item == NULL)
174                         item = folder_get_default_inbox();
175
176                 folderview_unselect(mainwin->folderview);
177                 folderview_select(mainwin->folderview, item);
178         }
179         statusbar_progress_all(0,0,0);
180 }
181
182 void inc_mail(MainWindow *mainwin, gboolean notify)
183 {
184         gint new_msgs = 0;
185         gint account_new_msgs = 0;
186
187         if (inc_lock_count) return;
188
189         if (prefs_common.work_offline && 
190             !inc_offline_should_override(TRUE,
191                 _("Claws Mail needs network access in order "
192                   "to get mails.")))
193                 return;
194
195         inc_lock();
196         inc_autocheck_timer_remove();
197         main_window_lock(mainwin);
198
199         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
200                 /* external incorporating program */
201                 if (execute_command_line(prefs_common.extinc_cmd, FALSE, NULL) < 0) {
202                         main_window_unlock(mainwin);
203                         inc_autocheck_timer_set();
204                         inc_unlock();
205                         return;
206                 }
207         } else {
208                 account_new_msgs = inc_account_mail_real(mainwin, cur_account);
209                 if (account_new_msgs > 0)
210                         new_msgs += account_new_msgs;
211         }
212
213         inc_update_stats(new_msgs);
214         inc_finished(mainwin, new_msgs > 0, FALSE);
215         main_window_unlock(mainwin);
216         inc_notify_cmd(new_msgs, notify);
217         inc_autocheck_timer_set();
218         inc_unlock();
219 }
220
221 void inc_pop_before_smtp(PrefsAccount *acc)
222 {
223         IncProgressDialog *inc_dialog;
224         IncSession *session;
225         MainWindow *mainwin;
226
227         mainwin = mainwindow_get_mainwindow();
228
229         session = inc_session_new(acc);
230         if (!session) return;
231         POP3_SESSION(session->session)->pop_before_smtp = TRUE;
232                 
233         inc_dialog = inc_progress_dialog_create(FALSE);
234         inc_dialog->queue_list = g_list_append(inc_dialog->queue_list,
235                                                session);
236         /* FIXME: assumes to attach to first main window */
237         inc_dialog->mainwin = mainwin;
238         inc_progress_dialog_set_list(inc_dialog);
239
240         if (mainwin) {
241                 toolbar_main_set_sensitive(mainwin);
242                 main_window_set_menu_sensitive(mainwin);
243         }
244                         
245         inc_start(inc_dialog);
246 }
247
248 static gint inc_account_mail_real(MainWindow *mainwin, PrefsAccount *account)
249 {
250         IncProgressDialog *inc_dialog;
251         IncSession *session;
252         
253         switch (account->protocol) {
254         case A_IMAP4:
255         case A_NNTP:
256                 /* Melvin: bug [14]
257                  * FIXME: it should return foldeview_check_new() value.
258                  * TODO: do it when bug [19] is fixed (IMAP folder sets 
259                  * an incorrect new message count)
260                  */
261                 folderview_check_new(FOLDER(account->folder));
262                 return 0;
263         case A_POP3:
264                 session = inc_session_new(account);
265                 if (!session) return 0;
266                 
267                 inc_dialog = inc_progress_dialog_create(FALSE);
268                 inc_dialog->queue_list = g_list_append(inc_dialog->queue_list,
269                                                        session);
270                 inc_dialog->mainwin = mainwin;
271                 inc_progress_dialog_set_list(inc_dialog);
272
273                 if (mainwin) {
274                         toolbar_main_set_sensitive(mainwin);
275                         main_window_set_menu_sensitive(mainwin);
276                 }
277                         
278                 return inc_start(inc_dialog);
279
280         case A_LOCAL:
281                 return inc_spool_account(account);
282
283         default:
284                 break;
285         }
286         return 0;
287 }
288
289 gint inc_account_mail(MainWindow *mainwin, PrefsAccount *account)
290 {
291         gint new_msgs;
292
293         if (inc_lock_count) return 0;
294
295         if (account->receive_in_progress) return 0;
296
297         if (prefs_common.work_offline && 
298             !inc_offline_should_override(TRUE,
299                 _("Claws Mail needs network access in order "
300                   "to get mails.")))
301                 return 0;
302
303         inc_autocheck_timer_remove();
304         main_window_lock(mainwin);
305
306         new_msgs = inc_account_mail_real(mainwin, account);
307
308         inc_update_stats(new_msgs);
309         inc_finished(mainwin, new_msgs > 0, FALSE);
310         main_window_unlock(mainwin);
311         inc_autocheck_timer_set();
312
313         return new_msgs;
314 }
315
316 void inc_account_list_mail(MainWindow *mainwin, GList *account_list, gboolean autocheck,
317                           gboolean notify)
318 {
319         GList *list, *queue_list = NULL;
320         IncProgressDialog *inc_dialog;
321         gint new_msgs = 0, num;
322
323         if (prefs_common.work_offline && 
324             !inc_offline_should_override( (autocheck == FALSE),
325                 _("Claws Mail needs network access in order "
326                   "to get mails.")))
327                 return;
328
329         if (inc_lock_count) return;
330
331         main_window_lock(mainwin);
332
333         if (!account_list) {
334                 inc_update_stats(new_msgs);
335                 inc_finished(mainwin, new_msgs > 0, autocheck);
336                 main_window_unlock(mainwin);
337                 inc_notify_cmd(new_msgs, notify);
338                 return;
339         }
340
341         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
342                 /* external incorporating program */
343                 if (execute_command_line(prefs_common.extinc_cmd, FALSE, NULL) < 0) {
344                         log_error(LOG_PROTOCOL, _("%s failed\n"), prefs_common.extinc_cmd);
345                         
346                         main_window_unlock(mainwin);
347                         return;
348                 }
349         }
350
351         /* Check all accounts in the list, one by one. */
352         for (list = account_list; list != NULL; list = list->next) {
353                 PrefsAccount *account = list->data;
354
355                 if (account == NULL) {
356                         debug_print("INC: Huh? inc_account_list_mail() got a NULL account, this should not happen!\n");
357                         continue;
358                 }
359
360                 debug_print("INC: checking account %d\n", account->account_id);
361                 switch (account->protocol) {
362                         case A_POP3:
363                                 if (!(account->receive_in_progress)) {
364                                         IncSession *session = inc_session_new(account);
365
366                                         if (session != NULL) {
367                                                 debug_print("INC: adding POP3 account %d to inc queue\n",
368                                                                 account->account_id);
369                                                 queue_list = g_list_append(queue_list, session);
370                                         }
371                                 }
372                                 break;
373
374                         case A_IMAP4:
375                         case A_NNTP:
376                                 new_msgs += folderview_check_new(FOLDER(account->folder));
377                                 break;
378
379                         case A_LOCAL:
380                                 num = inc_spool_account(account);
381                                 if (num > 0)
382                                         new_msgs += num;
383                                 break;
384
385                         case A_NONE:
386                                 /* Nothing to do here, it's a SMTP-only account. */
387                                 break;
388
389                         default:
390                                 debug_print("INC: encountered account %d with unknown protocol %d, ignoring\n",
391                                                 account->account_id, account->protocol);
392                                 break;
393                 }
394         }
395
396
397
398         if (queue_list) {
399                 inc_dialog = inc_progress_dialog_create(autocheck);
400                 inc_dialog->queue_list = queue_list;
401                 inc_dialog->mainwin = mainwin;
402                 inc_progress_dialog_set_list(inc_dialog);
403
404                 toolbar_main_set_sensitive(mainwin);
405                 main_window_set_menu_sensitive(mainwin);
406                 new_msgs += inc_start(inc_dialog);
407         }
408
409         inc_update_stats(new_msgs);
410         inc_finished(mainwin, new_msgs > 0, autocheck);
411         main_window_unlock(mainwin);
412         inc_notify_cmd(new_msgs, notify);
413 }
414
415 void inc_all_account_mail(MainWindow *mainwin, gboolean autocheck,
416                           gboolean check_at_startup, gboolean notify)
417 {
418         GList *list, *list2 = NULL;
419         gboolean condition;
420         gboolean hide_dialog = FALSE;
421
422         debug_print("INC: inc_all_account_mail(), autocheck: %s\n",
423                         autocheck ? "YES" : "NO");
424
425         /* Collect list of accounts which use the global autocheck interval. */
426         for (list = account_get_list(); list != NULL; list = list->next) {
427                 PrefsAccount *account = list->data;
428
429                 /* Nothing to do for SMTP-only accounts. */
430                 if (account->protocol == A_NONE)
431                         continue;
432
433                 /* Set up condition which decides whether or not to check
434                  * this account, based on whether we're doing global autocheck
435                  * or a check at startup or a manual 'Get all' check. */
436                 if (autocheck)
437                         condition = prefs_common_get_prefs()->autochk_newmail
438                                 && account->autochk_use_default;
439                 else if (check_at_startup || (!check_at_startup && !autocheck))
440                         condition = account->recv_at_getall;
441
442                 if (condition) {
443                         debug_print("INC: will check account %d\n", account->account_id);
444                         list2 = g_list_append(list2, account);
445                 }
446         }
447
448         /* Do the check on the collected accounts. */
449         if (list2 != NULL) {
450                 if (autocheck || check_at_startup)
451                         hide_dialog = TRUE;
452                 inc_account_list_mail(mainwin, list2, hide_dialog, notify);
453                 g_list_free(list2);
454         }
455 }
456
457 static void inc_progress_dialog_size_allocate_cb(GtkWidget *widget,
458                                          GtkAllocation *allocation)
459 {
460         cm_return_if_fail(allocation != NULL);
461
462         prefs_common.receivewin_width = allocation->width;
463         prefs_common.receivewin_height = allocation->height;
464 }
465
466 static IncProgressDialog *inc_progress_dialog_create(gboolean autocheck)
467 {
468         IncProgressDialog *dialog;
469         ProgressDialog *progress;
470         static GdkGeometry geometry;
471
472         dialog = g_new0(IncProgressDialog, 1);
473
474         progress = progress_dialog_create();
475         gtk_window_set_title(GTK_WINDOW(progress->window),
476                              _("Retrieving new messages"));
477         g_signal_connect(G_OBJECT(progress->showlog_btn), "clicked",
478                          G_CALLBACK(inc_showlog_cb), dialog);
479         g_signal_connect(G_OBJECT(progress->cancel_btn), "clicked",
480                          G_CALLBACK(inc_cancel_cb), dialog);
481         g_signal_connect(G_OBJECT(progress->window), "delete_event",
482                          G_CALLBACK(inc_dialog_delete_cb), dialog);
483         g_signal_connect(G_OBJECT(progress->window), "size_allocate",
484                          G_CALLBACK(inc_progress_dialog_size_allocate_cb), NULL);
485         /* manage_window_set_transient(GTK_WINDOW(progress->window)); */
486
487         progress_dialog_get_fraction(progress);
488
489         stock_pixbuf_gdk(STOCK_PIXMAP_COMPLETE, &okpix);
490         stock_pixbuf_gdk(STOCK_PIXMAP_CONTINUE, &currentpix);
491         stock_pixbuf_gdk(STOCK_PIXMAP_ERROR, &errorpix);
492
493         if (!geometry.min_height) {
494                 geometry.min_width = 460;
495                 geometry.min_height = 250;
496         }
497
498         gtk_window_set_geometry_hints(GTK_WINDOW(progress->window), NULL, &geometry,
499                                       GDK_HINT_MIN_SIZE);
500         gtk_widget_set_size_request(progress->window, prefs_common.receivewin_width,
501                                     prefs_common.receivewin_height);
502
503         if (prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS ||
504             (prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL &&
505              !autocheck)) {
506                 dialog->show_dialog = TRUE;
507                 gtk_widget_show_now(progress->window);
508         }
509
510         dialog->dialog = progress;
511         dialog->progress_tv = g_date_time_new_now_local();
512         dialog->folder_tv = g_date_time_new_now_local();
513         dialog->queue_list = NULL;
514         dialog->cur_row = 0;
515
516         inc_dialog_list = g_list_append(inc_dialog_list, dialog);
517
518         return dialog;
519 }
520
521 static void inc_progress_dialog_set_list(IncProgressDialog *inc_dialog)
522 {
523         GList *list;
524
525         for (list = inc_dialog->queue_list; list != NULL; list = list->next) {
526                 IncSession *session = list->data;
527                 Pop3Session *pop3_session = POP3_SESSION(session->session);
528
529                 session->data = inc_dialog;
530
531                 progress_dialog_list_set(inc_dialog->dialog,
532                                          -1, NULL,
533                                          pop3_session->ac_prefs->account_name,
534                                          _("Standby"));
535         }
536 }
537
538 static void inc_progress_dialog_clear(IncProgressDialog *inc_dialog)
539 {
540         progress_dialog_get_fraction(inc_dialog->dialog);
541         progress_dialog_set_label(inc_dialog->dialog, "");
542         if (inc_dialog->mainwin)
543                 main_window_progress_off(inc_dialog->mainwin);
544 }
545
546 static void inc_progress_dialog_destroy(IncProgressDialog *inc_dialog)
547 {
548         cm_return_if_fail(inc_dialog != NULL);
549
550         inc_dialog_list = g_list_remove(inc_dialog_list, inc_dialog);
551
552         if (inc_dialog->mainwin)
553                 main_window_progress_off(inc_dialog->mainwin);
554         progress_dialog_destroy(inc_dialog->dialog);
555
556 #if GLIB_CHECK_VERSION(2,26,1)
557         g_date_time_unref(inc_dialog->progress_tv);
558         g_date_time_unref(inc_dialog->folder_tv);
559 #endif
560
561         g_free(inc_dialog);
562 }
563
564 static IncSession *inc_session_new(PrefsAccount *account)
565 {
566         IncSession *session;
567
568         cm_return_val_if_fail(account != NULL, NULL);
569
570         if (account->protocol != A_POP3)
571                 return NULL;
572         if (!account->recv_server || !account->userid)
573                 return NULL;
574
575         session = g_new0(IncSession, 1);
576
577         session->session = pop3_session_new(account);
578         session->session->data = session;
579         POP3_SESSION(session->session)->drop_message = inc_drop_message;
580         session_set_recv_message_notify(session->session,
581                                         inc_recv_message, session);
582         session_set_recv_data_progressive_notify(session->session,
583                                                  inc_recv_data_progressive,
584                                                  session);
585         session_set_recv_data_notify(session->session,
586                                      inc_recv_data_finished, session);
587
588         return session;
589 }
590
591 static void inc_session_destroy(IncSession *session)
592 {
593         cm_return_if_fail(session != NULL);
594
595         session_destroy(session->session);
596         g_free(session);
597 }
598
599 static gint pop3_get_port(Pop3Session *pop3_session)
600 {
601 #ifdef USE_GNUTLS
602         return pop3_session->ac_prefs->set_popport ?
603                 pop3_session->ac_prefs->popport :
604                 pop3_session->ac_prefs->ssl_pop == SSL_TUNNEL ? 995 : 110;
605 #else
606         return pop3_session->ac_prefs->set_popport ?
607                 pop3_session->ac_prefs->popport : 110;
608 #endif
609 }
610
611 static gint inc_start(IncProgressDialog *inc_dialog)
612 {
613         IncSession *session;
614         GList *qlist;
615         Pop3Session *pop3_session;
616         IncState inc_state;
617         gint error_num = 0;
618         gint new_msgs = 0;
619         gchar *msg;
620         gchar *fin_msg;
621         FolderItem *processing, *inbox;
622         GSList *msglist, *msglist_element;
623         gboolean cancelled = FALSE;
624
625         qlist = inc_dialog->queue_list;
626         while (qlist != NULL) {
627                 GList *next = qlist->next;
628
629                 session = qlist->data;
630                 pop3_session = POP3_SESSION(session->session); 
631                 pop3_session->user = g_strdup(pop3_session->ac_prefs->userid);
632
633                 if (inc_dialog->show_dialog)
634                         manage_window_focus_in
635                                 (inc_dialog->dialog->window,
636                                  NULL, NULL);
637
638                 if (password_get(pop3_session->user,
639                                         pop3_session->ac_prefs->recv_server,
640                                         "pop3", pop3_get_port(pop3_session),
641                                         &(pop3_session->pass))) {
642                         /* NOP */;
643                 } else if ((pop3_session->pass = passwd_store_get_account(
644                                                 pop3_session->ac_prefs->account_id, PWS_ACCOUNT_RECV)) == NULL) {
645                         gchar *pass;
646
647                         pass = input_dialog_query_password_keep
648                                 (pop3_session->ac_prefs->recv_server,
649                                  pop3_session->user,
650                                  &(pop3_session->ac_prefs->session_passwd));
651
652                         if (pass) {
653                                 pop3_session->pass = pass;
654                         }
655                 }
656
657                 if (inc_dialog->show_dialog)
658                         manage_window_focus_out
659                                 (inc_dialog->dialog->window,
660                                  NULL, NULL);
661
662                 qlist = next;
663         }
664
665 #define SET_PIXMAP_AND_TEXT(pix, str)                                      \
666 {                                                                          \
667         progress_dialog_list_set(inc_dialog->dialog,                       \
668                                  inc_dialog->cur_row,                      \
669                                  pix,                                      \
670                                  NULL,                                     \
671                                  str);                                     \
672 }
673
674         for (; inc_dialog->queue_list != NULL && !cancelled; inc_dialog->cur_row++) {
675                 session = inc_dialog->queue_list->data;
676                 pop3_session = POP3_SESSION(session->session);
677                 GSList *filtered, *unfiltered;
678
679                 if (pop3_session->pass == NULL) {
680                         SET_PIXMAP_AND_TEXT(okpix, _("Cancelled"));
681                         inc_session_destroy(session);
682                         inc_dialog->queue_list =
683                                 g_list_remove(inc_dialog->queue_list, session);
684                         continue;
685                 }
686
687                 inc_progress_dialog_clear(inc_dialog);
688                 progress_dialog_scroll_to_row(inc_dialog->dialog,
689                                               inc_dialog->cur_row);
690
691                 SET_PIXMAP_AND_TEXT(currentpix, _("Retrieving"));
692
693                 /* begin POP3 session */
694                 inc_state = inc_pop3_session_do(session);
695
696                 switch (inc_state) {
697                 case INC_SUCCESS:
698                         if (pop3_session->cur_total_num > 0)
699                                 msg = g_strdup_printf(
700                                         ngettext("Done (%d message (%s) received)",
701                                                  "Done (%d messages (%s) received)",
702                                          pop3_session->cur_total_num),
703                                          pop3_session->cur_total_num,
704                                          to_human_readable((goffset)pop3_session->cur_total_recv_bytes));
705                         else
706                                 msg = g_strdup_printf(_("Done (no new messages)"));
707                         SET_PIXMAP_AND_TEXT(okpix, msg);
708                         g_free(msg);
709                         break;
710                 case INC_CONNECT_ERROR:
711                         SET_PIXMAP_AND_TEXT(errorpix, _("Connection failed"));
712                         break;
713                 case INC_AUTH_FAILED:
714                         SET_PIXMAP_AND_TEXT(errorpix, _("Auth failed"));
715                         if (pop3_session->ac_prefs->session_passwd) {
716                                 g_free(pop3_session->ac_prefs->session_passwd);
717                                 pop3_session->ac_prefs->session_passwd = NULL;
718                         }
719                         break;
720                 case INC_LOCKED:
721                         SET_PIXMAP_AND_TEXT(errorpix, _("Locked"));
722                         break;
723                 case INC_ERROR:
724                 case INC_NO_SPACE:
725                 case INC_IO_ERROR:
726                 case INC_SOCKET_ERROR:
727                 case INC_EOF:
728                         SET_PIXMAP_AND_TEXT(errorpix, _("Error"));
729                         break;
730                 case INC_TIMEOUT:
731                         SET_PIXMAP_AND_TEXT(errorpix, _("Timeout"));
732                         break;
733                 case INC_CANCEL:
734                         SET_PIXMAP_AND_TEXT(okpix, _("Cancelled"));
735                         if (!inc_dialog->show_dialog)
736                                 cancelled = TRUE;
737                         break;
738                 default:
739                         break;
740                 }
741                 
742                 if (pop3_session->error_val == PS_AUTHFAIL) {
743                         if(!prefs_common.no_recv_err_panel) {
744                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
745                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL) && focus_window))
746                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
747                         }
748                 }
749
750                 /* CLAWS: perform filtering actions on dropped message */
751                 /* CLAWS: get default inbox (perhaps per account) */
752                 if (pop3_session->ac_prefs->inbox) {
753                         /* CLAWS: get destination folder / mailbox */
754                         inbox = folder_find_item_from_identifier(pop3_session->ac_prefs->inbox);
755                         if (!inbox)
756                                 inbox = folder_get_default_inbox();
757                 } else
758                         inbox = folder_get_default_inbox();
759
760                 /* get list of messages in processing */
761                 processing = folder_get_default_processing(pop3_session->ac_prefs->account_id);
762                 folder_item_scan(processing);
763                 msglist = folder_item_get_msg_list(processing);
764
765                 /* process messages */
766                 folder_item_update_freeze();
767                 
768                 procmsg_msglist_filter(msglist, pop3_session->ac_prefs, 
769                                 &filtered, &unfiltered, 
770                                 pop3_session->ac_prefs->filter_on_recv);
771
772                 filtering_move_and_copy_msgs(msglist);
773                 if (unfiltered != NULL)         
774                         folder_item_move_msgs(inbox, unfiltered);
775
776                 for(msglist_element = msglist; msglist_element != NULL; 
777                     msglist_element = msglist_element->next) {
778                         procmsg_msginfo_free((MsgInfo**)&(msglist_element->data));
779                 }
780                 folder_item_update_thaw();
781                 
782                 g_slist_free(msglist);
783                 g_slist_free(filtered);
784                 g_slist_free(unfiltered);
785
786                 statusbar_pop_all();
787
788                 new_msgs += pop3_session->cur_total_num;
789
790                 pop3_write_uidl_list(pop3_session);
791
792                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
793                         error_num++;
794                         if (inc_dialog->show_dialog)
795                                 manage_window_focus_in
796                                         (inc_dialog->dialog->window,
797                                          NULL, NULL);
798                         inc_put_error(inc_state, pop3_session);
799                         if (inc_dialog->show_dialog)
800                                 manage_window_focus_out
801                                         (inc_dialog->dialog->window,
802                                          NULL, NULL);
803                         if (inc_state == INC_NO_SPACE ||
804                             inc_state == INC_IO_ERROR)
805                                 break;
806                 }
807                 folder_item_free_cache(processing, TRUE);
808
809                 inc_session_destroy(session);
810                 inc_dialog->queue_list =
811                         g_list_remove(inc_dialog->queue_list, session);
812         }
813
814 #undef SET_PIXMAP_AND_TEXT
815
816         if (new_msgs > 0)
817                 fin_msg = g_strdup_printf(ngettext("Finished (%d new message)",
818                                                    "Finished (%d new messages)",
819                                                    new_msgs), new_msgs);
820         else
821                 fin_msg = g_strdup_printf(_("Finished (no new messages)"));
822
823         progress_dialog_set_label(inc_dialog->dialog, fin_msg);
824
825         while (inc_dialog->queue_list != NULL) {
826                 session = inc_dialog->queue_list->data;
827                 inc_session_destroy(session);
828                 inc_dialog->queue_list =
829                         g_list_remove(inc_dialog->queue_list, session);
830         }
831
832         if (prefs_common.close_recv_dialog || !inc_dialog->show_dialog)
833                 inc_progress_dialog_destroy(inc_dialog);
834         else {
835                 gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window),
836                                      fin_msg);
837                 gtk_button_set_label(GTK_BUTTON(inc_dialog->dialog->cancel_btn),
838                                      GTK_STOCK_CLOSE);
839         }
840
841         g_free(fin_msg);
842
843         return new_msgs;
844 }
845
846 static IncState inc_pop3_session_do(IncSession *session)
847 {
848         Pop3Session *pop3_session = POP3_SESSION(session->session);
849         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
850         PrefsAccount *ac = pop3_session->ac_prefs;
851         gchar *server;
852         gchar *account_name;
853         gushort port;
854         gchar *buf;
855         ProxyInfo *proxy_info = NULL;
856
857         debug_print("getting new messages of account %s...\n",
858                     ac->account_name);
859                     
860         ac->last_pop_login_time = time(NULL);
861
862         buf = g_strdup_printf(_("%s: Retrieving new messages"),
863                               ac->recv_server);
864         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
865         g_free(buf);
866
867         server = ac->recv_server;
868         account_name = ac->account_name;
869         port = pop3_get_port(pop3_session);
870
871 #ifdef USE_GNUTLS
872         SESSION(pop3_session)->ssl_type = ac->ssl_pop;
873         if (ac->ssl_pop != SSL_NONE)
874                 SESSION(pop3_session)->nonblocking =
875                         ac->use_nonblocking_ssl;
876 #else
877         if (ac->ssl_pop != SSL_NONE) {
878                 if (alertpanel_full(_("Insecure connection"),
879                         _("This connection is configured to be secured "
880                           "using SSL/TLS, but SSL/TLS is not available "
881                           "in this build of Claws Mail. \n\n"
882                           "Do you want to continue connecting to this "
883                           "server? The communication would not be "
884                           "secure."),
885                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), NULL,
886                                 ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING) != G_ALERTALTERNATE)
887                         return INC_CANCEL;
888         }
889 #endif
890
891         buf = g_strdup_printf(_("Account '%s': Connecting to POP3 server: %s:%d..."),
892                                 account_name, server, port);
893         statusbar_print_all("%s", buf);
894         log_message(LOG_PROTOCOL, "%s\n", buf);
895
896         progress_dialog_set_label(inc_dialog->dialog, buf);
897
898         if (ac->use_proxy) {
899                 if (ac->use_default_proxy) {
900                         proxy_info = (ProxyInfo *)&(prefs_common.proxy_info);
901                         if (proxy_info->use_proxy_auth)
902                                 proxy_info->proxy_pass = passwd_store_get(PWS_CORE, PWS_CORE_PROXY,
903                                         PWS_CORE_PROXY_PASS);
904                 } else {
905                         proxy_info = (ProxyInfo *)&(ac->proxy_info);
906                         if (proxy_info->use_proxy_auth)
907                                 proxy_info->proxy_pass = passwd_store_get_account(ac->account_id,
908                                         PWS_ACCOUNT_PROXY_PASS);
909                 }
910         }
911         SESSION(pop3_session)->proxy_info = proxy_info;
912
913         GTK_EVENTS_FLUSH();
914         g_free(buf);
915
916         session_set_timeout(SESSION(pop3_session),
917                             prefs_common.io_timeout_secs * 1000);
918         
919         if (session_connect(SESSION(pop3_session), server, port) < 0) {
920                 if(!prefs_common.no_recv_err_panel) {
921                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
922                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL) && focus_window)) {
923                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
924                         }
925                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
926                                          server, port);
927                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
928                 } else {
929                         log_error(LOG_PROTOCOL, _("Can't connect to POP3 server: %s:%d\n"),
930                             server, port);
931                 }
932                 session->inc_state = INC_CONNECT_ERROR;
933                 statusbar_pop_all();
934                 return INC_CONNECT_ERROR;
935         }
936
937         while (session_is_running(SESSION(pop3_session)) &&
938                session->inc_state != INC_CANCEL)
939                 gtk_main_iteration();
940
941         if (session->inc_state == INC_SUCCESS) {
942                 switch (pop3_session->error_val) {
943                 case PS_SUCCESS:
944                         switch (SESSION(pop3_session)->state) {
945                         case SESSION_ERROR:
946                                 if (pop3_session->state == POP3_READY)
947                                         session->inc_state = INC_CONNECT_ERROR;
948                                 else
949                                         session->inc_state = INC_ERROR;
950                                 break;
951                         case SESSION_EOF:
952                                 session->inc_state = INC_EOF;
953                                 break;
954                         case SESSION_TIMEOUT:
955                                 session->inc_state = INC_TIMEOUT;
956                                 break;
957                         default:
958                                 session->inc_state = INC_SUCCESS;
959                                 break;
960                         }
961                         break;
962                 case PS_AUTHFAIL:
963                         session->inc_state = INC_AUTH_FAILED;
964                         break;
965                 case PS_IOERR:
966                         session->inc_state = INC_IO_ERROR;
967                         break;
968                 case PS_SOCKET:
969                         session->inc_state = INC_SOCKET_ERROR;
970                         break;
971                 case PS_LOCKBUSY:
972                         session->inc_state = INC_LOCKED;
973                         break;
974                 default:
975                         session->inc_state = INC_ERROR;
976                         break;
977                 }
978         }
979
980         session_disconnect(SESSION(pop3_session));
981         statusbar_pop_all();
982
983         return session->inc_state;
984 }
985
986 static void inc_progress_dialog_update(IncProgressDialog *inc_dialog,
987                                        IncSession *inc_session)
988 {
989         inc_progress_dialog_set_label(inc_dialog, inc_session);
990         inc_progress_dialog_set_progress(inc_dialog, inc_session);
991 }
992
993 static void inc_progress_dialog_set_label(IncProgressDialog *inc_dialog,
994                                           IncSession *inc_session)
995 {
996         ProgressDialog *dialog = inc_dialog->dialog;
997         Pop3Session *session;
998
999         cm_return_if_fail(inc_session != NULL);
1000
1001         session = POP3_SESSION(inc_session->session);
1002
1003         switch (session->state) {
1004         case POP3_GREETING:
1005                 break;
1006         case POP3_GETAUTH_USER:
1007         case POP3_GETAUTH_PASS:
1008         case POP3_GETAUTH_APOP:
1009                 progress_dialog_set_label(dialog, _("Authenticating..."));
1010                 statusbar_pop_all();
1011                 statusbar_print_all(_("Retrieving messages from %s (%s)..."),
1012                                     SESSION(session)->server,
1013                                     session->ac_prefs->account_name);
1014                 break;
1015         case POP3_GETRANGE_STAT:
1016                 progress_dialog_set_label
1017                         (dialog, _("Getting the number of new messages (STAT)..."));
1018                 break;
1019         case POP3_GETRANGE_LAST:
1020                 progress_dialog_set_label
1021                         (dialog, _("Getting the number of new messages (LAST)..."));
1022                 break;
1023         case POP3_GETRANGE_UIDL:
1024                 progress_dialog_set_label
1025                         (dialog, _("Getting the number of new messages (UIDL)..."));
1026                 break;
1027         case POP3_GETSIZE_LIST:
1028                 progress_dialog_set_label
1029                         (dialog, _("Getting the size of messages (LIST)..."));
1030                 break;
1031         case POP3_RETR:
1032         case POP3_RETR_RECV:
1033         case POP3_DELETE:
1034                 break;
1035         case POP3_LOGOUT:
1036                 progress_dialog_set_label(dialog, _("Quitting"));
1037                 break;
1038         default:
1039                 break;
1040         }
1041 }
1042
1043 static void inc_progress_dialog_set_progress(IncProgressDialog *inc_dialog,
1044                                              IncSession *inc_session)
1045 {
1046         gchar buf[MESSAGEBUFSIZE];
1047         Pop3Session *pop3_session = POP3_SESSION(inc_session->session);
1048         gchar *total_size_str;
1049         gint cur_total;
1050         gint total;
1051
1052         if (!pop3_session->new_msg_exist) return;
1053
1054         cur_total = inc_session->cur_total_bytes;
1055         total = pop3_session->total_bytes;
1056         if (pop3_session->state == POP3_RETR ||
1057             pop3_session->state == POP3_RETR_RECV ||
1058             pop3_session->state == POP3_DELETE) {
1059                 Xstrdup_a(total_size_str, to_human_readable((goffset)total), return);
1060                 g_snprintf(buf, sizeof(buf),
1061                            _("Retrieving message (%d / %d) (%s / %s)"),
1062                            pop3_session->cur_msg, pop3_session->count,
1063                            to_human_readable((goffset)cur_total), total_size_str);
1064                 progress_dialog_set_label(inc_dialog->dialog, buf);
1065         }
1066
1067         progress_dialog_set_fraction
1068                 (inc_dialog->dialog, (total == 0) ? 0: (gfloat)cur_total / (gfloat)total);
1069
1070         statusbar_progress_all(pop3_session->cur_msg, pop3_session->count, 1);
1071
1072         if (pop3_session->cur_total_num > 0) {
1073                 g_snprintf(buf, sizeof(buf),
1074                            ngettext("Retrieving (%d message (%s) received)",
1075                                     "Retrieving (%d messages (%s) received)",
1076                                     pop3_session->cur_total_num),
1077                            pop3_session->cur_total_num,
1078                            to_human_readable
1079                            ((goffset)pop3_session->cur_total_recv_bytes));
1080                 progress_dialog_list_set_status(inc_dialog->dialog,
1081                                                 inc_dialog->cur_row,
1082                                                 buf);
1083         }
1084 }
1085
1086 static void inc_progress_dialog_update_periodic(IncProgressDialog *inc_dialog,
1087                                                 IncSession *inc_session)
1088 {
1089         GDateTime *tv_cur = g_date_time_new_now_local();
1090         GTimeSpan tv_result;
1091
1092         tv_result = g_date_time_difference(tv_cur, inc_dialog->progress_tv);
1093         g_date_time_unref(tv_cur);
1094         if (tv_result < 0) {
1095             tv_result += G_USEC_PER_SEC;
1096         }
1097
1098         if (tv_result > PROGRESS_UPDATE_INTERVAL) {
1099                 inc_progress_dialog_update(inc_dialog, inc_session);
1100                 tv_cur = g_date_time_add(inc_dialog->progress_tv, tv_result);
1101                 g_date_time_unref(inc_dialog->progress_tv);
1102                 inc_dialog->progress_tv = tv_cur;
1103         }
1104 }
1105
1106 static gint inc_recv_data_progressive(Session *session, guint cur_len,
1107                                       guint total_len, gpointer data)
1108 {
1109         IncSession *inc_session = (IncSession *)data;
1110         Pop3Session *pop3_session = POP3_SESSION(session);
1111         IncProgressDialog *inc_dialog;
1112         gint cur_total;
1113
1114         cm_return_val_if_fail(inc_session != NULL, -1);
1115
1116         if (pop3_session->state != POP3_RETR &&
1117             pop3_session->state != POP3_RETR_RECV &&
1118             pop3_session->state != POP3_DELETE &&
1119             pop3_session->state != POP3_LOGOUT) return 0;
1120
1121         if (!pop3_session->new_msg_exist) return 0;
1122
1123         cur_total = pop3_session->cur_total_bytes + cur_len;
1124         if (cur_total > pop3_session->total_bytes)
1125                 cur_total = pop3_session->total_bytes;
1126         inc_session->cur_total_bytes = cur_total;
1127
1128         inc_dialog = (IncProgressDialog *)inc_session->data;
1129         inc_progress_dialog_update_periodic(inc_dialog, inc_session);
1130
1131         return 0;
1132 }
1133
1134 static gint inc_recv_data_finished(Session *session, guint len, gpointer data)
1135 {
1136         IncSession *inc_session = (IncSession *)data;
1137         IncProgressDialog *inc_dialog;
1138
1139         cm_return_val_if_fail(inc_session != NULL, -1);
1140
1141         inc_dialog = (IncProgressDialog *)inc_session->data;
1142
1143         inc_recv_data_progressive(session, 0, 0, inc_session);
1144
1145         if (POP3_SESSION(session)->state == POP3_LOGOUT) {
1146                 inc_progress_dialog_update(inc_dialog, inc_session);
1147         }
1148
1149         return 0;
1150 }
1151
1152 static gint inc_recv_message(Session *session, const gchar *msg, gpointer data)
1153 {
1154         IncSession *inc_session = (IncSession *)data;
1155         IncProgressDialog *inc_dialog;
1156
1157         cm_return_val_if_fail(inc_session != NULL, -1);
1158
1159         inc_dialog = (IncProgressDialog *)inc_session->data;
1160
1161         switch (POP3_SESSION(session)->state) {
1162         case POP3_GETAUTH_USER:
1163         case POP3_GETAUTH_PASS:
1164         case POP3_GETAUTH_APOP:
1165         case POP3_GETRANGE_STAT:
1166         case POP3_GETRANGE_LAST:
1167         case POP3_GETRANGE_UIDL:
1168         case POP3_GETSIZE_LIST:
1169                 inc_progress_dialog_update(inc_dialog, inc_session);
1170                 break;
1171         case POP3_RETR:
1172                 inc_recv_data_progressive(session, 0, 0, inc_session);
1173                 break;
1174         case POP3_LOGOUT:
1175                 inc_progress_dialog_update(inc_dialog, inc_session);
1176                 break;
1177         default:
1178                 break;
1179         }
1180
1181         return 0;
1182 }
1183
1184 static gint inc_drop_message(Pop3Session *session, const gchar *file)
1185 {
1186         FolderItem *inbox;
1187         FolderItem *dropfolder;
1188         IncSession *inc_session = (IncSession *)(SESSION(session)->data);
1189         gint msgnum;
1190
1191         cm_return_val_if_fail(inc_session != NULL, -1);
1192
1193         if (session->ac_prefs->inbox) {
1194                 inbox = folder_find_item_from_identifier
1195                         (session->ac_prefs->inbox);
1196                 if (!inbox)
1197                         inbox = folder_get_default_inbox();
1198         } else
1199                 inbox = folder_get_default_inbox();
1200         if (!inbox) {
1201                 claws_unlink(file);
1202                 return -1;
1203         }
1204
1205         /* CLAWS: claws uses a global .processing folder for the filtering. */
1206         dropfolder = folder_get_default_processing(session->ac_prefs->account_id);
1207
1208         /* add msg file to drop folder */
1209         if ((msgnum = folder_item_add_msg(
1210                         dropfolder, file, NULL, TRUE)) < 0) {
1211                 claws_unlink(file);
1212                 return -1;
1213         }
1214
1215         return 0;
1216 }
1217
1218 static void inc_put_error(IncState istate, Pop3Session *session)
1219 {
1220         gchar *log_msg = NULL;
1221         gchar *err_msg = NULL;
1222         gboolean fatal_error = FALSE;
1223
1224         switch (istate) {
1225         case INC_CONNECT_ERROR:
1226                 fatal_error = TRUE;
1227                 if (prefs_common.no_recv_err_panel)
1228                         break;
1229                 err_msg = g_strdup_printf(_("Connection to %s:%d failed."),
1230                                           SESSION(session)->server, 
1231                                           SESSION(session)->port);
1232                 break;
1233         case INC_ERROR:
1234                 log_msg = _("Error occurred while processing mail.");
1235                 fatal_error = TRUE;
1236                 if (prefs_common.no_recv_err_panel)
1237                         break;
1238                 if (session->error_msg)
1239                         err_msg = g_strdup_printf
1240                                 (_("Error occurred while processing mail:\n%s"),
1241                                  session->error_msg);
1242                 else
1243                         err_msg = g_strdup(log_msg);
1244                 break;
1245         case INC_NO_SPACE:
1246                 log_msg = _("No disk space left.");
1247                 err_msg = g_strdup(log_msg);
1248                 fatal_error = TRUE;
1249                 break;
1250         case INC_IO_ERROR:
1251                 log_msg = _("Can't write file.");
1252                 err_msg = g_strdup(log_msg);
1253                 fatal_error = TRUE;
1254                 break;
1255         case INC_SOCKET_ERROR:
1256                 log_msg = _("Socket error.");
1257                 if (prefs_common.no_recv_err_panel)
1258                         break;
1259                 err_msg = g_strdup_printf(_("Socket error on connection to %s:%d."),
1260                                           SESSION(session)->server, 
1261                                           SESSION(session)->port);
1262                 break;
1263         case INC_EOF:
1264                 log_msg = _("Connection closed by the remote host.");
1265                 if (prefs_common.no_recv_err_panel)
1266                         break;
1267                 err_msg = g_strdup_printf(_("Connection to %s:%d closed by the remote host."), 
1268                                           SESSION(session)->server, 
1269                                           SESSION(session)->port);
1270                 break;
1271         case INC_LOCKED:
1272                 log_msg = _("Mailbox is locked.");
1273                 if (prefs_common.no_recv_err_panel)
1274                         break;
1275                 if (session->error_msg)
1276                         err_msg = g_strdup_printf(_("Mailbox is locked:\n%s"),
1277                                                   session->error_msg);
1278                 else
1279                         err_msg = g_strdup(log_msg);
1280                 break;
1281         case INC_AUTH_FAILED:
1282                 log_msg = _("Authentication failed.");
1283                 fatal_error = TRUE;
1284                 if (prefs_common.no_recv_err_panel)
1285                         break;
1286                 if (session->error_msg)
1287                         err_msg = g_strdup_printf
1288                                 (_("Authentication failed:\n%s"), session->error_msg);
1289                 else
1290                         err_msg = g_strdup(log_msg);
1291                 break;
1292         case INC_TIMEOUT:
1293                 log_msg = _("Session timed out. You may be able to "
1294                             "recover by increasing the timeout value in "
1295                             "Preferences/Other/Miscellaneous.");
1296                 if (prefs_common.no_recv_err_panel)
1297                         break;
1298                 err_msg = g_strdup_printf(_("Connection to %s:%d timed out."), 
1299                                           SESSION(session)->server, 
1300                                           SESSION(session)->port);
1301                 break;
1302         default:
1303                 break;
1304         }
1305
1306         if (log_msg) {
1307                 if (fatal_error)
1308                         log_error(LOG_PROTOCOL, "%s\n", log_msg);
1309                 else
1310                         log_warning(LOG_PROTOCOL, "%s\n", log_msg);
1311         }
1312         if (prefs_common.no_recv_err_panel && fatal_error)
1313                 mainwindow_show_error();
1314
1315         if (err_msg) {
1316                 alertpanel_error_log("%s", err_msg);
1317                 g_free(err_msg);
1318         }
1319 }
1320
1321 static void inc_cancel(IncProgressDialog *dialog)
1322 {
1323         IncSession *session;
1324
1325         cm_return_if_fail(dialog != NULL);
1326
1327         if (dialog->queue_list == NULL) {
1328                 inc_progress_dialog_destroy(dialog);
1329                 return;
1330         }
1331
1332         session = dialog->queue_list->data;
1333
1334         session->inc_state = INC_CANCEL;
1335
1336         log_message(LOG_PROTOCOL, _("Incorporation cancelled\n"));
1337 }
1338
1339 gboolean inc_is_active(void)
1340 {
1341         return (inc_dialog_list != NULL);
1342 }
1343
1344 void inc_cancel_all(void)
1345 {
1346         GList *cur;
1347
1348         for (cur = inc_dialog_list; cur != NULL; cur = cur->next)
1349                 inc_cancel((IncProgressDialog *)cur->data);
1350 }
1351
1352 static void inc_showlog_cb(GtkWidget *widget, gpointer data)
1353 {
1354         MainWindow *mainwin = mainwindow_get_mainwindow();
1355
1356         log_window_show(mainwin->logwin);
1357 }
1358
1359 static void inc_cancel_cb(GtkWidget *widget, gpointer data)
1360 {
1361         inc_cancel((IncProgressDialog *)data);
1362 }
1363
1364 static gint inc_dialog_delete_cb(GtkWidget *widget, GdkEventAny *event,
1365                                  gpointer data)
1366 {
1367         IncProgressDialog *dialog = (IncProgressDialog *)data;
1368
1369         if (dialog->queue_list == NULL)
1370                 inc_progress_dialog_destroy(dialog);
1371
1372         return TRUE;
1373 }
1374
1375 static gint inc_spool_account(PrefsAccount *account)
1376 {
1377         FolderItem *inbox;
1378         gchar *mbox;
1379         gint result;
1380
1381         if (account->local_inbox) {
1382                 inbox = folder_find_item_from_identifier(account->local_inbox);
1383                 if (!inbox)
1384                         inbox = folder_get_default_inbox();
1385         } else
1386                 inbox = folder_get_default_inbox();
1387
1388         if (account->local_mbox) {
1389                 if (is_file_exist(account->local_mbox))
1390                         mbox = g_strdup(account->local_mbox);
1391                 else if (is_dir_exist(account->local_mbox)) 
1392                         mbox = g_strconcat(account->local_mbox, G_DIR_SEPARATOR_S,
1393                                            g_get_user_name(), NULL);
1394                 else {
1395                         debug_print("%s: local mailbox not found.\n", 
1396                                     account->local_mbox);
1397                         return -1;
1398                 }
1399         } else {
1400                 debug_print("local mailbox not set in account info.\n");
1401                 return -1;
1402         }       
1403
1404         result = get_spool(inbox, mbox, account);
1405         g_free(mbox);
1406         
1407         statusbar_pop_all();
1408         
1409         return result;
1410 }
1411
1412 static gint get_spool(FolderItem *dest, const gchar *mbox, PrefsAccount *account)
1413 {
1414         gint msgs, size;
1415         gint lockfd;
1416         gchar tmp_mbox[MAXPATHLEN + 1];
1417
1418         cm_return_val_if_fail(dest != NULL, -1);
1419         cm_return_val_if_fail(mbox != NULL, -1);
1420         cm_return_val_if_fail(account != NULL, -1);
1421
1422         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1423                 debug_print("%s: no messages in local mailbox.\n", mbox);
1424                 return 0;
1425         } else if (size < 0)
1426                 return -1;
1427
1428         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1429                 return -1;
1430
1431         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox.%p",
1432                    get_tmp_dir(), G_DIR_SEPARATOR, mbox);
1433
1434         if (copy_mbox(lockfd, tmp_mbox) < 0) {
1435                 unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1436                 return -1;
1437         }
1438
1439         debug_print("Getting new messages from %s into %s...\n",
1440                     mbox, dest->path);
1441
1442         msgs = proc_mbox(dest, tmp_mbox, account->filter_on_recv, account);
1443
1444         claws_unlink(tmp_mbox);
1445         if (msgs >= 0) empty_mbox(mbox);
1446         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1447
1448         return msgs;
1449 }
1450
1451 void inc_lock_real(void)
1452 {
1453         inc_lock_count++;
1454 }
1455
1456 void inc_unlock_real(void)
1457 {
1458         if (inc_lock_count > 0)
1459                 inc_lock_count--;
1460 }
1461
1462 static guint autocheck_timer = 0;
1463 static gpointer autocheck_data = NULL;
1464
1465 static void inc_notify_cmd(gint new_msgs, gboolean notify)
1466 {
1467         gchar *buf, *numpos, *ret_str;
1468         gssize by_read = 0, by_written = 0;
1469
1470         if (!(new_msgs && notify && prefs_common.newmail_notify_cmd &&
1471             *prefs_common.newmail_notify_cmd))
1472                      return;
1473
1474         buf = g_strdup(prefs_common.newmail_notify_cmd);
1475         if ((numpos = strstr(buf, "%d")) != NULL) {
1476                 gchar *buf2;
1477
1478                 *numpos = '\0';
1479                 buf2 = g_strdup_printf("%s%d%s", buf, new_msgs, numpos + 2);
1480                 g_free(buf);
1481                 buf = buf2;
1482         }
1483
1484         ret_str = g_locale_from_utf8(buf, strlen(buf), &by_read, &by_written,
1485                                      NULL);
1486         if (ret_str && by_written) {
1487                 g_free(buf);
1488                 buf = ret_str;
1489         }
1490         debug_print("executing new mail notification command: %s\n", buf);
1491         execute_command_line(buf, TRUE, NULL);
1492
1493         g_free(buf);
1494 }
1495
1496 void inc_autocheck_timer_init(MainWindow *mainwin)
1497 {
1498         autocheck_data = mainwin;
1499         inc_autocheck_timer_set();
1500 }
1501
1502 static void inc_autocheck_timer_set_interval(guint _interval)
1503 {
1504         guint interval = _interval;
1505
1506         /* Convert the interval to seconds if needed. */
1507         if (_interval % 1000 == 0)
1508                 interval /= 1000;
1509
1510         inc_autocheck_timer_remove();
1511         /* last test is to avoid re-enabling auto_check after modifying 
1512            the common preferences */
1513         if (prefs_common.autochk_newmail && autocheck_data
1514             && prefs_common.work_offline == FALSE) {
1515                         autocheck_timer =
1516                                 g_timeout_add_seconds(interval, inc_autocheck_func, autocheck_data);
1517                 debug_print("added global inc timer %d at %u seconds\n",
1518                                 autocheck_timer, interval);
1519         }
1520 }
1521
1522 void inc_autocheck_timer_set(void)
1523 {
1524         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 1000);
1525 }
1526
1527 void inc_autocheck_timer_remove(void)
1528 {
1529         if (autocheck_timer) {
1530                 debug_print("removed global inc timer %d\n", autocheck_timer);
1531                 g_source_remove(autocheck_timer);
1532                 autocheck_timer = 0;
1533         }
1534 }
1535
1536 static gint inc_autocheck_func(gpointer data)
1537 {
1538         MainWindow *mainwin = (MainWindow *)data;
1539
1540         if (inc_lock_count) {
1541                 debug_print("global inc: autocheck is locked.\n");
1542                 inc_autocheck_timer_set_interval(1000);
1543                 return FALSE;
1544         }
1545
1546         inc_all_account_mail(mainwin, TRUE, FALSE, prefs_common.newmail_notify_auto);
1547         inc_autocheck_timer_set();
1548
1549         return FALSE;
1550 }
1551
1552 static gboolean inc_account_autocheck_func(gpointer data)
1553 {
1554         PrefsAccount *account = (PrefsAccount *)data;
1555         GList *list = NULL;
1556
1557         cm_return_val_if_fail(account != NULL, FALSE);
1558
1559         debug_print("account %d: inc_account_autocheck_func\n",
1560                         account->account_id);
1561
1562         list = g_list_append(list, account);
1563         inc_account_list_mail(mainwindow_get_mainwindow(),
1564                         list, TRUE, prefs_common.newmail_notify_auto);
1565         g_list_free(list);
1566
1567         inc_account_autocheck_timer_set_interval(account);
1568
1569         return FALSE;
1570 }
1571
1572 void inc_account_autocheck_timer_remove(PrefsAccount *account)
1573 {
1574         cm_return_if_fail(account != NULL);
1575
1576         if (account->autocheck_timer != 0) {
1577                 g_source_remove(account->autocheck_timer);
1578                 debug_print("INC: account %d: removed inc timer %d\n", account->account_id,
1579                                 account->autocheck_timer);
1580                 account->autocheck_timer = 0;
1581         }
1582 }
1583
1584 void inc_account_autocheck_timer_set_interval(PrefsAccount *account)
1585 {
1586         cm_return_if_fail(account != NULL);
1587
1588         inc_account_autocheck_timer_remove(account);
1589
1590         if (account->autochk_use_default
1591                         || !account->autochk_use_custom
1592                         || account->autochk_itv == 0)
1593                 return;
1594
1595         account->autocheck_timer = g_timeout_add_seconds(
1596                         account->autochk_itv, inc_account_autocheck_func, account);
1597         debug_print("INC: account %d: added inc timer %d at %u seconds\n",
1598                         account->account_id, account->autocheck_timer, account->autochk_itv);
1599 }
1600
1601 gboolean inc_offline_should_override(gboolean force_ask, const gchar *msg)
1602 {
1603         gint length = 10; /* seconds */
1604         gint answer = G_ALERTDEFAULT;
1605
1606 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1607         /* If no network connection is available, override is not possible */
1608         if(!networkmanager_is_online(NULL))
1609                 return FALSE;
1610 #endif
1611
1612         if (prefs_common.autochk_newmail)
1613                 length = prefs_common.autochk_itv; /* seconds */
1614
1615         if (force_ask) {
1616                 inc_offline_overridden_no = (time_t)0;
1617         }
1618
1619         if (prefs_common.work_offline) {
1620                 gchar *tmp = NULL;
1621                 
1622                 if (time(NULL) - inc_offline_overridden_yes < length * 60) /* seconds */
1623                          return TRUE;
1624                 else if (time(NULL) - inc_offline_overridden_no < length * 60) /* seconds */
1625                          return FALSE;
1626
1627                 if (!force_ask) {
1628                         gchar *unit = _("seconds");
1629
1630                         /* show the offline override time (length) using the must appropriate unit:
1631                            the biggest unit possible (hours, minutes, seconds), provided that there
1632                            is not inferior unit involved: 1 hour, 150 minutes, 25 minutes, 90 minutes,
1633                            30 seconds, 90 seconds. */
1634                         if ((length / 3600) > 0) { /* hours? */
1635                                 if (((length % 3600) % 60) == 0) { /* no seconds left? */
1636                                         if ((length % 3600) > 0) { /* minutes left? */
1637                                                 length = length / 60;
1638                                                 unit = ngettext("minute", "minutes", length);
1639                                         } else {
1640                                                 length = length / 3600;
1641                                                 unit = ngettext("hour", "hours", length);
1642                                         }
1643                                 } /* else: seconds */
1644                         } else {
1645                                 if ((length / 60) > 0) { /* minutes left? */
1646                                         if ((length % 60) == 0) {
1647                                                 length = length / 60;
1648                                                 unit = ngettext("minute", "minutes", length);
1649                                         }
1650                                 } /* else: seconds */
1651                         }
1652                         tmp = g_strdup_printf(
1653                                 _("%s%sYou're working offline. Override for %d %s?"),
1654                                 msg?msg:"", 
1655                                 msg?"\n\n":"",
1656                                 length, unit);
1657                 } else
1658                         tmp = g_strdup_printf(
1659                                 _("%s%sYou're working offline. Override?"),
1660                                 msg?msg:"", 
1661                                 msg?"\n\n":"");
1662
1663                 answer = alertpanel(_("Offline warning"), 
1664                                tmp,
1665                                GTK_STOCK_NO, GTK_STOCK_YES,
1666                                 !force_ask? _("On_ly once"):NULL, ALERTFOCUS_SECOND);
1667                 g_free(tmp);
1668                 if (answer == G_ALERTALTERNATE) {
1669                         inc_offline_overridden_yes = time(NULL);
1670                         return TRUE;
1671                 } else if (answer == G_ALERTDEFAULT) {
1672                         if (!force_ask)
1673                                 inc_offline_overridden_no  = time(NULL);
1674                         return FALSE;
1675                 } else {
1676                         inc_reset_offline_override_timers();
1677                         return TRUE;
1678                 }
1679         }
1680         return TRUE;
1681 }
1682
1683 void inc_reset_offline_override_timers()
1684 {
1685         debug_print("resetting offline override timers\n");
1686         inc_offline_overridden_yes = (time_t)0;
1687         inc_offline_overridden_no  = (time_t)0;
1688 }