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