missed this in last commit
[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         g_date_time_unref(inc_dialog->progress_tv);
557         g_date_time_unref(inc_dialog->folder_tv);
558
559         g_free(inc_dialog);
560 }
561
562 static IncSession *inc_session_new(PrefsAccount *account)
563 {
564         IncSession *session;
565
566         cm_return_val_if_fail(account != NULL, NULL);
567
568         if (account->protocol != A_POP3)
569                 return NULL;
570         if (!account->recv_server || !account->userid)
571                 return NULL;
572
573         session = g_new0(IncSession, 1);
574
575         session->session = pop3_session_new(account);
576         session->session->data = session;
577         POP3_SESSION(session->session)->drop_message = inc_drop_message;
578         session_set_recv_message_notify(session->session,
579                                         inc_recv_message, session);
580         session_set_recv_data_progressive_notify(session->session,
581                                                  inc_recv_data_progressive,
582                                                  session);
583         session_set_recv_data_notify(session->session,
584                                      inc_recv_data_finished, session);
585
586         return session;
587 }
588
589 static void inc_session_destroy(IncSession *session)
590 {
591         cm_return_if_fail(session != NULL);
592
593         session_destroy(session->session);
594         g_free(session);
595 }
596
597 static gint pop3_get_port(Pop3Session *pop3_session)
598 {
599 #ifdef USE_GNUTLS
600         return pop3_session->ac_prefs->set_popport ?
601                 pop3_session->ac_prefs->popport :
602                 pop3_session->ac_prefs->ssl_pop == SSL_TUNNEL ? 995 : 110;
603 #else
604         return pop3_session->ac_prefs->set_popport ?
605                 pop3_session->ac_prefs->popport : 110;
606 #endif
607 }
608
609 static gint inc_start(IncProgressDialog *inc_dialog)
610 {
611         IncSession *session;
612         GList *qlist;
613         Pop3Session *pop3_session;
614         IncState inc_state;
615         gint error_num = 0;
616         gint new_msgs = 0;
617         gchar *msg;
618         gchar *fin_msg;
619         FolderItem *processing, *inbox;
620         GSList *msglist, *msglist_element;
621         gboolean cancelled = FALSE;
622
623         qlist = inc_dialog->queue_list;
624         while (qlist != NULL) {
625                 GList *next = qlist->next;
626
627                 session = qlist->data;
628                 pop3_session = POP3_SESSION(session->session); 
629                 pop3_session->user = g_strdup(pop3_session->ac_prefs->userid);
630
631                 if (inc_dialog->show_dialog)
632                         manage_window_focus_in
633                                 (inc_dialog->dialog->window,
634                                  NULL, NULL);
635
636                 if (password_get(pop3_session->user,
637                                         pop3_session->ac_prefs->recv_server,
638                                         "pop3", pop3_get_port(pop3_session),
639                                         &(pop3_session->pass))) {
640                         /* NOP */;
641                 } else if ((pop3_session->pass = passwd_store_get_account(
642                                                 pop3_session->ac_prefs->account_id, PWS_ACCOUNT_RECV)) == NULL) {
643                         gchar *pass;
644
645                         pass = input_dialog_query_password_keep
646                                 (pop3_session->ac_prefs->recv_server,
647                                  pop3_session->user,
648                                  &(pop3_session->ac_prefs->session_passwd));
649
650                         if (pass) {
651                                 pop3_session->pass = pass;
652                         }
653                 }
654
655                 if (inc_dialog->show_dialog)
656                         manage_window_focus_out
657                                 (inc_dialog->dialog->window,
658                                  NULL, NULL);
659
660                 qlist = next;
661         }
662
663 #define SET_PIXMAP_AND_TEXT(pix, str)                                      \
664 {                                                                          \
665         progress_dialog_list_set(inc_dialog->dialog,                       \
666                                  inc_dialog->cur_row,                      \
667                                  pix,                                      \
668                                  NULL,                                     \
669                                  str);                                     \
670 }
671
672         for (; inc_dialog->queue_list != NULL && !cancelled; inc_dialog->cur_row++) {
673                 session = inc_dialog->queue_list->data;
674                 pop3_session = POP3_SESSION(session->session);
675                 GSList *filtered, *unfiltered;
676
677                 if (pop3_session->pass == NULL) {
678                         SET_PIXMAP_AND_TEXT(okpix, _("Cancelled"));
679                         inc_session_destroy(session);
680                         inc_dialog->queue_list =
681                                 g_list_remove(inc_dialog->queue_list, session);
682                         continue;
683                 }
684
685                 inc_progress_dialog_clear(inc_dialog);
686                 progress_dialog_scroll_to_row(inc_dialog->dialog,
687                                               inc_dialog->cur_row);
688
689                 SET_PIXMAP_AND_TEXT(currentpix, _("Retrieving"));
690
691                 /* begin POP3 session */
692                 inc_state = inc_pop3_session_do(session);
693
694                 switch (inc_state) {
695                 case INC_SUCCESS:
696                         if (pop3_session->cur_total_num > 0)
697                                 msg = g_strdup_printf(
698                                         ngettext("Done (%d message (%s) received)",
699                                                  "Done (%d messages (%s) received)",
700                                          pop3_session->cur_total_num),
701                                          pop3_session->cur_total_num,
702                                          to_human_readable((goffset)pop3_session->cur_total_recv_bytes));
703                         else
704                                 msg = g_strdup_printf(_("Done (no new messages)"));
705                         SET_PIXMAP_AND_TEXT(okpix, msg);
706                         g_free(msg);
707                         break;
708                 case INC_CONNECT_ERROR:
709                         SET_PIXMAP_AND_TEXT(errorpix, _("Connection failed"));
710                         break;
711                 case INC_AUTH_FAILED:
712                         SET_PIXMAP_AND_TEXT(errorpix, _("Auth failed"));
713                         if (pop3_session->ac_prefs->session_passwd) {
714                                 g_free(pop3_session->ac_prefs->session_passwd);
715                                 pop3_session->ac_prefs->session_passwd = NULL;
716                         }
717                         break;
718                 case INC_LOCKED:
719                         SET_PIXMAP_AND_TEXT(errorpix, _("Locked"));
720                         break;
721                 case INC_ERROR:
722                 case INC_NO_SPACE:
723                 case INC_IO_ERROR:
724                 case INC_SOCKET_ERROR:
725                 case INC_EOF:
726                         SET_PIXMAP_AND_TEXT(errorpix, _("Error"));
727                         break;
728                 case INC_TIMEOUT:
729                         SET_PIXMAP_AND_TEXT(errorpix, _("Timeout"));
730                         break;
731                 case INC_CANCEL:
732                         SET_PIXMAP_AND_TEXT(okpix, _("Cancelled"));
733                         if (!inc_dialog->show_dialog)
734                                 cancelled = TRUE;
735                         break;
736                 default:
737                         break;
738                 }
739                 
740                 if (pop3_session->error_val == PS_AUTHFAIL) {
741                         if(!prefs_common.no_recv_err_panel) {
742                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
743                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL) && focus_window))
744                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
745                         }
746                 }
747
748                 /* CLAWS: perform filtering actions on dropped message */
749                 /* CLAWS: get default inbox (perhaps per account) */
750                 if (pop3_session->ac_prefs->inbox) {
751                         /* CLAWS: get destination folder / mailbox */
752                         inbox = folder_find_item_from_identifier(pop3_session->ac_prefs->inbox);
753                         if (!inbox)
754                                 inbox = folder_get_default_inbox();
755                 } else
756                         inbox = folder_get_default_inbox();
757
758                 /* get list of messages in processing */
759                 processing = folder_get_default_processing(pop3_session->ac_prefs->account_id);
760                 folder_item_scan(processing);
761                 msglist = folder_item_get_msg_list(processing);
762
763                 /* process messages */
764                 folder_item_update_freeze();
765                 
766                 procmsg_msglist_filter(msglist, pop3_session->ac_prefs, 
767                                 &filtered, &unfiltered, 
768                                 pop3_session->ac_prefs->filter_on_recv);
769
770                 filtering_move_and_copy_msgs(msglist);
771                 if (unfiltered != NULL)         
772                         folder_item_move_msgs(inbox, unfiltered);
773
774                 for(msglist_element = msglist; msglist_element != NULL; 
775                     msglist_element = msglist_element->next) {
776                         procmsg_msginfo_free((MsgInfo**)&(msglist_element->data));
777                 }
778                 folder_item_update_thaw();
779                 
780                 g_slist_free(msglist);
781                 g_slist_free(filtered);
782                 g_slist_free(unfiltered);
783
784                 statusbar_pop_all();
785
786                 new_msgs += pop3_session->cur_total_num;
787
788                 pop3_write_uidl_list(pop3_session);
789
790                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
791                         error_num++;
792                         if (inc_dialog->show_dialog)
793                                 manage_window_focus_in
794                                         (inc_dialog->dialog->window,
795                                          NULL, NULL);
796                         inc_put_error(inc_state, pop3_session);
797                         if (inc_dialog->show_dialog)
798                                 manage_window_focus_out
799                                         (inc_dialog->dialog->window,
800                                          NULL, NULL);
801                         if (inc_state == INC_NO_SPACE ||
802                             inc_state == INC_IO_ERROR)
803                                 break;
804                 }
805                 folder_item_free_cache(processing, TRUE);
806
807                 inc_session_destroy(session);
808                 inc_dialog->queue_list =
809                         g_list_remove(inc_dialog->queue_list, session);
810         }
811
812 #undef SET_PIXMAP_AND_TEXT
813
814         if (new_msgs > 0)
815                 fin_msg = g_strdup_printf(ngettext("Finished (%d new message)",
816                                                    "Finished (%d new messages)",
817                                                    new_msgs), new_msgs);
818         else
819                 fin_msg = g_strdup_printf(_("Finished (no new messages)"));
820
821         progress_dialog_set_label(inc_dialog->dialog, fin_msg);
822
823         while (inc_dialog->queue_list != NULL) {
824                 session = inc_dialog->queue_list->data;
825                 inc_session_destroy(session);
826                 inc_dialog->queue_list =
827                         g_list_remove(inc_dialog->queue_list, session);
828         }
829
830         if (prefs_common.close_recv_dialog || !inc_dialog->show_dialog)
831                 inc_progress_dialog_destroy(inc_dialog);
832         else {
833                 gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window),
834                                      fin_msg);
835                 gtk_button_set_label(GTK_BUTTON(inc_dialog->dialog->cancel_btn),
836                                      GTK_STOCK_CLOSE);
837         }
838
839         g_free(fin_msg);
840
841         return new_msgs;
842 }
843
844 static IncState inc_pop3_session_do(IncSession *session)
845 {
846         Pop3Session *pop3_session = POP3_SESSION(session->session);
847         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
848         PrefsAccount *ac = pop3_session->ac_prefs;
849         gchar *server;
850         gchar *account_name;
851         gushort port;
852         gchar *buf;
853         ProxyInfo *proxy_info = NULL;
854
855         debug_print("getting new messages of account %s...\n",
856                     ac->account_name);
857                     
858         ac->last_pop_login_time = time(NULL);
859
860         buf = g_strdup_printf(_("%s: Retrieving new messages"),
861                               ac->recv_server);
862         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
863         g_free(buf);
864
865         server = ac->recv_server;
866         account_name = ac->account_name;
867         port = pop3_get_port(pop3_session);
868
869 #ifdef USE_GNUTLS
870         SESSION(pop3_session)->ssl_type = ac->ssl_pop;
871         if (ac->ssl_pop != SSL_NONE)
872                 SESSION(pop3_session)->nonblocking =
873                         ac->use_nonblocking_ssl;
874 #else
875         if (ac->ssl_pop != SSL_NONE) {
876                 if (alertpanel_full(_("Insecure connection"),
877                         _("This connection is configured to be secured "
878                           "using SSL/TLS, but SSL/TLS is not available "
879                           "in this build of Claws Mail. \n\n"
880                           "Do you want to continue connecting to this "
881                           "server? The communication would not be "
882                           "secure."),
883                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), NULL,
884                                 ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING) != G_ALERTALTERNATE)
885                         return INC_CANCEL;
886         }
887 #endif
888
889         buf = g_strdup_printf(_("Account '%s': Connecting to POP3 server: %s:%d..."),
890                                 account_name, server, port);
891         statusbar_print_all("%s", buf);
892         log_message(LOG_PROTOCOL, "%s\n", buf);
893
894         progress_dialog_set_label(inc_dialog->dialog, buf);
895
896         if (ac->use_proxy) {
897                 if (ac->use_default_proxy) {
898                         proxy_info = (ProxyInfo *)&(prefs_common.proxy_info);
899                         if (proxy_info->use_proxy_auth)
900                                 proxy_info->proxy_pass = passwd_store_get(PWS_CORE, PWS_CORE_PROXY,
901                                         PWS_CORE_PROXY_PASS);
902                 } else {
903                         proxy_info = (ProxyInfo *)&(ac->proxy_info);
904                         if (proxy_info->use_proxy_auth)
905                                 proxy_info->proxy_pass = passwd_store_get_account(ac->account_id,
906                                         PWS_ACCOUNT_PROXY_PASS);
907                 }
908         }
909         SESSION(pop3_session)->proxy_info = proxy_info;
910
911         GTK_EVENTS_FLUSH();
912         g_free(buf);
913
914         session_set_timeout(SESSION(pop3_session),
915                             prefs_common.io_timeout_secs * 1000);
916         
917         if (session_connect(SESSION(pop3_session), server, port) < 0) {
918                 if(!prefs_common.no_recv_err_panel) {
919                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
920                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL) && focus_window)) {
921                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
922                         }
923                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
924                                          server, port);
925                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
926                 } else {
927                         log_error(LOG_PROTOCOL, _("Can't connect to POP3 server: %s:%d\n"),
928                             server, port);
929                 }
930                 session->inc_state = INC_CONNECT_ERROR;
931                 statusbar_pop_all();
932                 return INC_CONNECT_ERROR;
933         }
934
935         while (session_is_running(SESSION(pop3_session)) &&
936                session->inc_state != INC_CANCEL)
937                 gtk_main_iteration();
938
939         if (session->inc_state == INC_SUCCESS) {
940                 switch (pop3_session->error_val) {
941                 case PS_SUCCESS:
942                         switch (SESSION(pop3_session)->state) {
943                         case SESSION_ERROR:
944                                 if (pop3_session->state == POP3_READY)
945                                         session->inc_state = INC_CONNECT_ERROR;
946                                 else
947                                         session->inc_state = INC_ERROR;
948                                 break;
949                         case SESSION_EOF:
950                                 session->inc_state = INC_EOF;
951                                 break;
952                         case SESSION_TIMEOUT:
953                                 session->inc_state = INC_TIMEOUT;
954                                 break;
955                         default:
956                                 session->inc_state = INC_SUCCESS;
957                                 break;
958                         }
959                         break;
960                 case PS_AUTHFAIL:
961                         session->inc_state = INC_AUTH_FAILED;
962                         break;
963                 case PS_IOERR:
964                         session->inc_state = INC_IO_ERROR;
965                         break;
966                 case PS_SOCKET:
967                         session->inc_state = INC_SOCKET_ERROR;
968                         break;
969                 case PS_LOCKBUSY:
970                         session->inc_state = INC_LOCKED;
971                         break;
972                 default:
973                         session->inc_state = INC_ERROR;
974                         break;
975                 }
976         }
977
978         session_disconnect(SESSION(pop3_session));
979         statusbar_pop_all();
980
981         return session->inc_state;
982 }
983
984 static void inc_progress_dialog_update(IncProgressDialog *inc_dialog,
985                                        IncSession *inc_session)
986 {
987         inc_progress_dialog_set_label(inc_dialog, inc_session);
988         inc_progress_dialog_set_progress(inc_dialog, inc_session);
989 }
990
991 static void inc_progress_dialog_set_label(IncProgressDialog *inc_dialog,
992                                           IncSession *inc_session)
993 {
994         ProgressDialog *dialog = inc_dialog->dialog;
995         Pop3Session *session;
996
997         cm_return_if_fail(inc_session != NULL);
998
999         session = POP3_SESSION(inc_session->session);
1000
1001         switch (session->state) {
1002         case POP3_GREETING:
1003                 break;
1004         case POP3_GETAUTH_USER:
1005         case POP3_GETAUTH_PASS:
1006         case POP3_GETAUTH_APOP:
1007                 progress_dialog_set_label(dialog, _("Authenticating..."));
1008                 statusbar_pop_all();
1009                 statusbar_print_all(_("Retrieving messages from %s (%s)..."),
1010                                     SESSION(session)->server,
1011                                     session->ac_prefs->account_name);
1012                 break;
1013         case POP3_GETRANGE_STAT:
1014                 progress_dialog_set_label
1015                         (dialog, _("Getting the number of new messages (STAT)..."));
1016                 break;
1017         case POP3_GETRANGE_LAST:
1018                 progress_dialog_set_label
1019                         (dialog, _("Getting the number of new messages (LAST)..."));
1020                 break;
1021         case POP3_GETRANGE_UIDL:
1022                 progress_dialog_set_label
1023                         (dialog, _("Getting the number of new messages (UIDL)..."));
1024                 break;
1025         case POP3_GETSIZE_LIST:
1026                 progress_dialog_set_label
1027                         (dialog, _("Getting the size of messages (LIST)..."));
1028                 break;
1029         case POP3_RETR:
1030         case POP3_RETR_RECV:
1031         case POP3_DELETE:
1032                 break;
1033         case POP3_LOGOUT:
1034                 progress_dialog_set_label(dialog, _("Quitting"));
1035                 break;
1036         default:
1037                 break;
1038         }
1039 }
1040
1041 static void inc_progress_dialog_set_progress(IncProgressDialog *inc_dialog,
1042                                              IncSession *inc_session)
1043 {
1044         gchar buf[MESSAGEBUFSIZE];
1045         Pop3Session *pop3_session = POP3_SESSION(inc_session->session);
1046         gchar *total_size_str;
1047         gint cur_total;
1048         gint total;
1049
1050         if (!pop3_session->new_msg_exist) return;
1051
1052         cur_total = inc_session->cur_total_bytes;
1053         total = pop3_session->total_bytes;
1054         if (pop3_session->state == POP3_RETR ||
1055             pop3_session->state == POP3_RETR_RECV ||
1056             pop3_session->state == POP3_DELETE) {
1057                 Xstrdup_a(total_size_str, to_human_readable((goffset)total), return);
1058                 g_snprintf(buf, sizeof(buf),
1059                            _("Retrieving message (%d / %d) (%s / %s)"),
1060                            pop3_session->cur_msg, pop3_session->count,
1061                            to_human_readable((goffset)cur_total), total_size_str);
1062                 progress_dialog_set_label(inc_dialog->dialog, buf);
1063         }
1064
1065         progress_dialog_set_fraction
1066                 (inc_dialog->dialog, (total == 0) ? 0: (gfloat)cur_total / (gfloat)total);
1067
1068         statusbar_progress_all(pop3_session->cur_msg, pop3_session->count, 1);
1069
1070         if (pop3_session->cur_total_num > 0) {
1071                 g_snprintf(buf, sizeof(buf),
1072                            ngettext("Retrieving (%d message (%s) received)",
1073                                     "Retrieving (%d messages (%s) received)",
1074                                     pop3_session->cur_total_num),
1075                            pop3_session->cur_total_num,
1076                            to_human_readable
1077                            ((goffset)pop3_session->cur_total_recv_bytes));
1078                 progress_dialog_list_set_status(inc_dialog->dialog,
1079                                                 inc_dialog->cur_row,
1080                                                 buf);
1081         }
1082 }
1083
1084 static void inc_progress_dialog_update_periodic(IncProgressDialog *inc_dialog,
1085                                                 IncSession *inc_session)
1086 {
1087         GDateTime *tv_cur = g_date_time_new_now_local();
1088         GTimeSpan tv_result;
1089
1090         tv_result = g_date_time_difference(tv_cur, inc_dialog->progress_tv);
1091         g_date_time_unref(tv_cur);
1092         if (tv_result < 0) {
1093             tv_result += G_USEC_PER_SEC;
1094         }
1095
1096         if (tv_result > PROGRESS_UPDATE_INTERVAL) {
1097                 inc_progress_dialog_update(inc_dialog, inc_session);
1098                 tv_cur = g_date_time_add(inc_dialog->progress_tv, tv_result);
1099                 g_date_time_unref(inc_dialog->progress_tv);
1100                 inc_dialog->progress_tv = tv_cur;
1101         }
1102 }
1103
1104 static gint inc_recv_data_progressive(Session *session, guint cur_len,
1105                                       guint total_len, gpointer data)
1106 {
1107         IncSession *inc_session = (IncSession *)data;
1108         Pop3Session *pop3_session = POP3_SESSION(session);
1109         IncProgressDialog *inc_dialog;
1110         gint cur_total;
1111
1112         cm_return_val_if_fail(inc_session != NULL, -1);
1113
1114         if (pop3_session->state != POP3_RETR &&
1115             pop3_session->state != POP3_RETR_RECV &&
1116             pop3_session->state != POP3_DELETE &&
1117             pop3_session->state != POP3_LOGOUT) return 0;
1118
1119         if (!pop3_session->new_msg_exist) return 0;
1120
1121         cur_total = pop3_session->cur_total_bytes + cur_len;
1122         if (cur_total > pop3_session->total_bytes)
1123                 cur_total = pop3_session->total_bytes;
1124         inc_session->cur_total_bytes = cur_total;
1125
1126         inc_dialog = (IncProgressDialog *)inc_session->data;
1127         inc_progress_dialog_update_periodic(inc_dialog, inc_session);
1128
1129         return 0;
1130 }
1131
1132 static gint inc_recv_data_finished(Session *session, guint len, gpointer data)
1133 {
1134         IncSession *inc_session = (IncSession *)data;
1135         IncProgressDialog *inc_dialog;
1136
1137         cm_return_val_if_fail(inc_session != NULL, -1);
1138
1139         inc_dialog = (IncProgressDialog *)inc_session->data;
1140
1141         inc_recv_data_progressive(session, 0, 0, inc_session);
1142
1143         if (POP3_SESSION(session)->state == POP3_LOGOUT) {
1144                 inc_progress_dialog_update(inc_dialog, inc_session);
1145         }
1146
1147         return 0;
1148 }
1149
1150 static gint inc_recv_message(Session *session, const gchar *msg, gpointer data)
1151 {
1152         IncSession *inc_session = (IncSession *)data;
1153         IncProgressDialog *inc_dialog;
1154
1155         cm_return_val_if_fail(inc_session != NULL, -1);
1156
1157         inc_dialog = (IncProgressDialog *)inc_session->data;
1158
1159         switch (POP3_SESSION(session)->state) {
1160         case POP3_GETAUTH_USER:
1161         case POP3_GETAUTH_PASS:
1162         case POP3_GETAUTH_APOP:
1163         case POP3_GETRANGE_STAT:
1164         case POP3_GETRANGE_LAST:
1165         case POP3_GETRANGE_UIDL:
1166         case POP3_GETSIZE_LIST:
1167                 inc_progress_dialog_update(inc_dialog, inc_session);
1168                 break;
1169         case POP3_RETR:
1170                 inc_recv_data_progressive(session, 0, 0, inc_session);
1171                 break;
1172         case POP3_LOGOUT:
1173                 inc_progress_dialog_update(inc_dialog, inc_session);
1174                 break;
1175         default:
1176                 break;
1177         }
1178
1179         return 0;
1180 }
1181
1182 static gint inc_drop_message(Pop3Session *session, const gchar *file)
1183 {
1184         FolderItem *inbox;
1185         FolderItem *dropfolder;
1186         IncSession *inc_session = (IncSession *)(SESSION(session)->data);
1187         gint msgnum;
1188
1189         cm_return_val_if_fail(inc_session != NULL, -1);
1190
1191         if (session->ac_prefs->inbox) {
1192                 inbox = folder_find_item_from_identifier
1193                         (session->ac_prefs->inbox);
1194                 if (!inbox)
1195                         inbox = folder_get_default_inbox();
1196         } else
1197                 inbox = folder_get_default_inbox();
1198         if (!inbox) {
1199                 claws_unlink(file);
1200                 return -1;
1201         }
1202
1203         /* CLAWS: claws uses a global .processing folder for the filtering. */
1204         dropfolder = folder_get_default_processing(session->ac_prefs->account_id);
1205
1206         /* add msg file to drop folder */
1207         if ((msgnum = folder_item_add_msg(
1208                         dropfolder, file, NULL, TRUE)) < 0) {
1209                 claws_unlink(file);
1210                 return -1;
1211         }
1212
1213         return 0;
1214 }
1215
1216 static void inc_put_error(IncState istate, Pop3Session *session)
1217 {
1218         gchar *log_msg = NULL;
1219         gchar *err_msg = NULL;
1220         gboolean fatal_error = FALSE;
1221
1222         switch (istate) {
1223         case INC_CONNECT_ERROR:
1224                 fatal_error = TRUE;
1225                 if (prefs_common.no_recv_err_panel)
1226                         break;
1227                 err_msg = g_strdup_printf(_("Connection to %s:%d failed."),
1228                                           SESSION(session)->server, 
1229                                           SESSION(session)->port);
1230                 break;
1231         case INC_ERROR:
1232                 log_msg = _("Error occurred while processing mail.");
1233                 fatal_error = TRUE;
1234                 if (prefs_common.no_recv_err_panel)
1235                         break;
1236                 if (session->error_msg)
1237                         err_msg = g_strdup_printf
1238                                 (_("Error occurred while processing mail:\n%s"),
1239                                  session->error_msg);
1240                 else
1241                         err_msg = g_strdup(log_msg);
1242                 break;
1243         case INC_NO_SPACE:
1244                 log_msg = _("No disk space left.");
1245                 err_msg = g_strdup(log_msg);
1246                 fatal_error = TRUE;
1247                 break;
1248         case INC_IO_ERROR:
1249                 log_msg = _("Can't write file.");
1250                 err_msg = g_strdup(log_msg);
1251                 fatal_error = TRUE;
1252                 break;
1253         case INC_SOCKET_ERROR:
1254                 log_msg = _("Socket error.");
1255                 if (prefs_common.no_recv_err_panel)
1256                         break;
1257                 err_msg = g_strdup_printf(_("Socket error on connection to %s:%d."),
1258                                           SESSION(session)->server, 
1259                                           SESSION(session)->port);
1260                 break;
1261         case INC_EOF:
1262                 log_msg = _("Connection closed by the remote host.");
1263                 if (prefs_common.no_recv_err_panel)
1264                         break;
1265                 err_msg = g_strdup_printf(_("Connection to %s:%d closed by the remote host."), 
1266                                           SESSION(session)->server, 
1267                                           SESSION(session)->port);
1268                 break;
1269         case INC_LOCKED:
1270                 log_msg = _("Mailbox is locked.");
1271                 if (prefs_common.no_recv_err_panel)
1272                         break;
1273                 if (session->error_msg)
1274                         err_msg = g_strdup_printf(_("Mailbox is locked:\n%s"),
1275                                                   session->error_msg);
1276                 else
1277                         err_msg = g_strdup(log_msg);
1278                 break;
1279         case INC_AUTH_FAILED:
1280                 log_msg = _("Authentication failed.");
1281                 fatal_error = TRUE;
1282                 if (prefs_common.no_recv_err_panel)
1283                         break;
1284                 if (session->error_msg)
1285                         err_msg = g_strdup_printf
1286                                 (_("Authentication failed:\n%s"), session->error_msg);
1287                 else
1288                         err_msg = g_strdup(log_msg);
1289                 break;
1290         case INC_TIMEOUT:
1291                 log_msg = _("Session timed out. You may be able to "
1292                             "recover by increasing the timeout value in "
1293                             "Preferences/Other/Miscellaneous.");
1294                 if (prefs_common.no_recv_err_panel)
1295                         break;
1296                 err_msg = g_strdup_printf(_("Connection to %s:%d timed out."), 
1297                                           SESSION(session)->server, 
1298                                           SESSION(session)->port);
1299                 break;
1300         default:
1301                 break;
1302         }
1303
1304         if (log_msg) {
1305                 if (fatal_error)
1306                         log_error(LOG_PROTOCOL, "%s\n", log_msg);
1307                 else
1308                         log_warning(LOG_PROTOCOL, "%s\n", log_msg);
1309         }
1310         if (prefs_common.no_recv_err_panel && fatal_error)
1311                 mainwindow_show_error();
1312
1313         if (err_msg) {
1314                 alertpanel_error_log("%s", err_msg);
1315                 g_free(err_msg);
1316         }
1317 }
1318
1319 static void inc_cancel(IncProgressDialog *dialog)
1320 {
1321         IncSession *session;
1322
1323         cm_return_if_fail(dialog != NULL);
1324
1325         if (dialog->queue_list == NULL) {
1326                 inc_progress_dialog_destroy(dialog);
1327                 return;
1328         }
1329
1330         session = dialog->queue_list->data;
1331
1332         session->inc_state = INC_CANCEL;
1333
1334         log_message(LOG_PROTOCOL, _("Incorporation cancelled\n"));
1335 }
1336
1337 gboolean inc_is_active(void)
1338 {
1339         return (inc_dialog_list != NULL);
1340 }
1341
1342 void inc_cancel_all(void)
1343 {
1344         GList *cur;
1345
1346         for (cur = inc_dialog_list; cur != NULL; cur = cur->next)
1347                 inc_cancel((IncProgressDialog *)cur->data);
1348 }
1349
1350 static void inc_showlog_cb(GtkWidget *widget, gpointer data)
1351 {
1352         MainWindow *mainwin = mainwindow_get_mainwindow();
1353
1354         log_window_show(mainwin->logwin);
1355 }
1356
1357 static void inc_cancel_cb(GtkWidget *widget, gpointer data)
1358 {
1359         inc_cancel((IncProgressDialog *)data);
1360 }
1361
1362 static gint inc_dialog_delete_cb(GtkWidget *widget, GdkEventAny *event,
1363                                  gpointer data)
1364 {
1365         IncProgressDialog *dialog = (IncProgressDialog *)data;
1366
1367         if (dialog->queue_list == NULL)
1368                 inc_progress_dialog_destroy(dialog);
1369
1370         return TRUE;
1371 }
1372
1373 static gint inc_spool_account(PrefsAccount *account)
1374 {
1375         FolderItem *inbox;
1376         gchar *mbox;
1377         gint result;
1378
1379         if (account->local_inbox) {
1380                 inbox = folder_find_item_from_identifier(account->local_inbox);
1381                 if (!inbox)
1382                         inbox = folder_get_default_inbox();
1383         } else
1384                 inbox = folder_get_default_inbox();
1385
1386         if (account->local_mbox) {
1387                 if (is_file_exist(account->local_mbox))
1388                         mbox = g_strdup(account->local_mbox);
1389                 else if (is_dir_exist(account->local_mbox)) 
1390                         mbox = g_strconcat(account->local_mbox, G_DIR_SEPARATOR_S,
1391                                            g_get_user_name(), NULL);
1392                 else {
1393                         debug_print("%s: local mailbox not found.\n", 
1394                                     account->local_mbox);
1395                         return -1;
1396                 }
1397         } else {
1398                 debug_print("local mailbox not set in account info.\n");
1399                 return -1;
1400         }       
1401
1402         result = get_spool(inbox, mbox, account);
1403         g_free(mbox);
1404         
1405         statusbar_pop_all();
1406         
1407         return result;
1408 }
1409
1410 static gint get_spool(FolderItem *dest, const gchar *mbox, PrefsAccount *account)
1411 {
1412         gint msgs, size;
1413         gint lockfd;
1414         gchar tmp_mbox[MAXPATHLEN + 1];
1415
1416         cm_return_val_if_fail(dest != NULL, -1);
1417         cm_return_val_if_fail(mbox != NULL, -1);
1418         cm_return_val_if_fail(account != NULL, -1);
1419
1420         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1421                 debug_print("%s: no messages in local mailbox.\n", mbox);
1422                 return 0;
1423         } else if (size < 0)
1424                 return -1;
1425
1426         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1427                 return -1;
1428
1429         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox.%p",
1430                    get_tmp_dir(), G_DIR_SEPARATOR, mbox);
1431
1432         if (copy_mbox(lockfd, tmp_mbox) < 0) {
1433                 unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1434                 return -1;
1435         }
1436
1437         debug_print("Getting new messages from %s into %s...\n",
1438                     mbox, dest->path);
1439
1440         msgs = proc_mbox(dest, tmp_mbox, account->filter_on_recv, account);
1441
1442         claws_unlink(tmp_mbox);
1443         if (msgs >= 0) empty_mbox(mbox);
1444         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1445
1446         return msgs;
1447 }
1448
1449 void inc_lock_real(void)
1450 {
1451         inc_lock_count++;
1452 }
1453
1454 void inc_unlock_real(void)
1455 {
1456         if (inc_lock_count > 0)
1457                 inc_lock_count--;
1458 }
1459
1460 static guint autocheck_timer = 0;
1461 static gpointer autocheck_data = NULL;
1462
1463 static void inc_notify_cmd(gint new_msgs, gboolean notify)
1464 {
1465         gchar *buf, *numpos, *ret_str;
1466         gssize by_read = 0, by_written = 0;
1467
1468         if (!(new_msgs && notify && prefs_common.newmail_notify_cmd &&
1469             *prefs_common.newmail_notify_cmd))
1470                      return;
1471
1472         buf = g_strdup(prefs_common.newmail_notify_cmd);
1473         if ((numpos = strstr(buf, "%d")) != NULL) {
1474                 gchar *buf2;
1475
1476                 *numpos = '\0';
1477                 buf2 = g_strdup_printf("%s%d%s", buf, new_msgs, numpos + 2);
1478                 g_free(buf);
1479                 buf = buf2;
1480         }
1481
1482         ret_str = g_locale_from_utf8(buf, strlen(buf), &by_read, &by_written,
1483                                      NULL);
1484         if (ret_str && by_written) {
1485                 g_free(buf);
1486                 buf = ret_str;
1487         }
1488         debug_print("executing new mail notification command: %s\n", buf);
1489         execute_command_line(buf, TRUE, NULL);
1490
1491         g_free(buf);
1492 }
1493
1494 void inc_autocheck_timer_init(MainWindow *mainwin)
1495 {
1496         autocheck_data = mainwin;
1497         inc_autocheck_timer_set();
1498 }
1499
1500 static void inc_autocheck_timer_set_interval(guint _interval)
1501 {
1502         guint interval = _interval;
1503
1504         /* Convert the interval to seconds if needed. */
1505         if (_interval % 1000 == 0)
1506                 interval /= 1000;
1507
1508         inc_autocheck_timer_remove();
1509         /* last test is to avoid re-enabling auto_check after modifying 
1510            the common preferences */
1511         if (prefs_common.autochk_newmail && autocheck_data
1512             && prefs_common.work_offline == FALSE) {
1513                         autocheck_timer =
1514                                 g_timeout_add_seconds(interval, inc_autocheck_func, autocheck_data);
1515                 debug_print("added global inc timer %d at %u seconds\n",
1516                                 autocheck_timer, interval);
1517         }
1518 }
1519
1520 void inc_autocheck_timer_set(void)
1521 {
1522         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 1000);
1523 }
1524
1525 void inc_autocheck_timer_remove(void)
1526 {
1527         if (autocheck_timer) {
1528                 debug_print("removed global inc timer %d\n", autocheck_timer);
1529                 g_source_remove(autocheck_timer);
1530                 autocheck_timer = 0;
1531         }
1532 }
1533
1534 static gint inc_autocheck_func(gpointer data)
1535 {
1536         MainWindow *mainwin = (MainWindow *)data;
1537
1538         if (inc_lock_count) {
1539                 debug_print("global inc: autocheck is locked.\n");
1540                 inc_autocheck_timer_set_interval(1000);
1541                 return FALSE;
1542         }
1543
1544         inc_all_account_mail(mainwin, TRUE, FALSE, prefs_common.newmail_notify_auto);
1545         inc_autocheck_timer_set();
1546
1547         return FALSE;
1548 }
1549
1550 static gboolean inc_account_autocheck_func(gpointer data)
1551 {
1552         PrefsAccount *account = (PrefsAccount *)data;
1553         GList *list = NULL;
1554
1555         cm_return_val_if_fail(account != NULL, FALSE);
1556
1557         debug_print("account %d: inc_account_autocheck_func\n",
1558                         account->account_id);
1559
1560         list = g_list_append(list, account);
1561         inc_account_list_mail(mainwindow_get_mainwindow(),
1562                         list, TRUE, prefs_common.newmail_notify_auto);
1563         g_list_free(list);
1564
1565         inc_account_autocheck_timer_set_interval(account);
1566
1567         return FALSE;
1568 }
1569
1570 void inc_account_autocheck_timer_remove(PrefsAccount *account)
1571 {
1572         cm_return_if_fail(account != NULL);
1573
1574         if (account->autocheck_timer != 0) {
1575                 g_source_remove(account->autocheck_timer);
1576                 debug_print("INC: account %d: removed inc timer %d\n", account->account_id,
1577                                 account->autocheck_timer);
1578                 account->autocheck_timer = 0;
1579         }
1580 }
1581
1582 void inc_account_autocheck_timer_set_interval(PrefsAccount *account)
1583 {
1584         cm_return_if_fail(account != NULL);
1585
1586         inc_account_autocheck_timer_remove(account);
1587
1588         if (account->autochk_use_default
1589                         || !account->autochk_use_custom
1590                         || account->autochk_itv == 0)
1591                 return;
1592
1593         account->autocheck_timer = g_timeout_add_seconds(
1594                         account->autochk_itv, inc_account_autocheck_func, account);
1595         debug_print("INC: account %d: added inc timer %d at %u seconds\n",
1596                         account->account_id, account->autocheck_timer, account->autochk_itv);
1597 }
1598
1599 gboolean inc_offline_should_override(gboolean force_ask, const gchar *msg)
1600 {
1601         gint length = 10; /* seconds */
1602         gint answer = G_ALERTDEFAULT;
1603
1604 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1605         /* If no network connection is available, override is not possible */
1606         if(!networkmanager_is_online(NULL))
1607                 return FALSE;
1608 #endif
1609
1610         if (prefs_common.autochk_newmail)
1611                 length = prefs_common.autochk_itv; /* seconds */
1612
1613         if (force_ask) {
1614                 inc_offline_overridden_no = (time_t)0;
1615         }
1616
1617         if (prefs_common.work_offline) {
1618                 gchar *tmp = NULL;
1619                 
1620                 if (time(NULL) - inc_offline_overridden_yes < length * 60) /* seconds */
1621                          return TRUE;
1622                 else if (time(NULL) - inc_offline_overridden_no < length * 60) /* seconds */
1623                          return FALSE;
1624
1625                 if (!force_ask) {
1626                         gchar *unit = _("seconds");
1627
1628                         /* show the offline override time (length) using the must appropriate unit:
1629                            the biggest unit possible (hours, minutes, seconds), provided that there
1630                            is not inferior unit involved: 1 hour, 150 minutes, 25 minutes, 90 minutes,
1631                            30 seconds, 90 seconds. */
1632                         if ((length / 3600) > 0) { /* hours? */
1633                                 if (((length % 3600) % 60) == 0) { /* no seconds left? */
1634                                         if ((length % 3600) > 0) { /* minutes left? */
1635                                                 length = length / 60;
1636                                                 unit = ngettext("minute", "minutes", length);
1637                                         } else {
1638                                                 length = length / 3600;
1639                                                 unit = ngettext("hour", "hours", length);
1640                                         }
1641                                 } /* else: seconds */
1642                         } else {
1643                                 if ((length / 60) > 0) { /* minutes left? */
1644                                         if ((length % 60) == 0) {
1645                                                 length = length / 60;
1646                                                 unit = ngettext("minute", "minutes", length);
1647                                         }
1648                                 } /* else: seconds */
1649                         }
1650                         tmp = g_strdup_printf(
1651                                 _("%s%sYou're working offline. Override for %d %s?"),
1652                                 msg?msg:"", 
1653                                 msg?"\n\n":"",
1654                                 length, unit);
1655                 } else
1656                         tmp = g_strdup_printf(
1657                                 _("%s%sYou're working offline. Override?"),
1658                                 msg?msg:"", 
1659                                 msg?"\n\n":"");
1660
1661                 answer = alertpanel(_("Offline warning"), 
1662                                tmp,
1663                                GTK_STOCK_NO, GTK_STOCK_YES,
1664                                 !force_ask? _("On_ly once"):NULL, ALERTFOCUS_SECOND);
1665                 g_free(tmp);
1666                 if (answer == G_ALERTALTERNATE) {
1667                         inc_offline_overridden_yes = time(NULL);
1668                         return TRUE;
1669                 } else if (answer == G_ALERTDEFAULT) {
1670                         if (!force_ask)
1671                                 inc_offline_overridden_no  = time(NULL);
1672                         return FALSE;
1673                 } else {
1674                         inc_reset_offline_override_timers();
1675                         return TRUE;
1676                 }
1677         }
1678         return TRUE;
1679 }
1680
1681 void inc_reset_offline_override_timers()
1682 {
1683         debug_print("resetting offline override timers\n");
1684         inc_offline_overridden_yes = (time_t)0;
1685         inc_offline_overridden_no  = (time_t)0;
1686 }