5f30ad81df6eebc6d37e0e8db958e08b552bf506
[claws.git] / src / news.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 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 #ifdef HAVE_LIBETPAN
25
26 #include "defs.h"
27
28 #include <glib.h>
29 #include <glib/gi18n.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <dirent.h>
34 #include <unistd.h>
35 #include <time.h>
36 #include <libetpan/libetpan.h>
37
38 #include "nntp-thread.h"
39 #include "news.h"
40 #include "news_gtk.h"
41 #include "socket.h"
42 #include "recv.h"
43 #include "procmsg.h"
44 #include "procheader.h"
45 #include "folder.h"
46 #include "session.h"
47 #include "statusbar.h"
48 #include "codeconv.h"
49 #include "utils.h"
50 #include "prefs_common.h"
51 #include "prefs_account.h"
52 #include "inputdialog.h"
53 #include "log.h"
54 #include "progressindicator.h"
55 #include "remotefolder.h"
56 #include "alertpanel.h"
57 #include "inc.h"
58 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
59 #  include "ssl.h"
60 #endif
61
62 #define NNTP_PORT       119
63 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
64 #define NNTPS_PORT      563
65 #endif
66
67 typedef struct _NewsFolder      NewsFolder;
68 typedef struct _NewsSession     NewsSession;
69
70 #define NEWS_FOLDER(obj)        ((NewsFolder *)obj)
71 #define NEWS_SESSION(obj)       ((NewsSession *)obj)
72
73 struct _NewsFolder
74 {
75         RemoteFolder rfolder;
76
77         gboolean use_auth;
78         gboolean lock_count;
79         guint refcnt;
80 };
81
82 struct _NewsSession
83 {
84         Session session;
85
86         gchar *group;
87 };
88
89 static void news_folder_init(Folder *folder, const gchar *name,
90                              const gchar *path);
91
92 static Folder   *news_folder_new        (const gchar    *name,
93                                          const gchar    *folder);
94 static void      news_folder_destroy    (Folder         *folder);
95
96 static gchar *news_fetch_msg            (Folder         *folder,
97                                          FolderItem     *item,
98                                          gint            num);
99 static void news_remove_cached_msg      (Folder         *folder, 
100                                          FolderItem     *item, 
101                                          MsgInfo        *msginfo);
102 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
103 static Session *news_session_new         (Folder        *folder,
104                                           const gchar   *server,
105                                           gushort        port,
106                                           const gchar   *userid,
107                                           const gchar   *passwd,
108                                           SSLType        ssl_type);
109 #else
110 static Session *news_session_new         (Folder        *folder,
111                                           const gchar   *server,
112                                           gushort        port,
113                                           const gchar   *userid,
114                                           const gchar   *passwd);
115 #endif
116
117 static gint news_get_article             (Folder        *folder,
118                                           gint           num,
119                                           gchar         *filename);
120
121 static gint news_select_group            (Folder        *folder,
122                                           const gchar   *group,
123                                           gint          *num,
124                                           gint          *first,
125                                           gint          *last);
126 static MsgInfo *news_parse_xover         (struct newsnntp_xover_resp_item *item);
127 static gchar *news_parse_xhdr            (clist         *list,
128                                           MsgInfo       *msginfo);
129 static gint news_get_num_list                    (Folder        *folder, 
130                                           FolderItem    *item,
131                                           GSList       **list,
132                                           gboolean      *old_uids_valid);
133 static MsgInfo *news_get_msginfo                 (Folder        *folder, 
134                                           FolderItem    *item,
135                                           gint           num);
136 static GSList *news_get_msginfos                 (Folder        *folder,
137                                           FolderItem    *item,
138                                           GSList        *msgnum_list);
139 static gboolean news_scan_required               (Folder        *folder,
140                                           FolderItem    *item);
141
142 static gchar *news_folder_get_path       (Folder        *folder);
143 static gchar *news_item_get_path                 (Folder        *folder,
144                                           FolderItem    *item);
145 static void news_synchronise             (FolderItem    *item, gint days);
146 static int news_remove_msg               (Folder        *folder, 
147                                           FolderItem    *item, 
148                                           gint           msgnum);
149 static gint news_rename_folder           (Folder *folder,
150                                           FolderItem *item,
151                                           const gchar *name);
152 static gint news_remove_folder           (Folder        *folder,
153                                           FolderItem    *item);
154 static FolderClass news_class;
155
156 FolderClass *news_get_class(void)
157 {
158         if (news_class.idstr == NULL) {
159                 news_class.type = F_NEWS;
160                 news_class.idstr = "news";
161                 news_class.uistr = "News";
162
163                 /* Folder functions */
164                 news_class.new_folder = news_folder_new;
165                 news_class.destroy_folder = news_folder_destroy;
166
167                 /* FolderItem functions */
168                 news_class.item_get_path = news_item_get_path;
169                 news_class.get_num_list = news_get_num_list;
170                 news_class.scan_required = news_scan_required;
171                 news_class.rename_folder = news_rename_folder;
172                 news_class.remove_folder = news_remove_folder;
173
174                 /* Message functions */
175                 news_class.get_msginfo = news_get_msginfo;
176                 news_class.get_msginfos = news_get_msginfos;
177                 news_class.fetch_msg = news_fetch_msg;
178                 news_class.synchronise = news_synchronise;
179                 news_class.remove_msg = news_remove_msg;
180                 news_class.remove_cached_msg = news_remove_cached_msg;
181         };
182
183         return &news_class;
184 }
185
186 guint nntp_folder_get_refcnt(Folder *folder)
187 {
188         return ((NewsFolder *)folder)->refcnt;
189 }
190
191 void nntp_folder_ref(Folder *folder)
192 {
193         ((NewsFolder *)folder)->refcnt++;
194 }
195
196 void nntp_folder_unref(Folder *folder)
197 {
198         if (((NewsFolder *)folder)->refcnt > 0)
199                 ((NewsFolder *)folder)->refcnt--;
200 }
201
202 static int news_remove_msg               (Folder        *folder, 
203                                           FolderItem    *item, 
204                                           gint           msgnum)
205 {
206         gchar *path, *filename;
207
208         g_return_val_if_fail(folder != NULL, -1);
209         g_return_val_if_fail(item != NULL, -1);
210
211         path = folder_item_get_path(item);
212         if (!is_dir_exist(path))
213                 make_dir_hier(path);
214         
215         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msgnum), NULL);
216         g_free(path);
217         claws_unlink(filename);
218         g_free(filename);
219         return 0;
220 }
221
222 static void news_folder_lock(NewsFolder *folder)
223 {
224         folder->lock_count++;
225 }
226
227 static void news_folder_unlock(NewsFolder *folder)
228 {
229         if (folder->lock_count > 0)
230                 folder->lock_count--;
231 }
232
233 int news_folder_locked(Folder *folder)
234 {
235         if (folder == NULL)
236                 return 0;
237
238         return NEWS_FOLDER(folder)->lock_count;
239 }
240
241 static Folder *news_folder_new(const gchar *name, const gchar *path)
242 {
243         Folder *folder;
244
245         folder = (Folder *)g_new0(NewsFolder, 1);
246         folder->klass = &news_class;
247         news_folder_init(folder, name, path);
248
249         return folder;
250 }
251
252 static void news_folder_destroy(Folder *folder)
253 {
254         gchar *dir;
255
256         while (nntp_folder_get_refcnt(folder) > 0)
257                 gtk_main_iteration();
258
259         dir = news_folder_get_path(folder);
260         if (is_dir_exist(dir))
261                 remove_dir_recursive(dir);
262         g_free(dir);
263
264         nntp_done(folder);
265         folder_remote_folder_destroy(REMOTE_FOLDER(folder));
266 }
267
268 static void news_folder_init(Folder *folder, const gchar *name,
269                              const gchar *path)
270 {
271         folder_remote_folder_init(folder, name, path);
272 }
273
274 static void news_session_destroy(Session *session)
275 {
276         NewsSession *news_session = NEWS_SESSION(session);
277
278         g_return_if_fail(session != NULL);
279
280         if (news_session->group)
281                 g_free(news_session->group);
282 }
283
284 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
285 static Session *news_session_new(Folder *folder, const gchar *server, gushort port,
286                                  const gchar *userid, const gchar *passwd,
287                                  SSLType ssl_type)
288 #else
289 static Session *news_session_new(Folder *folder, const gchar *server, gushort port,
290                                  const gchar *userid, const gchar *passwd)
291 #endif
292 {
293         NewsSession *session;
294         int r = 0;
295         g_return_val_if_fail(server != NULL, NULL);
296
297         log_message(LOG_PROTOCOL, _("creating NNTP connection to %s:%d ...\n"), server, port);
298
299         session = g_new0(NewsSession, 1);
300         session_init(SESSION(session), folder->account, FALSE);
301         SESSION(session)->type             = SESSION_NEWS;
302         SESSION(session)->server           = g_strdup(server);
303         SESSION(session)->sock             = NULL;
304         SESSION(session)->destroy          = news_session_destroy;
305         
306         nntp_init(folder);
307
308 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
309         if (ssl_type != SSL_NONE)
310                 r = nntp_threaded_connect_ssl(folder, server, port);
311         else
312 #endif
313                 r = nntp_threaded_connect(folder, server, port);
314         
315         if (r != NEWSNNTP_NO_ERROR) {
316                 log_error(LOG_PROTOCOL, _("Error logging in to %s:%d ...\n"), server, port);
317                 session_destroy(SESSION(session));
318                 return NULL;
319         }
320         
321         return SESSION(session);
322 }
323
324 static Session *news_session_new_for_folder(Folder *folder)
325 {
326         Session *session;
327         PrefsAccount *ac;
328         const gchar *userid = NULL;
329         gchar *passwd = NULL;
330         gushort port;
331
332         g_return_val_if_fail(folder != NULL, NULL);
333         g_return_val_if_fail(folder->account != NULL, NULL);
334
335         ac = folder->account;
336         if (ac->use_nntp_auth && ac->userid && ac->userid[0]) {
337                 userid = ac->userid;
338                 if (ac->passwd && ac->passwd[0])
339                         passwd = g_strdup(ac->passwd);
340                 else
341                         passwd = input_dialog_query_password_keep(ac->nntp_server,
342                                                                   userid,
343                                                                   &(ac->session_passwd));
344         }
345
346 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
347         port = ac->set_nntpport ? ac->nntpport
348                 : ac->ssl_nntp ? NNTPS_PORT : NNTP_PORT;
349         session = news_session_new(folder, ac->nntp_server, port, userid, passwd,
350                                    ac->ssl_nntp);
351 #else
352         if (ac->ssl_nntp != SSL_NONE) {
353                 if (alertpanel_full(_("Insecure connection"),
354                         _("This connection is configured to be secured "
355                           "using SSL, but SSL is not available in this "
356                           "build of Claws Mail. \n\n"
357                           "Do you want to continue connecting to this "
358                           "server? The communication would not be "
359                           "secure."),
360                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), 
361                           NULL, FALSE, NULL, ALERT_WARNING,
362                           G_ALERTDEFAULT) != G_ALERTALTERNATE)
363                         return NULL;
364         }
365         port = ac->set_nntpport ? ac->nntpport : NNTP_PORT;
366         session = news_session_new(folder, ac->nntp_server, port, userid, passwd);
367 #endif
368
369         if ((session != NULL) && ac->use_nntp_auth) { /* FIXME:  && ac->use_nntp_auth_onconnect */
370                 if (nntp_threaded_login(folder, userid, passwd) !=
371                         NEWSNNTP_NO_ERROR) {
372                         log_error(LOG_PROTOCOL, _("Error authenticating to %s:%d ...\n"), ac->nntp_server, port);
373                         session_destroy(SESSION(session));
374                         g_free(passwd);
375                         if (ac->session_passwd) {
376                                 g_free(ac->session_passwd);
377                                 ac->session_passwd = NULL;
378                         }
379                         return NULL;
380                 }
381         }
382         g_free(passwd);
383
384         return session;
385 }
386
387 static NewsSession *news_session_get(Folder *folder)
388 {
389         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
390         struct tm lt;
391         int r;
392         
393         g_return_val_if_fail(folder != NULL, NULL);
394         g_return_val_if_fail(FOLDER_CLASS(folder) == &news_class, NULL);
395         g_return_val_if_fail(folder->account != NULL, NULL);
396
397         if (prefs_common.work_offline && 
398             !inc_offline_should_override(FALSE,
399                 _("Claws Mail needs network access in order "
400                   "to access the News server."))) {
401                 return NULL;
402         }
403
404         if (!rfolder->session) {
405                 rfolder->session = news_session_new_for_folder(folder);
406                 return NEWS_SESSION(rfolder->session);
407         }
408
409         if (time(NULL) - rfolder->session->last_access_time <
410                 SESSION_TIMEOUT_INTERVAL) {
411                 return NEWS_SESSION(rfolder->session);
412         }
413
414         if ((r = nntp_threaded_date(folder, &lt)) != NEWSNNTP_NO_ERROR) {
415                 if (r != NEWSNNTP_ERROR_COMMAND_NOT_SUPPORTED &&
416                     r != NEWSNNTP_ERROR_COMMAND_NOT_UNDERSTOOD) {
417                         log_warning(LOG_PROTOCOL, _("NNTP connection to %s:%d has been"
418                               " disconnected. Reconnecting...\n"),
419                             folder->account->nntp_server,
420                             folder->account->set_nntpport ?
421                             folder->account->nntpport : NNTP_PORT);
422                         session_destroy(rfolder->session);
423                         rfolder->session = news_session_new_for_folder(folder);
424                 }
425         }
426         
427         if (rfolder->session)
428                 session_set_access_time(rfolder->session);
429
430         return NEWS_SESSION(rfolder->session);
431 }
432
433 static void news_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
434 {
435         gchar *path, *filename;
436
437         path = folder_item_get_path(item);
438
439         if (!is_dir_exist(path)) {
440                 g_free(path);
441                 return;
442         }
443
444         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
445         g_free(path);
446
447         if (is_file_exist(filename)) {
448                 claws_unlink(filename);
449         }
450         g_free(filename);
451 }
452
453 static gchar *news_fetch_msg(Folder *folder, FolderItem *item, gint num)
454 {
455         gchar *path, *filename;
456         NewsSession *session;
457         gint ok;
458
459         g_return_val_if_fail(folder != NULL, NULL);
460         g_return_val_if_fail(item != NULL, NULL);
461
462         path = folder_item_get_path(item);
463         if (!is_dir_exist(path))
464                 make_dir_hier(path);
465         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(num), NULL);
466         g_free(path);
467
468         if (is_file_exist(filename)) {
469                 debug_print("article %d has been already cached.\n", num);
470                 return filename;
471         }
472
473         session = news_session_get(folder);
474         if (!session) {
475                 g_free(filename);
476                 return NULL;
477         }
478
479         ok = news_select_group(folder, item->path, NULL, NULL, NULL);
480         if (ok != NEWSNNTP_NO_ERROR) {
481                 if (ok == NEWSNNTP_ERROR_STREAM) {
482                         session_destroy(SESSION(session));
483                         REMOTE_FOLDER(folder)->session = NULL;
484                 }
485                 g_free(filename);
486                 return NULL;
487         }
488
489         debug_print("getting article %d...\n", num);
490         ok = news_get_article(folder,
491                               num, filename);
492         if (ok != NEWSNNTP_NO_ERROR) {
493                 g_warning("can't read article %d\n", num);
494                 if (ok == NEWSNNTP_ERROR_STREAM) {
495                         session_destroy(SESSION(session));
496                         REMOTE_FOLDER(folder)->session = NULL;
497                 }
498                 g_free(filename);
499                 return NULL;
500         }
501         GTK_EVENTS_FLUSH();
502         return filename;
503 }
504
505 static NewsGroupInfo *news_group_info_new(const gchar *name,
506                                           gint first, gint last, gchar type)
507 {
508         NewsGroupInfo *ginfo;
509
510         ginfo = g_new(NewsGroupInfo, 1);
511         ginfo->name = g_strdup(name);
512         ginfo->first = first;
513         ginfo->last = last;
514         ginfo->type = type;
515
516         return ginfo;
517 }
518
519 static void news_group_info_free(NewsGroupInfo *ginfo)
520 {
521         g_free(ginfo->name);
522         g_free(ginfo);
523 }
524
525 static gint news_group_info_compare(NewsGroupInfo *ginfo1,
526                                     NewsGroupInfo *ginfo2)
527 {
528         return g_ascii_strcasecmp(ginfo1->name, ginfo2->name);
529 }
530
531 GSList *news_get_group_list(Folder *folder)
532 {
533         gchar *path, *filename;
534         FILE *fp;
535         GSList *list = NULL;
536         GSList *last = NULL;
537         gchar buf[BUFFSIZE];
538
539         g_return_val_if_fail(folder != NULL, NULL);
540         g_return_val_if_fail(FOLDER_CLASS(folder) == &news_class, NULL);
541
542         path = folder_item_get_path(FOLDER_ITEM(folder->node->data));
543         if (!is_dir_exist(path))
544                 make_dir_hier(path);
545         filename = g_strconcat(path, G_DIR_SEPARATOR_S, NEWSGROUP_LIST, NULL);
546         g_free(path);
547
548         if ((fp = g_fopen(filename, "rb")) == NULL) {
549                 NewsSession *session;
550                 gint ok;
551                 clist *grouplist = NULL;
552                 clistiter *cur;
553                 fp = g_fopen(filename, "wb");
554                 
555                 if (!fp) {
556                         g_free(filename);
557                         return NULL;
558                 }
559                 session = news_session_get(folder);
560                 if (!session) {
561                         fclose(fp);
562                         g_free(filename);
563                         return NULL;
564                 }
565
566                 ok = nntp_threaded_list(folder, &grouplist);
567                 
568                 if (ok != NEWSNNTP_NO_ERROR) {
569                         if (ok == NEWSNNTP_ERROR_STREAM) {
570                                 session_destroy(SESSION(session));
571                                 REMOTE_FOLDER(folder)->session = NULL;
572                         }
573                         fclose(fp);
574                         g_free(filename);
575                         return NULL;
576                 }
577                 
578                 for (cur = clist_begin(grouplist); cur; cur = clist_next(cur)) {
579                         struct newsnntp_group_info *info = (struct newsnntp_group_info *)
580                                                                 clist_content(cur);
581                         if (fprintf(fp, "%s %d %d %c\n",
582                                 info->grp_name,
583                                 info->grp_last,
584                                 info->grp_first,
585                                 info->grp_type) < 0) {
586                                 log_error(LOG_PROTOCOL, ("Can't write newsgroup list\n"));
587                                 session_destroy(SESSION(session));
588                                 REMOTE_FOLDER(folder)->session = NULL;
589                                 fclose(fp);
590                                 g_free(filename);
591                                 newsnntp_list_free(grouplist);
592                                 return NULL;
593                         }
594                 }
595                 newsnntp_list_free(grouplist);
596
597                 if (fclose(fp) == EOF) {
598                         log_error(LOG_PROTOCOL, ("Can't write newsgroup list\n"));
599                         session_destroy(SESSION(session));
600                         REMOTE_FOLDER(folder)->session = NULL;
601                         g_free(filename);
602                         return NULL;
603                 }
604
605                 if ((fp = g_fopen(filename, "rb")) == NULL) {
606                         FILE_OP_ERROR(filename, "fopen");
607                         g_free(filename);
608                         return NULL;
609                 }
610         }
611
612         while (fgets(buf, sizeof(buf), fp) != NULL) {
613                 gchar *p = buf;
614                 gchar *name;
615                 gint last_num;
616                 gint first_num;
617                 gchar type;
618                 NewsGroupInfo *ginfo;
619
620                 p = strchr(p, ' ');
621                 if (!p) continue;
622                 *p = '\0';
623                 p++;
624                 name = buf;
625
626                 if (sscanf(p, "%d %d %c", &last_num, &first_num, &type) < 3)
627                         continue;
628
629                 ginfo = news_group_info_new(name, first_num, last_num, type);
630
631                 if (!last)
632                         last = list = g_slist_append(NULL, ginfo);
633                 else {
634                         last = g_slist_append(last, ginfo);
635                         last = last->next;
636                 }
637         }
638
639         fclose(fp);
640         g_free(filename);
641
642         list = g_slist_sort(list, (GCompareFunc)news_group_info_compare);
643
644         return list;
645 }
646
647 void news_group_list_free(GSList *group_list)
648 {
649         GSList *cur;
650
651         if (!group_list) return;
652
653         for (cur = group_list; cur != NULL; cur = cur->next)
654                 news_group_info_free((NewsGroupInfo *)cur->data);
655         g_slist_free(group_list);
656 }
657
658 void news_remove_group_list_cache(Folder *folder)
659 {
660         gchar *path, *filename;
661
662         g_return_if_fail(folder != NULL);
663         g_return_if_fail(FOLDER_CLASS(folder) == &news_class);
664
665         path = folder_item_get_path(FOLDER_ITEM(folder->node->data));
666         filename = g_strconcat(path, G_DIR_SEPARATOR_S, NEWSGROUP_LIST, NULL);
667         g_free(path);
668
669         if (is_file_exist(filename)) {
670                 if (remove(filename) < 0)
671                         FILE_OP_ERROR(filename, "remove");
672         }
673         g_free(filename);
674 }
675
676 gint news_post(Folder *folder, const gchar *file)
677 {
678         gint ok;
679         char *contents = file_read_to_str_no_recode(file);
680         NewsSession *session;
681
682         g_return_val_if_fail(folder != NULL, -1);
683         g_return_val_if_fail(FOLDER_CLASS(folder) == &news_class, -1);
684         g_return_val_if_fail(contents != NULL, -1);
685         
686         session = news_session_get(folder);
687         if (!session)  {
688                 g_free(contents);
689                 return -1;
690         }
691         
692         ok = nntp_threaded_post(folder, contents, strlen(contents));
693
694         if (ok != NEWSNNTP_NO_ERROR && ok != NEWSNNTP_ERROR_STREAM) {
695                 ok = nntp_threaded_mode_reader(folder);
696                 if (ok == NEWSNNTP_NO_ERROR)
697                         ok = nntp_threaded_post(folder, contents, strlen(contents));
698         }
699         g_free(contents);
700
701         if (ok == NEWSNNTP_ERROR_STREAM) {
702                 session_destroy(SESSION(session));
703                 REMOTE_FOLDER(folder)->session = NULL;
704         }
705
706         return (ok == NEWSNNTP_NO_ERROR ? 0 : -1);
707 }
708
709 static gint news_get_article(Folder *folder, gint num, gchar *filename)
710 {
711         size_t len;
712         char *result = NULL;
713         int r;
714         
715         r = nntp_threaded_article(folder, num, &result, &len);
716         
717         if (r == NEWSNNTP_NO_ERROR) {
718                 if (str_write_to_file(result, filename) < 0)
719                         return -1;
720                 g_free(result);
721         }
722         
723         return r;
724 }
725
726 /**
727  * news_select_group:
728  * @session: Active NNTP session.
729  * @group: Newsgroup name.
730  * @num: Estimated number of articles.
731  * @first: First article number.
732  * @last: Last article number.
733  *
734  * Select newsgroup @group with the GROUP command if it is not already
735  * selected in @session, or article numbers need to be returned.
736  *
737  * Return value: NNTP result code.
738  **/
739 static gint news_select_group(Folder *folder, const gchar *group,
740                               gint *num, gint *first, gint *last)
741 {
742         gint ok;
743         gint num_, first_, last_;
744         struct newsnntp_group_info *info = NULL;
745         NewsSession *session = NEWS_SESSION(news_session_get(folder));
746
747         g_return_val_if_fail(session != NULL, -1);
748         
749         if (!num || !first || !last) {
750                 if (session->group && g_ascii_strcasecmp(session->group, group) == 0)
751                         return NEWSNNTP_NO_ERROR;
752                 num = &num_;
753                 first = &first_;
754                 last = &last_;
755         }
756
757         g_free(session->group);
758         session->group = NULL;
759
760         ok = nntp_threaded_group(folder, group, &info);
761         
762         if (ok != NEWSNNTP_NO_ERROR && 
763             ok != NEWSNNTP_ERROR_STREAM && 
764             ok != NEWSNNTP_WARNING_REQUEST_AUTHORIZATION_USERNAME) {
765                 ok = nntp_threaded_mode_reader(folder);
766                 if (ok == NEWSNNTP_NO_ERROR)
767                         ok = nntp_threaded_group(folder, group, &info);
768         }
769
770         if (ok == NEWSNNTP_NO_ERROR && info) {
771                 session->group = g_strdup(group);
772                 *num = info->grp_first;
773                 *first = info->grp_first;
774                 *last = info->grp_last;
775                 newsnntp_group_free(info);
776         } else {
777                 log_warning(LOG_PROTOCOL, _("couldn't select group: %s\n"), group);
778         }
779         return ok;
780 }
781
782 static MsgInfo *news_parse_xover(struct newsnntp_xover_resp_item *item)
783 {
784         MsgInfo *msginfo;
785
786         /* set MsgInfo */
787         msginfo = procmsg_msginfo_new();
788         msginfo->msgnum = item->ovr_article;
789         msginfo->size = item->ovr_size;
790
791         msginfo->date = g_strdup(item->ovr_date);
792         msginfo->date_t = procheader_date_parse(NULL, item->ovr_date, 0);
793
794         msginfo->from = conv_unmime_header(item->ovr_author, NULL);
795         msginfo->fromname = procheader_get_fromname(msginfo->from);
796
797         msginfo->subject = conv_unmime_header(item->ovr_subject, NULL);
798
799         remove_return(msginfo->from);
800         remove_return(msginfo->fromname);
801         remove_return(msginfo->subject);
802
803         if (item->ovr_message_id) {
804                 gchar *tmp = g_strdup(item->ovr_message_id);
805                 extract_parenthesis(tmp, '<', '>');
806                 remove_space(tmp);
807                 if (*tmp != '\0')
808                         msginfo->msgid = g_strdup(tmp);
809                 g_free(tmp);
810         }                        
811
812         /* FIXME: this is a quick fix; references' meaning was changed
813          * into having the actual list of references in the References: header.
814          * We need a GSList here, so msginfo_free() and msginfo_copy() can do 
815          * their things properly. */ 
816         if (item->ovr_references && *(item->ovr_references)) {   
817                 gchar **ref_tokens = g_strsplit(item->ovr_references, " ", -1);
818                 guint i = 0;
819                 char *tmp;
820                 char *p;
821                 while (ref_tokens[i]) {
822                         gchar *cur_ref = ref_tokens[i];
823                         msginfo->references = references_list_append(msginfo->references, 
824                                         cur_ref);
825                         i++;
826                 }
827                 g_strfreev(ref_tokens);
828                 
829                 tmp = g_strdup(item->ovr_references);
830                 eliminate_parenthesis(tmp, '(', ')');
831                 if ((p = strrchr(tmp, '<')) != NULL) {
832                         extract_parenthesis(p, '<', '>');
833                         remove_space(p);
834                         if (*p != '\0')
835                                 msginfo->inreplyto = g_strdup(p);
836                 }
837                 g_free(tmp);
838         } 
839
840         return msginfo;
841 }
842
843 static gchar *news_parse_xhdr(clist *hdrlist, MsgInfo *msginfo)
844 {
845         struct newsnntp_xhdr_resp_item *hdr;
846         
847         hdr = clist_content(clist_begin(hdrlist));
848         if (hdr->hdr_article != msginfo->msgnum)
849                 return NULL;
850         return g_strdup(hdr->hdr_value);
851 }
852
853 gint news_cancel_article(Folder * folder, MsgInfo * msginfo)
854 {
855         gchar * tmp;
856         FILE * tmpfp;
857         gchar buf[BUFFSIZE];
858
859         tmp = g_strdup_printf("%s%ccancel%p", get_tmp_dir(),
860                               G_DIR_SEPARATOR, msginfo);
861         if (tmp == NULL)
862                 return -1;
863
864         if ((tmpfp = g_fopen(tmp, "wb")) == NULL) {
865                 FILE_OP_ERROR(tmp, "fopen");
866                 return -1;
867         }
868         if (change_file_mode_rw(tmpfp, tmp) < 0) {
869                 FILE_OP_ERROR(tmp, "chmod");
870                 g_warning("can't change file mode\n");
871         }
872         
873         get_rfc822_date(buf, sizeof(buf));
874         if (fprintf(tmpfp, "From: %s\r\n"
875                        "Newsgroups: %s\r\n"
876                        "Subject: cmsg cancel <%s>\r\n"
877                        "Control: cancel <%s>\r\n"
878                        "Approved: %s\r\n"
879                        "X-Cancelled-by: %s\r\n"
880                        "Date: %s\r\n"
881                        "\r\n"
882                        "removed with Claws Mail\r\n",
883                        msginfo->from,
884                        msginfo->newsgroups,
885                        msginfo->msgid,
886                        msginfo->msgid,
887                        msginfo->from,
888                        msginfo->from,
889                        buf) < 0) {
890                 FILE_OP_ERROR(tmp, "fprintf");
891                 fclose(tmpfp);
892                 claws_unlink(tmp);
893                 g_free(tmp);
894                 return -1;
895         }
896
897         if (fclose(tmpfp) == EOF) {
898                 FILE_OP_ERROR(tmp, "fclose");
899                 claws_unlink(tmp);
900                 g_free(tmp);
901                 return -1;
902         }
903
904         news_post(folder, tmp);
905         remove(tmp);
906
907         g_free(tmp);
908
909         return 0;
910 }
911
912 static gchar *news_folder_get_path(Folder *folder)
913 {
914         gchar *folder_path;
915
916         g_return_val_if_fail(folder->account != NULL, NULL);
917
918         folder_path = g_strconcat(get_news_cache_dir(),
919                                   G_DIR_SEPARATOR_S,
920                                   folder->account->nntp_server,
921                                   NULL);
922         return folder_path;
923 }
924
925 static gchar *news_item_get_path(Folder *folder, FolderItem *item)
926 {
927         gchar *folder_path, *path;
928
929         g_return_val_if_fail(folder != NULL, NULL);
930         g_return_val_if_fail(item != NULL, NULL);
931         folder_path = news_folder_get_path(folder);
932
933         g_return_val_if_fail(folder_path != NULL, NULL);
934         if (folder_path[0] == G_DIR_SEPARATOR) {
935                 if (item->path)
936                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
937                                            item->path, NULL);
938                 else
939                         path = g_strdup(folder_path);
940         } else {
941                 if (item->path)
942                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
943                                            folder_path, G_DIR_SEPARATOR_S,
944                                            item->path, NULL);
945                 else
946                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
947                                            folder_path, NULL);
948         }
949         g_free(folder_path);
950
951         return path;
952 }
953
954 static gint news_get_num_list(Folder *folder, FolderItem *item, GSList **msgnum_list, gboolean *old_uids_valid)
955 {
956         NewsSession *session;
957         gint i, ok, num, first, last, nummsgs = 0;
958         gchar *dir;
959
960         g_return_val_if_fail(item != NULL, -1);
961         g_return_val_if_fail(item->folder != NULL, -1);
962         g_return_val_if_fail(FOLDER_CLASS(folder) == &news_class, -1);
963
964         session = news_session_get(folder);
965         g_return_val_if_fail(session != NULL, -1);
966
967         *old_uids_valid = TRUE;
968         
969         news_folder_lock(NEWS_FOLDER(item->folder));
970
971         ok = news_select_group(folder, item->path, &num, &first, &last);
972         if (ok != NEWSNNTP_NO_ERROR) {
973                 log_warning(LOG_PROTOCOL, _("couldn't set group: %s\n"), item->path);
974                 news_folder_unlock(NEWS_FOLDER(item->folder));
975                 return -1;
976         }
977
978         dir = news_folder_get_path(folder);
979         if (num <= 0)
980                 remove_all_numbered_files(dir);
981         else if (last < first)
982                 log_warning(LOG_PROTOCOL, _("invalid article range: %d - %d\n"),
983                             first, last);
984         else {
985                 for (i = first; i <= last; i++) {
986                         *msgnum_list = g_slist_prepend(*msgnum_list, 
987                                                        GINT_TO_POINTER(i));
988                         nummsgs++;
989                 }
990                 debug_print("removing old messages from %d to %d in %s\n",
991                             first, last, dir);
992                 remove_numbered_files(dir, 1, first - 1);
993         }
994         g_free(dir);
995         news_folder_unlock(NEWS_FOLDER(item->folder));
996         return nummsgs;
997 }
998
999 static void news_set_msg_flags(FolderItem *item, MsgInfo *msginfo)
1000 {
1001         msginfo->flags.tmp_flags = 0;
1002         if (item->folder->account->mark_crosspost_read && msginfo->msgid) {
1003                 if (item->folder->newsart &&
1004                     g_hash_table_lookup(item->folder->newsart, msginfo->msgid) != NULL) {
1005                         msginfo->flags.perm_flags = MSG_COLORLABEL_TO_FLAGS(item->folder->account->crosspost_col);
1006                                 
1007                 } else {
1008                         if (!item->folder->newsart) 
1009                                 item->folder->newsart = g_hash_table_new(g_str_hash, g_str_equal);
1010                         g_hash_table_insert(item->folder->newsart,
1011                                         g_strdup(msginfo->msgid), GINT_TO_POINTER(1));
1012                         msginfo->flags.perm_flags = MSG_NEW|MSG_UNREAD;
1013                 }
1014         } else {
1015                 msginfo->flags.perm_flags = MSG_NEW|MSG_UNREAD;
1016         }
1017 }
1018
1019 static MsgInfo *news_get_msginfo(Folder *folder, FolderItem *item, gint num)
1020 {
1021         NewsSession *session;
1022         MsgInfo *msginfo = NULL;
1023         gint ok;
1024         struct newsnntp_xover_resp_item *result = NULL;
1025         clist *hdrlist = NULL;
1026
1027         session = news_session_get(folder);
1028         g_return_val_if_fail(session != NULL, NULL);
1029         g_return_val_if_fail(item != NULL, NULL);
1030         g_return_val_if_fail(item->folder != NULL, NULL);
1031         g_return_val_if_fail(FOLDER_CLASS(item->folder) == &news_class, NULL);
1032
1033         log_message(LOG_PROTOCOL, _("getting xover %d in %s...\n"),
1034                     num, item->path);
1035         news_folder_lock(NEWS_FOLDER(item->folder));
1036
1037         ok = nntp_threaded_xover(folder, num, num, &result, NULL);
1038         if (ok != NEWSNNTP_NO_ERROR) {
1039                 log_warning(LOG_PROTOCOL, _("couldn't get xover\n"));
1040                 if (ok == NEWSNNTP_ERROR_STREAM) {
1041                         session_destroy(SESSION(session));
1042                         REMOTE_FOLDER(item->folder)->session = NULL;
1043                 }
1044                 news_folder_unlock(NEWS_FOLDER(item->folder));
1045                 return NULL;
1046         }
1047         
1048         msginfo = news_parse_xover(result);
1049         xover_resp_item_free(result);
1050         if (!msginfo) {
1051                 log_warning(LOG_PROTOCOL, _("invalid xover line\n"));
1052         }
1053
1054         if(!msginfo) {
1055                 news_folder_unlock(NEWS_FOLDER(item->folder));
1056                 return NULL;
1057         }
1058
1059         msginfo->folder = item;
1060         
1061         news_set_msg_flags(item, msginfo);
1062         msginfo->flags.tmp_flags |= MSG_NEWS;
1063         msginfo->newsgroups = g_strdup(item->path);
1064
1065         ok = nntp_threaded_xhdr(folder, "to", num, num, &hdrlist);
1066         
1067         if (ok != NEWSNNTP_NO_ERROR) {
1068                 log_warning(LOG_PROTOCOL, _("couldn't get xhdr\n"));
1069                 if (ok == NEWSNNTP_ERROR_STREAM) {
1070                         session_destroy(SESSION(session));
1071                         REMOTE_FOLDER(item->folder)->session = NULL;
1072                 }
1073                 news_folder_unlock(NEWS_FOLDER(item->folder));
1074                 return msginfo;
1075         }
1076
1077         msginfo->to = news_parse_xhdr(hdrlist, msginfo);
1078         newsnntp_xhdr_free(hdrlist);
1079
1080         ok = nntp_threaded_xhdr(folder, "cc", num, num, &hdrlist);
1081         
1082         if (ok != NEWSNNTP_NO_ERROR) {
1083                 log_warning(LOG_PROTOCOL, _("couldn't get xhdr\n"));
1084                 if (ok == NEWSNNTP_ERROR_STREAM) {
1085                         session_destroy(SESSION(session));
1086                         REMOTE_FOLDER(item->folder)->session = NULL;
1087                 }
1088                 news_folder_unlock(NEWS_FOLDER(item->folder));
1089                 return msginfo;
1090         }
1091
1092         msginfo->cc = news_parse_xhdr(hdrlist, msginfo);
1093         newsnntp_xhdr_free(hdrlist);
1094
1095         news_folder_unlock(NEWS_FOLDER(item->folder));
1096         return msginfo;
1097 }
1098
1099 static GSList *news_get_msginfos_for_range(NewsSession *session, FolderItem *item, guint begin, guint end)
1100 {
1101         GSList *newlist = NULL;
1102         GSList *llast = NULL;
1103         MsgInfo *msginfo;
1104         gint ok;
1105         clist *msglist = NULL;
1106         clistiter *cur;
1107         g_return_val_if_fail(session != NULL, NULL);
1108         g_return_val_if_fail(item != NULL, NULL);
1109
1110         log_message(LOG_PROTOCOL, _("getting xover %d - %d in %s...\n"),
1111                     begin, end, item->path);
1112
1113         news_folder_lock(NEWS_FOLDER(item->folder));
1114         
1115         ok = nntp_threaded_xover(item->folder, begin, end, NULL, &msglist);
1116         
1117         if (ok != NEWSNNTP_NO_ERROR) {
1118                 log_warning(LOG_PROTOCOL, _("couldn't get xover\n"));
1119                 if (ok == NEWSNNTP_ERROR_STREAM) {
1120                         session_destroy(SESSION(session));
1121                         REMOTE_FOLDER(item->folder)->session = NULL;
1122                 }
1123                 news_folder_unlock(NEWS_FOLDER(item->folder));
1124                 return NULL;
1125         }
1126
1127         for (cur = clist_begin(msglist); cur; cur = clist_next(cur)) {
1128                 struct newsnntp_xover_resp_item *ritem = (struct newsnntp_xover_resp_item *)clist_content(cur);
1129                 msginfo = news_parse_xover(ritem);
1130                 
1131                 if (!msginfo) {
1132                         log_warning(LOG_PROTOCOL, _("invalid xover line\n"));
1133                         continue;
1134                 }
1135
1136                 msginfo->folder = item;
1137                 news_set_msg_flags(item, msginfo);
1138                 msginfo->flags.tmp_flags |= MSG_NEWS;
1139                 msginfo->newsgroups = g_strdup(item->path);
1140
1141                 if (!newlist)
1142                         llast = newlist = g_slist_append(newlist, msginfo);
1143                 else {
1144                         llast = g_slist_append(llast, msginfo);
1145                         llast = llast->next;
1146                 }
1147         }
1148         newsnntp_xover_resp_list_free(msglist);
1149
1150         news_folder_unlock(NEWS_FOLDER(item->folder));
1151
1152         session_set_access_time(SESSION(session));
1153
1154         return newlist;
1155 }
1156
1157 static GSList *news_get_msginfos(Folder *folder, FolderItem *item, GSList *msgnum_list)
1158 {
1159         NewsSession *session;
1160         GSList *elem, *msginfo_list = NULL, *tmp_msgnum_list, *tmp_msginfo_list;
1161         guint first, last, next;
1162         guint tofetch, fetched;
1163         
1164         g_return_val_if_fail(folder != NULL, NULL);
1165         g_return_val_if_fail(FOLDER_CLASS(folder) == &news_class, NULL);
1166         g_return_val_if_fail(msgnum_list != NULL, NULL);
1167         g_return_val_if_fail(item != NULL, NULL);
1168         
1169         session = news_session_get(folder);
1170         g_return_val_if_fail(session != NULL, NULL);
1171
1172         tmp_msgnum_list = g_slist_copy(msgnum_list);
1173         tmp_msgnum_list = g_slist_sort(tmp_msgnum_list, g_int_compare);
1174
1175         progressindicator_start(PROGRESS_TYPE_NETWORK);
1176         tofetch = g_slist_length(tmp_msgnum_list);
1177         fetched = 0;
1178
1179         first = GPOINTER_TO_INT(tmp_msgnum_list->data);
1180         last = first;
1181         
1182         news_folder_lock(NEWS_FOLDER(item->folder));
1183         
1184         for(elem = g_slist_next(tmp_msgnum_list); elem != NULL; elem = g_slist_next(elem)) {
1185                 next = GPOINTER_TO_INT(elem->data);
1186                 if(next != (last + 1)) {
1187 /*                      session->fetch_base_percentage = ((gfloat) fetched) / ((gfloat) tofetch);
1188                         session->fetch_total_percentage = ((gfloat) (last - first + 1)) / ((gfloat) tofetch);
1189 */
1190                         tmp_msginfo_list = news_get_msginfos_for_range(session, item, first, last);
1191                         msginfo_list = g_slist_concat(msginfo_list, tmp_msginfo_list);
1192                         fetched = last - first + 1;
1193                         first = next;
1194                 }
1195                 last = next;
1196         }
1197         
1198         news_folder_unlock(NEWS_FOLDER(item->folder));
1199         
1200 /*      session->fetch_base_percentage = ((gfloat) fetched) / ((gfloat) tofetch);
1201         session->fetch_total_percentage = ((gfloat) (last - first + 1)) / ((gfloat) tofetch);
1202 */
1203         tmp_msginfo_list = news_get_msginfos_for_range(session, item, first, last);
1204         msginfo_list = g_slist_concat(msginfo_list, tmp_msginfo_list);
1205
1206         g_slist_free(tmp_msgnum_list);
1207         
1208         progressindicator_stop(PROGRESS_TYPE_NETWORK);
1209
1210         return msginfo_list;
1211 }
1212
1213 static gboolean news_scan_required(Folder *folder, FolderItem *item)
1214 {
1215         return TRUE;
1216 }
1217
1218 void news_synchronise(FolderItem *item, gint days) 
1219 {
1220         news_gtk_synchronise(item, days);
1221 }
1222
1223 static gint news_rename_folder(Folder *folder, FolderItem *item,
1224                                 const gchar *name)
1225 {
1226         gchar *path;
1227          
1228         g_return_val_if_fail(folder != NULL, -1);
1229         g_return_val_if_fail(item != NULL, -1);
1230         g_return_val_if_fail(item->path != NULL, -1);
1231         g_return_val_if_fail(name != NULL, -1);
1232
1233         path = folder_item_get_path(item);
1234         if (!is_dir_exist(path))
1235                 make_dir_hier(path);
1236
1237         g_free(item->name);
1238         item->name = g_strdup(name);
1239
1240         return 0;
1241 }
1242
1243 static gint news_remove_folder(Folder *folder, FolderItem *item)
1244 {
1245         gchar *path;
1246
1247         g_return_val_if_fail(folder != NULL, -1);
1248         g_return_val_if_fail(item != NULL, -1);
1249         g_return_val_if_fail(item->path != NULL, -1);
1250
1251         path = folder_item_get_path(item);
1252         if (remove_dir_recursive(path) < 0) {
1253                 g_warning("can't remove directory `%s'\n", path);
1254                 g_free(path);
1255                 return -1;
1256         }
1257
1258         g_free(path);
1259         folder_item_remove(item);
1260         return 0;
1261 }
1262
1263 #else
1264 #include <glib.h>
1265 #include <glib/gi18n.h>
1266 #include <gtk/gtk.h>
1267 #include "folder.h"
1268 #include "alertpanel.h"
1269
1270 static FolderClass news_class;
1271
1272 static void warn_etpan(void)
1273 {
1274         static gboolean missing_news_warning = TRUE;
1275         if (missing_news_warning) {
1276                 missing_news_warning = FALSE;
1277                 alertpanel_error(
1278                         _("You have one or more News accounts "
1279                           "defined. However this version of "
1280                           "Claws Mail has been built without "
1281                           "News support; your News account(s) are "
1282                           "disabled.\n\n"
1283                           "You probably need to "
1284                           "install libetpan and recompile "
1285                           "Claws Mail."));
1286         }
1287 }
1288 static Folder *news_folder_new(const gchar *name, const gchar *path)
1289 {
1290         warn_etpan();
1291         return NULL;
1292 }
1293 void news_group_list_free(GSList *group_list)
1294 {
1295         warn_etpan();
1296 }
1297 void news_remove_group_list_cache(Folder *folder)
1298 {
1299         warn_etpan();
1300 }
1301 int news_folder_locked(Folder *folder)
1302 {
1303         warn_etpan();
1304         return 0;
1305 }
1306 gint news_post(Folder *folder, const gchar *file)
1307 {
1308         warn_etpan();
1309         return -1;
1310 }
1311
1312 gint news_cancel_article(Folder * folder, MsgInfo * msginfo)
1313 {
1314         warn_etpan();
1315         return -1;
1316 }
1317
1318 GSList *news_get_group_list(Folder *folder)
1319 {
1320         warn_etpan();
1321         return NULL;
1322 }
1323
1324
1325 FolderClass *news_get_class(void)
1326 {
1327         if (news_class.idstr == NULL) {
1328                 news_class.type = F_NEWS;
1329                 news_class.idstr = "news";
1330                 news_class.uistr = "News";
1331
1332                 /* Folder functions */
1333                 news_class.new_folder = news_folder_new;
1334         };
1335
1336         return &news_class;
1337 }
1338
1339
1340 #endif