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