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