e1806bf66a6915e10511d91c7fd405f5d7464dcb
[claws.git] / src / filtering.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 Hiroyuki Yamamoto & The Sylpheed Claws 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 2 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, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 /* 
21  * initital     Hoa             initial
22  * 07/16/01     Alfons          fix bugs
23  * 07/18/01     Alfons          rewrite things
24  */
25
26 /* 07/18/01 (alfons) 
27  * 
28  * filter_message() is no longer the entry point for filtering. it's
29  * replaced with filter_incoming_message() which does not trust
30  * on MsgInfo's from a folder. instead it directly works with
31  * the temporary file.  
32  * updating the mark file is a lot easier now, because we can do that
33  * right after a call to folder_item_add_msg(). 
34  */ 
35
36 #include <ctype.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <errno.h>
40 #include <gtk/gtk.h>
41 #include <stdio.h>
42 #include "intl.h"
43 #include "utils.h"
44 #include "defs.h"
45 #include "procheader.h"
46 #include "matcher.h"
47 #include "filtering.h"
48 #include "prefs.h"
49 #include "compose.h"
50
51 #define PREFSBUFSIZE            1024
52
53 GSList * prefs_filtering = NULL;
54
55 FilteringAction * filteringaction_new(int type, int account_id,
56                                       gchar * destination)
57 {
58         FilteringAction * action;
59
60         action = g_new0(FilteringAction, 1);
61
62         action->type = type;
63         action->account_id = account_id;
64         if (destination)
65                 action->destination = g_strdup(destination);
66
67         return action;
68 }
69
70 void filteringaction_free(FilteringAction * action)
71 {
72         if (action->destination)
73                 g_free(action->destination);
74         g_free(action);
75 }
76
77 FilteringAction * filteringaction_parse(gchar ** str)
78 {
79         FilteringAction * action;
80         gchar * tmp;
81         gchar * destination = NULL;
82         gint account_id = 0;
83         gint key;
84
85         tmp = * str;
86
87         key = matcher_parse_keyword(&tmp);
88
89         switch (key) {
90         case MATCHING_ACTION_MOVE:
91         case MATCHING_ACTION_COPY:
92         case MATCHING_EXECUTE:
93                 destination = matcher_parse_str(&tmp);
94                 if (tmp == NULL) {
95                         * str = NULL;
96                         return NULL;
97                 }
98                 break;
99         case MATCHING_ACTION_DELETE:
100                 break;
101         case MATCHING_ACTION_MARK:
102                 break;
103         case MATCHING_ACTION_MARK_AS_READ:
104                 break;
105         case MATCHING_ACTION_UNMARK:
106                 break;
107         case MATCHING_ACTION_MARK_AS_UNREAD:
108                 break;
109         case MATCHING_ACTION_FORWARD:
110         case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
111                 account_id = matcher_parse_number(&tmp);
112                 if (tmp == NULL) {
113                         * str = NULL;
114                         return NULL;
115                 }
116
117                 destination = matcher_parse_str(&tmp);
118                 if (tmp == NULL) {
119                         * str = NULL;
120                         return NULL;
121                 }
122
123                 break;
124         default:
125                 * str = NULL;
126                 return NULL;
127         }
128
129         * str = tmp;
130         action = filteringaction_new(key, account_id, destination);
131
132         return action;
133 }
134
135 FilteringProp * filteringprop_parse(gchar ** str)
136 {
137         gchar * tmp;
138         gint key;
139         FilteringProp * filtering;
140         MatcherList * matchers;
141         FilteringAction * action;
142         
143         tmp = * str;
144
145         matchers = matcherlist_parse(&tmp);
146         if (tmp == NULL) {
147                 * str = NULL;
148                 return NULL;
149         }
150
151         if (tmp == NULL) {
152                 matcherlist_free(matchers);
153                 * str = NULL;
154                 return NULL;
155         }
156
157         action = filteringaction_parse(&tmp);
158         if (tmp == NULL) {
159                 matcherlist_free(matchers);
160                 * str = NULL;
161                 return NULL;
162         }
163
164         filtering = filteringprop_new(matchers, action);
165
166         * str = tmp;
167         return filtering;
168 }
169
170
171 FilteringProp * filteringprop_new(MatcherList * matchers,
172                                   FilteringAction * action)
173 {
174         FilteringProp * filtering;
175
176         filtering = g_new0(FilteringProp, 1);
177         filtering->matchers = matchers;
178         filtering->action = action;
179
180         return filtering;
181 }
182
183 void filteringprop_free(FilteringProp * prop)
184 {
185         matcherlist_free(prop->matchers);
186         filteringaction_free(prop->action);
187         g_free(prop);
188 }
189
190 /* filteringaction_update_mark() - updates a mark for a message. note that
191  * the message should not have been moved or copied. remember that the
192  * procmsg_open_mark_file(PATH, TRUE) actually _appends_ a new record.
193  */
194 static gboolean filteringaction_update_mark(MsgInfo * info)
195 {
196         gchar * dest_path;
197         FILE * fp;
198
199         if (info->folder->folder->type == F_MH) {
200                 dest_path = folder_item_get_path(info->folder);
201                 if (!is_dir_exist(dest_path))
202                         make_dir_hier(dest_path);
203                 
204                 if (dest_path == NULL) {
205                         g_warning(_("Can't open mark file.\n"));
206                         return FALSE;
207                 }
208                 
209                 if ((fp = procmsg_open_mark_file(dest_path, TRUE))
210                     == NULL) {
211                         g_warning(_("Can't open mark file.\n"));
212                         return FALSE;
213                 }
214                 
215                 procmsg_write_flags(info, fp);
216                 fclose(fp);
217                 return TRUE;
218         }
219         return FALSE;
220 }
221
222 static inline gint strlen_with_check(const gchar *expr, gint fline, const gchar *str)
223 {
224         if (str) 
225                 return strlen(str);
226         else {
227                 debug_print("%s(%d) - invalid string %s\n", __FILE__, fline, expr);
228                 return 0;
229         }
230 }
231
232 #define STRLEN_WITH_CHECK(expr) \
233         strlen_with_check(#expr, __LINE__, expr)
234         
235 static gchar * filteringaction_execute_command(gchar * cmd, MsgInfo * info)
236 {
237         gchar * s = cmd;
238         gchar * filename = NULL;
239         gchar * processed_cmd;
240         gchar * p;
241         gint size;
242
243         size = strlen(cmd) + 1;
244         while (*s != '\0') {
245                 if (*s == '%') {
246                         s++;
247                         switch (*s) {
248                         case '%':
249                                 size -= 1;
250                                 break;
251                         case 's': /* subject */
252                                 size += STRLEN_WITH_CHECK(info->subject) - 2;
253                                 break;
254                         case 'f': /* from */
255                                 size += STRLEN_WITH_CHECK(info->from) - 2;
256                                 break;
257                         case 't': /* to */
258                                 size += STRLEN_WITH_CHECK(info->to) - 2;
259                                 break;
260                         case 'c': /* cc */
261                                 size += STRLEN_WITH_CHECK(info->cc) - 2;
262                                 break;
263                         case 'd': /* date */
264                                 size += STRLEN_WITH_CHECK(info->date) - 2;
265                                 break;
266                         case 'i': /* message-id */
267                                 size += STRLEN_WITH_CHECK(info->msgid) - 2;
268                                 break;
269                         case 'n': /* newsgroups */
270                                 size += STRLEN_WITH_CHECK(info->newsgroups) - 2;
271                                 break;
272                         case 'r': /* references */
273                                 size += STRLEN_WITH_CHECK(info->references) - 2;
274                                 break;
275                         case 'F': /* file */
276                                 if (MSG_IS_FILTERING(info->flags))
277                                         filename = g_strdup(info->folder);
278                                 else
279                                         filename = folder_item_fetch_msg(info->folder, info->msgnum);
280                                 
281                                 if (filename == NULL) {
282                                         g_warning(_("filename is not set"));
283                                         return NULL;
284                                 }
285                                 else
286                                         size += strlen(filename) - 2;
287                                 break;
288                         }
289                         s++;
290                 }
291                 else s++;
292         }
293
294
295         processed_cmd = g_new0(gchar, size);
296         s = cmd;
297         p = processed_cmd;
298
299         while (*s != '\0') {
300                 if (*s == '%') {
301                         s++;
302                         switch (*s) {
303                         case '%':
304                                 *p = '%';
305                                 p++;
306                                 break;
307                         case 's': /* subject */
308                                 if (info->subject != NULL)
309                                         strcpy(p, info->subject);
310                                 else
311                                         strcpy(p, "(none)");
312                                 p += strlen(p);
313                                 break;
314                         case 'f': /* from */
315                                 if (info->from != NULL)
316                                         strcpy(p, info->from);
317                                 else
318                                         strcpy(p, "(none)");
319                                 p += strlen(p);
320                                 break;
321                         case 't': /* to */
322                                 if (info->to != NULL)
323                                         strcpy(p, info->to);
324                                 else
325                                         strcpy(p, "(none)");
326                                 p += strlen(p);
327                                 break;
328                         case 'c': /* cc */
329                                 if (info->cc != NULL)
330                                         strcpy(p, info->cc);
331                                 else
332                                         strcpy(p, "(none)");
333                                 p += strlen(p);
334                                 break;
335                         case 'd': /* date */
336                                 if (info->date != NULL)
337                                         strcpy(p, info->date);
338                                 else
339                                         strcpy(p, "(none)");
340                                 p += strlen(p);
341                                 break;
342                         case 'i': /* message-id */
343                                 if (info->msgid != NULL)
344                                         strcpy(p, info->msgid);
345                                 else
346                                         strcpy(p, "(none)");
347                                 p += strlen(p);
348                                 break;
349                         case 'n': /* newsgroups */
350                                 if (info->newsgroups != NULL)
351                                         strcpy(p, info->newsgroups);
352                                 else
353                                         strcpy(p, "(none)");
354                                 p += strlen(p);
355                                 break;
356                         case 'r': /* references */
357                                 if (info->references != NULL)
358                                         strcpy(p, info->references);
359                                 else
360                                         strcpy(p, "(none)");
361                                 p += strlen(p);
362                                 break;
363                         case 'F': /* file */
364                                 strcpy(p, filename);
365                                 p += strlen(p);
366                                 break;
367                         default:
368                                 *p = '%';
369                                 p++;
370                                 *p = *s;
371                                 p++;
372                                 break;
373                         }
374                         s++;
375                 }
376                 else {
377                         *p = *s;
378                         p++;
379                         s++;
380                 }
381         }
382
383         g_free(filename);
384         return processed_cmd;
385 }
386
387 /*
388   fitleringaction_apply
389   runs the action on one MsgInfo
390   return value : return TRUE if the action could be applied
391 */
392
393 #define CHANGE_FLAGS(msginfo) \
394 { \
395 if (msginfo->folder->folder->change_flags != NULL) \
396 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
397                                       msginfo->folder, \
398                                       msginfo); \
399 }
400
401 static gboolean filteringaction_apply(FilteringAction * action, MsgInfo * info,
402                                       GHashTable *folder_table)
403 {
404         FolderItem * dest_folder;
405         gint val;
406         Compose * compose;
407         PrefsAccount * account;
408         gchar * cmd;
409
410         switch(action->type) {
411         case MATCHING_ACTION_MOVE:
412                 dest_folder =
413                         folder_find_item_from_identifier(action->destination);
414                 if (!dest_folder)
415                         return FALSE;
416
417                 if (folder_item_move_msg(dest_folder, info) == -1)
418                         return FALSE;
419
420                 /* WRONG: can not update the mark, because the message has 
421                  * been moved. info pertains to original location. 
422                  * folder_item_move_msg() already updated the mark for the
423                  * destination folder.
424                 info->flags = 0;
425                 filteringaction_update_mark(info);
426                  */
427                 if (folder_table) {
428                         val = GPOINTER_TO_INT(g_hash_table_lookup
429                                               (folder_table, dest_folder));
430                         if (val == 0) {
431                                 folder_item_scan(dest_folder);
432                                 g_hash_table_insert(folder_table, dest_folder,
433                                                     GINT_TO_POINTER(1));
434                         }
435                         val = GPOINTER_TO_INT(g_hash_table_lookup
436                                               (folder_table, info->folder));
437                         if (val == 0) {
438                                 folder_item_scan(info->folder);
439                                 g_hash_table_insert(folder_table, info->folder,
440                                                     GINT_TO_POINTER(1));
441                         }
442                 }
443                 return TRUE;
444
445         case MATCHING_ACTION_COPY:
446                 dest_folder =
447                         folder_find_item_from_identifier(action->destination);
448
449                 if (!dest_folder)
450                         return FALSE;
451
452                 /* NOTE: the following call *will* update the mark file for
453                  * the destination folder. but the original message will
454                  * still be there in the inbox. */
455
456                 if (folder_item_copy_msg(dest_folder, info) == -1)
457                         return FALSE;
458
459                 if (folder_table) {
460                         val = GPOINTER_TO_INT(g_hash_table_lookup
461                                               (folder_table, dest_folder));
462                         if (val == 0) {
463                                 folder_item_scan(dest_folder);
464                                 g_hash_table_insert(folder_table, dest_folder,
465                                                     GINT_TO_POINTER(1));
466                         }
467                 }
468                         
469                 return TRUE;
470
471         case MATCHING_ACTION_DELETE:
472                 if (folder_item_remove_msg(info->folder, info->msgnum) == -1)
473                         return FALSE;
474
475                 /* WRONG: can not update the mark. this would actually add
476                  * a bogus record to the mark file for the message's original 
477                  * folder. 
478                 info->flags = 0;
479                 filteringaction_update_mark(info);
480                  */
481
482                 return TRUE;
483
484         case MATCHING_ACTION_MARK:
485                 MSG_SET_PERM_FLAGS(info->flags, MSG_MARKED);
486                 debug_print("*** MARKING message %d, in folder %s, \"%s\"\n",
487                             info->msgnum, info->folder->name,
488                             info->subject ? info->subject : "<none>");
489                 filteringaction_update_mark(info);
490
491                 CHANGE_FLAGS(info);
492
493                 return TRUE;
494
495         case MATCHING_ACTION_UNMARK:
496                 MSG_UNSET_PERM_FLAGS(info->flags, MSG_MARKED);
497                 filteringaction_update_mark(info);
498
499                 CHANGE_FLAGS(info);
500
501                 return TRUE;
502                 
503         case MATCHING_ACTION_MARK_AS_READ:
504                 MSG_UNSET_PERM_FLAGS(info->flags, MSG_UNREAD | MSG_NEW);
505                 filteringaction_update_mark(info);
506
507                 CHANGE_FLAGS(info);
508
509                 return TRUE;
510
511         case MATCHING_ACTION_MARK_AS_UNREAD:
512                 MSG_SET_PERM_FLAGS(info->flags, MSG_UNREAD | MSG_NEW);
513                 filteringaction_update_mark(info);
514
515                 CHANGE_FLAGS(info);
516                 
517                 return TRUE;
518
519         case MATCHING_ACTION_FORWARD:
520
521                 account = account_find_from_id(action->account_id);
522                 compose = compose_forward(account, info, FALSE);
523                 if (compose->account->protocol == A_NNTP)
524                         compose_entry_append(compose, action->destination,
525                                              COMPOSE_NEWSGROUPS);
526                 else
527                         compose_entry_append(compose, action->destination,
528                                              COMPOSE_TO);
529
530                 val = compose_send(compose);
531                 if (val == 0) {
532                         gtk_widget_destroy(compose->window);
533                         return TRUE;
534                 }
535
536                 gtk_widget_destroy(compose->window);
537                 return FALSE;
538
539         case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
540
541                 account = account_find_from_id(action->account_id);
542                 compose = compose_forward(account, info, TRUE);
543                 if (compose->account->protocol == A_NNTP)
544                         compose_entry_append(compose, action->destination,
545                                              COMPOSE_NEWSGROUPS);
546                 else
547                         compose_entry_append(compose, action->destination,
548                                              COMPOSE_TO);
549
550                 val = compose_send(compose);
551                 if (val == 0) {
552                         gtk_widget_destroy(compose->window);
553                         return TRUE;
554                 }
555
556                 gtk_widget_destroy(compose->window);
557                 return FALSE;
558
559         case MATCHING_EXECUTE:
560
561                 cmd = matching_build_command(action->destination, info);
562                 if (cmd == NULL)
563                         return TRUE;
564                 else {
565                         system(cmd);
566                         g_free(cmd);
567                 }
568
569                 return TRUE;
570
571         default:
572                 return FALSE;
573         }
574 }
575
576 /* filteringprop_apply() - runs the action on one MsgInfo if it matches the 
577  * criterium. certain actions can be followed by other actions. in this
578  * case the function returns FALSE. if an action can not be followed
579  * by others, the function returns TRUE.
580  *
581  * remember that this is because of the fact that msg flags are always
582  * _appended_ to mark files. currently sylpheed does not insert messages 
583  * at a certain index. 
584  * now, after having performed a certain action, the MsgInfo is still
585  * valid for the message. in *this* case the function returns FALSE.
586  */
587 static gboolean filteringprop_apply(FilteringProp * filtering, MsgInfo * info,
588                                     GHashTable *folder_table)
589 {
590         if (matcherlist_match(filtering->matchers, info)) {
591                 gint result;
592                 gchar * action_str;
593
594                 result = TRUE;
595
596                 result = filteringaction_apply(filtering->action, info,
597                                                folder_table);
598                 action_str =
599                         filteringaction_to_string(filtering->action);
600                 if (!result) {
601                         g_warning(_("action %s could not be applied"),
602                                   action_str);
603                 }
604                 else {
605                         debug_print(_("message %i %s..."),
606                                       info->msgnum, action_str);
607                 }
608
609                 g_free(action_str);
610
611                 switch(filtering->action->type) {
612                 case MATCHING_ACTION_MOVE:
613                 case MATCHING_ACTION_DELETE:
614                         return TRUE; /* MsgInfo invalid for message */
615                 case MATCHING_EXECUTE:
616                 case MATCHING_ACTION_COPY:
617                 case MATCHING_ACTION_MARK:
618                 case MATCHING_ACTION_MARK_AS_READ:
619                 case MATCHING_ACTION_UNMARK:
620                 case MATCHING_ACTION_MARK_AS_UNREAD:
621                 case MATCHING_ACTION_FORWARD:
622                 case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
623                         return FALSE; /* MsgInfo still valid for message */
624                 default:
625                         return FALSE;
626                 }
627         }
628         else
629                 return FALSE;
630 }
631
632 void filter_msginfo(GSList * filtering_list, MsgInfo * info,
633                     GHashTable *folder_table)
634 {
635         GSList * l;
636
637         if (info == NULL) {
638                 g_warning(_("msginfo is not set"));
639                 return;
640         }
641         
642         for(l = filtering_list ; l != NULL ; l = g_slist_next(l)) {
643                 FilteringProp * filtering = (FilteringProp *) l->data;
644                 
645                 if (filteringprop_apply(filtering, info, folder_table))
646                         break;
647         }
648 }
649
650 void filter_msginfo_move_or_delete(GSList * filtering_list, MsgInfo * info,
651                                    GHashTable *folder_table)
652 {
653         GSList * l;
654
655         if (info == NULL) {
656                 g_warning(_("msginfo is not set"));
657                 return;
658         }
659         
660         for(l = filtering_list ; l != NULL ; l = g_slist_next(l)) {
661                 FilteringProp * filtering = (FilteringProp *) l->data;
662
663                 switch (filtering->action->type) {
664                 case MATCHING_ACTION_MOVE:
665                 case MATCHING_ACTION_DELETE:
666                         if (filteringprop_apply(filtering, info, folder_table))
667                                 return;
668                 }
669         }
670 }
671
672 void filter_message(GSList * filtering_list, FolderItem * item,
673                     gint msgnum, GHashTable *folder_table)
674 {
675         MsgInfo * msginfo;
676         gchar * filename;
677         MsgFlags  msgflags = { 0, 0 };
678
679         if (item == NULL) {
680                 g_warning(_("folderitem not set"));
681                 return;
682         }
683
684         filename = folder_item_fetch_msg(item, msgnum);
685
686         if (filename == NULL) {
687                 g_warning(_("filename is not set"));
688                 return;
689         }
690
691         msginfo = procheader_parse(filename, msgflags, TRUE);
692         
693         g_free(filename);
694
695         if (msginfo == NULL) {
696                 g_warning(_("could not get info for %s"), filename);
697                 return;
698         }
699
700         msginfo->folder = item;
701         msginfo->msgnum = msgnum;
702
703         filter_msginfo(filtering_list, msginfo, folder_table);
704 }
705
706
707 /******************************************************************************/
708
709 /* revised filtering system.  
710  * 
711  * 07/18/01     alfons          initial revisement
712  */
713
714 /* (alfons)
715  * 
716  * the revised filtering system does not rely on a message being "registered"
717  * in one of sylpheed's folders. it now uses the file sylpheed created on
718  * incorporation of mail. 
719  * i do use MsgInfo data; that's needed by the matcher, but for the rest
720  * the MsgInfo is not really used. */
721  
722
723 /* add_mark() - adds a mark for a file */
724 static void add_mark(FolderItem *folder, gint msgnum, MsgPermFlags flags)
725 {
726         gchar * dest_path;
727         FILE * fp;
728
729         if (folder->folder->type == F_MH) {
730                 dest_path = folder_item_get_path(folder);
731                 if (!is_dir_exist(dest_path))
732                         make_dir_hier(dest_path);
733                 
734                 if (dest_path == NULL) {
735                         g_warning(_("Can't open mark file.\n"));
736                         return;
737                 }
738                 
739                 if ((fp = procmsg_open_mark_file(dest_path, TRUE))
740                     == NULL) {
741                         g_warning(_("Can't open mark file.\n"));
742                         return;
743                 }
744
745                 /* TODO: straight from procmsg.c:procmsg_write_flags()
746                  * should update this when mark file version changes */
747 #if MARK_VERSION == 2            
748                 WRITE_CACHE_DATA_INT(msgnum, fp);
749                 WRITE_CACHE_DATA_INT(flags, fp);
750 #else
751 #error should rewrite the above for new  mark version   
752                 /* paste the source code of procmsg.c:procmsg_write_flags() */
753 #endif
754                 fclose(fp);
755                 return;
756         }
757         return;
758 }
759
760 /* prepare_destination() - prepares destination folder by registering it 
761  * in the global folder table (if not already there). it returns TRUE if
762  * successful. it also returns the FolderItem for the destination */
763 static gboolean prepare_destination(const gchar *destination, FolderItem **item, 
764                                     GHashTable *folder_table)
765 {
766         gint val;
767         FolderItem *result;
768
769         result = folder_find_item_from_identifier(destination);
770         if (!result)
771                 return FALSE;
772         if (folder_table) {
773                 *item = result;
774                 val = GPOINTER_TO_INT(g_hash_table_lookup(folder_table, *item));
775                 if (val == 0) {
776                         folder_item_scan(*item);
777                         g_hash_table_insert(folder_table, *item, GINT_TO_POINTER(1));
778                 }
779         }
780         return TRUE;
781 }
782
783 /* filter_incoming_perform_actions() - performs actions on incoming
784  * message. this function handles updating marks a little bit smarter;
785  * remember that marks can only be appended. */
786 static gboolean filter_incoming_perform_actions(FolderItem *default_folder, 
787                                                 MsgInfo    *msginfo,
788                                                 GHashTable *folder_table)
789 {
790         /* matching actions for msginfo */
791         struct matching_action {
792                 FilteringAction         *action;
793                 struct matching_action  *next;
794         };
795
796         struct matching_action  ma_head = { NULL, NULL };
797         struct matching_action *ma_tail = &ma_head;
798
799         /* need this for the forwarding stuff */
800         PrefsAccount *account;
801         Compose      *compose;
802         MsgFlags      tmp;
803         gchar        *fwd_msg_name;
804         gint          val;
805         MsgInfo      *fwd_msg;
806
807         MsgFlags     markflags = { 0, 0 };
808
809         /* use the global prefs_filtering list */
810         GSList *     list = prefs_filtering;
811
812         /* things we get after having added a message to a folder */
813         FolderItem  *dest_folder;
814         gint         msgnum;
815         
816         /* after performing certain action, we may have to copy 
817          * the message to inbox too */
818         gboolean     copy_to_inbox_too = TRUE;
819         
820         /* filename is only put in msginfo->folder if MSG_FILTERING is set. */
821         const gchar *filename = (gchar *) msginfo->folder;
822         
823         MsgPermFlags flags;
824         gboolean     stop;
825         gchar        *cmd;
826
827         /* build list of matching actions */
828         for (; list != NULL; list = g_slist_next(list)) {
829                 FilteringProp *prop = (FilteringProp *) list->data;
830                 
831                 if (!matcherlist_match(prop->matchers, msginfo))
832                         continue;
833
834                 if (NULL == (ma_tail->next = alloca(sizeof(struct matching_action)))) {
835                         debug_print(_("action allocation error\n"));
836                         break;
837                 }
838
839                 debug_print("*** action %d\n", prop->action->type);
840
841                 ma_tail->action = prop->action;
842                 ma_tail->next->action = NULL;
843                 ma_tail->next->next = NULL;
844                 ma_tail = ma_tail->next;
845         }
846
847         debug_print("*** collecting marks\n");          
848         
849         /* collect all marks */
850         for (ma_tail = &ma_head, stop = FALSE; ma_tail->action && !stop; ma_tail = ma_tail->next) {
851                 switch (ma_tail->action->type) {
852                 
853                 case MATCHING_ACTION_MARK:
854                         MSG_SET_PERM_FLAGS(markflags, MSG_MARKED);
855                         break;
856                         
857                 case MATCHING_ACTION_UNMARK:
858                         MSG_UNSET_PERM_FLAGS(markflags, MSG_MARKED);
859                         break;
860                 
861                 case MATCHING_ACTION_MARK_AS_READ:
862                         MSG_UNSET_PERM_FLAGS(markflags, MSG_UNREAD);
863                         break;
864
865                 case MATCHING_ACTION_MARK_AS_UNREAD:                    
866                         MSG_SET_PERM_FLAGS(markflags, MSG_UNREAD);
867                         break;
868
869                 /* UNCONTINUABLE */
870                 case MATCHING_ACTION_FORWARD:
871                 case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
872                 case MATCHING_ACTION_MOVE:
873                 case MATCHING_ACTION_DELETE:
874                         stop = TRUE;
875                         break;
876                 
877                 default:
878                         break;
879                 }
880         }
881
882
883         /* msgnum & dest_folder should have valid values after a succesful
884          * drop; in this case there is a MsgInfo available */
885         msgnum      = -1;
886         dest_folder = NULL;
887
888         debug_print("*** performing actions\n"); 
889         
890         for (ma_tail = &ma_head ; ma_tail->action; ma_tail = ma_tail->next) {
891
892                 /* there are variables you have to use when defining new actions:
893                  *
894                  * copy_to_inbox_too - if the original message should be copied to the inbox 
895                  *                     (default_folder) too.
896                  * 
897                  * also note that after dropping it to a folder (folder_item_add_msg()) you have
898                  * to mark the message, just to make sure any defined mark actions are applied. */
899                  
900 #define ACTION  (ma_tail->action->type) 
901
902                 /* C O N T I N U A B L E */
903
904                 if (MATCHING_ACTION_COPY == ACTION) {
905                         debug_print("*** performing copy\n");
906                         copy_to_inbox_too = TRUE;
907                         if (!prepare_destination(ma_tail->action->destination, &dest_folder, folder_table)) {
908                                 debug_print("Rule failed: unknown destination %s\n", ma_tail->action->destination);
909                                 continue; /* try next action */
910                         }
911                         if (0 > (msgnum = folder_item_add_msg(dest_folder, filename, FALSE))) {
912                                 debug_print(_("Rule failed: could not copy to folder %s\n"),
913                                             ma_tail->action->destination);
914                                 continue; /* try next action */     
915                         }   
916                         flags = msginfo->flags.perm_flags | markflags.perm_flags;
917                         add_mark(dest_folder, msgnum, flags);
918                 }               
919                 else if (MATCHING_EXECUTE == ACTION) {
920                         debug_print("*** performing exec\n");
921                         copy_to_inbox_too = TRUE;
922                         
923                         /* matching_build_command() knows about filtering */
924                         cmd = matching_build_command(ma_tail->action->destination, msginfo);
925                         if (cmd) { 
926                                 system(cmd);
927                                 g_free(cmd);
928                         }
929                         else
930                                 debug_print(_("Rule failed: no command line\n"));
931                 } 
932
933                 /* U N C O N T I N U A B L E */
934                 
935                 else if (MATCHING_ACTION_FORWARD == ACTION
936                 ||       MATCHING_ACTION_FORWARD_AS_ATTACHMENT == ACTION) {
937                         debug_print("*** performing forward\n");
938
939                         /* forwarding messages is complicated because there's currently no 
940                          * way to forward a message using "filenames"; you can only forward
941                          * a message if you have its MsgInfo. this means we have to drop
942                          * the message first */ 
943                         if (0 > (msgnum = folder_item_add_msg(default_folder, filename, FALSE))) {
944                                 debug_print(_("Rule failed: could not forward\n"));
945                                 copy_to_inbox_too = TRUE;
946                                 continue;
947                         }
948                                 
949                         flags = msginfo->flags.perm_flags | markflags.perm_flags;
950                         add_mark(default_folder, msgnum, flags);
951
952                         /* grab the dropped message */
953                         fwd_msg_name = folder_item_fetch_msg(default_folder, msgnum);
954
955                         tmp.perm_flags = tmp.tmp_flags = 0;
956                         fwd_msg = procheader_parse(fwd_msg_name, tmp, TRUE);
957
958                         /* do the compose_XXX stuff */
959                         account = account_find_from_id(ma_tail->action->account_id);
960                         compose = compose_forward(account, fwd_msg, ma_tail->action->type == ACTION ? FALSE : TRUE);
961                         if (compose->account->protocol == A_NNTP)
962                                 compose_entry_append(compose, ma_tail->action->destination,
963                                                      COMPOSE_NEWSGROUPS);
964                         else
965                                 compose_entry_append(compose, ma_tail->action->destination,
966                                                      COMPOSE_TO);
967
968                         compose_send(compose);
969
970                         procmsg_msginfo_free(fwd_msg);
971                         
972                         gtk_widget_destroy(compose->window);
973                         break;
974                 }                       
975                 else if (MATCHING_ACTION_DELETE == ACTION) {
976                         debug_print("*** performing delete\n");
977                         copy_to_inbox_too = FALSE;
978                         if (unlink(filename) < 0)
979                                 debug_print(_("Rule failed: could not delete message\n"));
980                         break;                          
981                 }
982                 else if (MATCHING_ACTION_MOVE == ACTION) {
983                         debug_print("*** performing move\n");
984                         copy_to_inbox_too = FALSE;
985                         
986                         if (!prepare_destination(ma_tail->action->destination, &dest_folder, folder_table)) {
987                                 copy_to_inbox_too = TRUE;
988                                 break;
989                         }
990                                 
991                         msgnum = folder_item_add_msg(dest_folder, filename, FALSE);
992                         if (msgnum < 0) {
993                                 debug_print(_("Rule failed: could not move to folder %s\n"),
994                                             ma_tail->action->destination);
995                                 copy_to_inbox_too = TRUE;                                          
996                                 break;
997                         }   
998                         
999                         flags = msginfo->flags.perm_flags | markflags.perm_flags;
1000                         add_mark(dest_folder, msgnum, flags);
1001                         break;
1002                 }
1003         }
1004
1005         /* may need to copy it to inbox too */
1006         if (copy_to_inbox_too) {
1007                 debug_print("*** performing inbox copy\n");
1008                 msgnum = folder_item_add_msg(default_folder, filename, TRUE);
1009                 if (msgnum < 0) {
1010                         debug_print(_("error copying incoming file %s to inbox\n"), 
1011                                     filename);
1012                         return FALSE;                               
1013                 }
1014                 flags = msginfo->flags.perm_flags | markflags.perm_flags;
1015                 add_mark(default_folder, msgnum, flags);
1016         }
1017         else {
1018                 debug_print("*** unlinking\n");
1019                 if (unlink(filename) < 0) 
1020                         debug_print(_("error deleting incoming message file\n"));
1021         }
1022
1023 #undef ACTION
1024
1025         return TRUE;
1026 }
1027
1028 static void filter_incoming_msginfo(FolderItem *default_folder, MsgInfo *msginfo, 
1029                                     GHashTable *folder_table)
1030 {
1031         filter_incoming_perform_actions(default_folder, msginfo, folder_table); 
1032 }
1033
1034 /* filter_incoming_message() - tries to apply a filter on one incoming message.
1035  * it also handles the case when there's no filter match */
1036 void filter_incoming_message(FolderItem *default_folder, const gchar *file_name, 
1037                              GHashTable *folder_table)
1038 {
1039         MsgInfo *msginfo;
1040         MsgFlags msgflags = { 0, 0 };
1041         
1042         /* make an "uncomplete" msginfo. it's incomplete because it doesn't
1043          * have a message number / folder yet. */
1044         if (NULL == (msginfo = procheader_parse(file_name, msgflags, TRUE))) {
1045                 g_warning(_("error filtering incoming message %s\n"), 
1046                           file_name);
1047                 return;         
1048         }
1049
1050         /* let matcher know that this is a message that has no
1051          * valid body data yet. */
1052         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_FILTERING);
1053         msginfo->folder = g_strdup(file_name);
1054         msginfo->msgnum = 0;
1055
1056         filter_incoming_msginfo(default_folder, msginfo, folder_table);
1057
1058         g_free(msginfo->folder);
1059         procmsg_msginfo_free(msginfo);
1060 }
1061
1062 /******************************************************************************/
1063
1064 void prefs_filtering_read_config(void)
1065 {
1066         gchar *rcpath;
1067         FILE *fp;
1068         gchar buf[PREFSBUFSIZE];
1069
1070         debug_print(_("Reading filtering configuration...\n"));
1071
1072         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1073                              FILTERING_RC, NULL);
1074         if ((fp = fopen(rcpath, "r")) == NULL) {
1075                 if (ENOENT != errno) FILE_OP_ERROR(rcpath, "fopen");
1076                 g_free(rcpath);
1077                 prefs_filtering = NULL;
1078                 return;
1079         }
1080         g_free(rcpath);
1081
1082         /* remove all filtering */
1083         while (prefs_filtering != NULL) {
1084                 FilteringProp * filtering =
1085                         (FilteringProp *) prefs_filtering->data;
1086                 filteringprop_free(filtering);
1087                 prefs_filtering = g_slist_remove(prefs_filtering, filtering);
1088         }
1089
1090         while (fgets(buf, sizeof(buf), fp) != NULL) {
1091                 FilteringProp * filtering;
1092                 gchar * tmp;
1093
1094                 g_strchomp(buf);
1095
1096                 if ((*buf != '#') && (*buf != '\0')) {
1097                         tmp = buf;
1098                         filtering = filteringprop_parse(&tmp);
1099                         if (tmp != NULL) {
1100                                 prefs_filtering =
1101                                         g_slist_append(prefs_filtering,
1102                                                        filtering);
1103                         }
1104                         else {
1105                                 /* debug */
1106                                 g_warning(_("syntax error : %s\n"), buf);
1107                         }
1108                 }
1109         }
1110
1111         fclose(fp);
1112 }
1113
1114 gchar * filteringaction_to_string(FilteringAction * action)
1115 {
1116         gchar * command_str;
1117         gint i;
1118         gchar * account_id_str;
1119
1120         command_str = NULL;
1121         command_str = get_matchparser_tab_str(action->type);
1122
1123         if (command_str == NULL)
1124                 return NULL;
1125
1126         switch(action->type) {
1127         case MATCHING_ACTION_MOVE:
1128         case MATCHING_ACTION_COPY:
1129         case MATCHING_EXECUTE:
1130                 return g_strconcat(command_str, " \"", action->destination,
1131                                    "\"", NULL);
1132
1133         case MATCHING_ACTION_DELETE:
1134         case MATCHING_ACTION_MARK:
1135         case MATCHING_ACTION_UNMARK:
1136         case MATCHING_ACTION_MARK_AS_READ:
1137         case MATCHING_ACTION_MARK_AS_UNREAD:
1138                 return g_strdup(command_str);
1139                 break;
1140
1141         case MATCHING_ACTION_FORWARD:
1142         case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
1143                 account_id_str = itos(action->account_id);
1144                 return g_strconcat(command_str, " ", account_id_str,
1145                                    " \"", action->destination, "\"", NULL);
1146
1147         default:
1148                 return NULL;
1149         }
1150 }
1151
1152 gchar * filteringprop_to_string(FilteringProp * prop)
1153 {
1154         gchar * list_str;
1155         gchar * action_str;
1156         gchar * filtering_str;
1157
1158         action_str = filteringaction_to_string(prop->action);
1159
1160         if (action_str == NULL)
1161                 return NULL;
1162
1163         list_str = matcherlist_to_string(prop->matchers);
1164
1165         if (list_str == NULL) {
1166                 g_free(action_str);
1167                 return NULL;
1168         }
1169
1170         filtering_str = g_strconcat(list_str, " ", action_str, NULL);
1171         g_free(list_str);
1172         g_free(action_str);
1173
1174         return filtering_str;
1175 }
1176
1177 void prefs_filtering_write_config(void)
1178 {
1179         gchar *rcpath;
1180         PrefFile *pfile;
1181         GSList *cur;
1182         FilteringProp * prop;
1183
1184         debug_print(_("Writing filtering configuration...\n"));
1185
1186         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, FILTERING_RC, NULL);
1187
1188         if ((pfile = prefs_write_open(rcpath)) == NULL) {
1189                 g_warning(_("failed to write configuration to file\n"));
1190                 g_free(rcpath);
1191                 return;
1192         }
1193
1194         for (cur = prefs_filtering; cur != NULL; cur = cur->next) {
1195                 gchar *filtering_str;
1196
1197                 prop = (FilteringProp *) cur->data;
1198                 filtering_str = filteringprop_to_string(prop);
1199                 if (fputs(filtering_str, pfile->fp) == EOF ||
1200                     fputc('\n', pfile->fp) == EOF) {
1201                         FILE_OP_ERROR(rcpath, "fputs || fputc");
1202                         prefs_write_close_revert(pfile);
1203                         g_free(rcpath);
1204                         g_free(filtering_str);
1205                         return;
1206                 }
1207                 g_free(filtering_str);
1208         }
1209
1210         g_free(rcpath);
1211
1212         if (prefs_write_close(pfile) < 0) {
1213                 g_warning(_("failed to write configuration to file\n"));
1214                 return;
1215         }
1216 }