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