T-gnus 6.15.15 revision 00.
[elisp/gnus.git-] / lisp / spam.el
1 ;;; spam.el --- Identifying spam
2 ;; Copyright (C) 2002, 2003 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: network
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; This module addresses a few aspects of spam control under Gnus.  Page
27 ;;; breaks are used for grouping declarations and documentation relating to
28 ;;; each particular aspect.
29
30 ;;; The integration with Gnus is not yet complete.  See various `FIXME'
31 ;;; comments, below, for supplementary explanations or discussions.
32
33 ;;; Several TODO items are marked as such
34
35 ;;; Code:
36
37 (require 'path-util)
38
39 (require 'gnus-sum)
40
41 (require 'gnus-uu)                      ; because of key prefix issues
42 (require 'gnus) ; for the definitions of group content classification and spam processors
43 (require 'message)                      ;for the message-fetch-field functions
44
45 ;; autoload query-dig
46 (eval-and-compile
47   (autoload 'query-dig "dig"))
48
49 ;; autoload query-dns
50 (eval-and-compile
51   (autoload 'query-dns "dns"))
52
53 ;;; Main parameters.
54
55 (defgroup spam nil
56   "Spam configuration.")
57
58 (defcustom spam-directory "~/News/spam/"
59   "Directory for spam whitelists and blacklists."
60   :type 'directory
61   :group 'spam)
62
63 (defcustom spam-move-spam-nonspam-groups-only t
64   "Whether spam should be moved in non-spam groups only.
65 When nil, only ham and unclassified groups will have their spam moved
66 to the spam-process-destination.  When t, spam will also be moved from
67 spam groups."
68   :type 'boolean
69   :group 'spam-ifile)
70
71 (defcustom spam-whitelist (expand-file-name "whitelist" spam-directory)
72   "The location of the whitelist.
73 The file format is one regular expression per line.
74 The regular expression is matched against the address."
75   :type 'file
76   :group 'spam)
77
78 (defcustom spam-blacklist (expand-file-name "blacklist" spam-directory)
79   "The location of the blacklist.
80 The file format is one regular expression per line.
81 The regular expression is matched against the address."
82   :type 'file
83   :group 'spam)
84
85 (defcustom spam-use-dig t
86   "Whether query-dig should be used instead of query-dns."
87   :type 'boolean
88   :group 'spam)
89
90 (defcustom spam-use-blacklist nil
91   "Whether the blacklist should be used by spam-split."
92   :type 'boolean
93   :group 'spam)
94
95 (defcustom spam-use-whitelist nil
96   "Whether the whitelist should be used by spam-split."
97   :type 'boolean
98   :group 'spam)
99
100 (defcustom spam-use-whitelist-exclusive nil
101   "Whether whitelist-exclusive should be used by spam-split.
102 Exclusive whitelisting means that all messages from senders not in the whitelist
103 are considered spam."
104   :type 'boolean
105   :group 'spam)
106
107 (defcustom spam-use-blackholes nil
108   "Whether blackholes should be used by spam-split."
109   :type 'boolean
110   :group 'spam)
111
112 (defcustom spam-use-regex-headers nil
113   "Whether a header regular expression match should be used by spam-split.
114 Also see the variable `spam-spam-regex-headers' and `spam-ham-regex-headers'."
115   :type 'boolean
116   :group 'spam)
117
118 (defcustom spam-use-bogofilter-headers nil
119   "Whether bogofilter headers should be used by spam-split.
120 Enable this if you pre-process messages with Bogofilter BEFORE Gnus sees them."
121   :type 'boolean
122   :group 'spam)
123
124 (defcustom spam-use-bogofilter nil
125   "Whether bogofilter should be invoked by spam-split.
126 Enable this if you want Gnus to invoke Bogofilter on new messages."
127   :type 'boolean
128   :group 'spam)
129
130 (defcustom spam-use-BBDB nil
131   "Whether BBDB should be used by spam-split."
132   :type 'boolean
133   :group 'spam)
134
135 (defcustom spam-use-BBDB-exclusive nil
136   "Whether BBDB-exclusive should be used by spam-split.
137 Exclusive BBDB means that all messages from senders not in the BBDB are 
138 considered spam."
139   :type 'boolean
140   :group 'spam)
141
142 (defcustom spam-use-ifile nil
143   "Whether ifile should be used by spam-split."
144   :type 'boolean
145   :group 'spam)
146
147 (defcustom spam-use-stat nil
148   "Whether spam-stat should be used by spam-split."
149   :type 'boolean
150   :group 'spam)
151
152 (defcustom spam-split-group "spam"
153   "Group name where incoming spam should be put by spam-split."
154   :type 'string
155   :group 'spam)
156
157 (defcustom spam-junk-mailgroups (cons spam-split-group '("mail.junk" "poste.pourriel"))
158   "Mailgroups with spam contents.
159 All unmarked article in such group receive the spam mark on group entry."
160   :type '(repeat (string :tag "Group"))
161   :group 'spam)
162
163 (defcustom spam-blackhole-servers '("bl.spamcop.net" "relays.ordb.org" 
164                                     "dev.null.dk" "relays.visi.com")
165   "List of blackhole servers."
166   :type '(repeat (string :tag "Server"))
167   :group 'spam)
168
169 (defcustom spam-blackhole-good-server-regex nil
170   "String matching IP addresses that should not be checked in the blackholes"
171   :type 'regexp
172   :group 'spam)
173
174 (defcustom spam-ham-marks (list 'gnus-del-mark 'gnus-read-mark 
175                                 'gnus-killed-mark 'gnus-kill-file-mark 
176                                 'gnus-low-score-mark)
177   "Marks considered as being ham (positively not spam).
178 Such articles will be processed as ham (non-spam) on group exit."
179   :type '(set
180           (variable-item gnus-del-mark)
181           (variable-item gnus-read-mark)
182           (variable-item gnus-killed-mark)
183           (variable-item gnus-kill-file-mark)
184           (variable-item gnus-low-score-mark))
185   :group 'spam)
186
187 (defcustom spam-spam-marks (list 'gnus-spam-mark)
188   "Marks considered as being spam (positively spam).
189 Such articles will be transmitted to `bogofilter -s' on group exit."
190   :type '(set 
191           (variable-item gnus-spam-mark)
192           (variable-item gnus-killed-mark)
193           (variable-item gnus-kill-file-mark)
194           (variable-item gnus-low-score-mark))
195   :group 'spam)
196
197 (defcustom spam-face 'gnus-splash-face
198   "Face for spam-marked articles"
199   :type 'face
200   :group 'spam)
201
202 (defcustom spam-regex-headers-spam '("^X-Spam-Flag: YES")
203   "Regular expression for positive header spam matches"
204   :type '(repeat (regexp :tag "Regular expression to match spam header"))
205   :group 'spam)
206
207 (defcustom spam-regex-headers-ham '("^X-Spam-Flag: NO")
208   "Regular expression for positive header ham matches"
209   :type '(repeat (regexp :tag "Regular expression to match ham header"))
210   :group 'spam)
211
212 (defgroup spam-ifile nil
213   "Spam ifile configuration."
214   :group 'spam)
215
216 (defcustom spam-ifile-path (exec-installed-p "ifile")
217   "File path of the ifile executable program."
218   :type '(choice (file :tag "Location of ifile")
219                  (const :tag "ifile is not installed"))
220   :group 'spam-ifile)
221
222 (defcustom spam-ifile-database-path nil
223   "File path of the ifile database."
224   :type '(choice (file :tag "Location of the ifile database")
225                  (const :tag "Use the default"))
226   :group 'spam-ifile)
227
228 (defcustom spam-ifile-spam-category "spam"
229   "Name of the spam ifile category."  
230   :type 'string
231   :group 'spam-ifile)
232
233 (defcustom spam-ifile-ham-category nil
234   "Name of the ham ifile category.  If nil, the current group name will
235 be used."
236   :type '(choice (string :tag "Use a fixed category")
237                 (const :tag "Use the current group name"))
238   :group 'spam-ifile)
239
240 (defcustom spam-ifile-all-categories nil
241   "Whether the ifile check will return all categories, or just spam.
242 Set this to t if you want to use the spam-split invocation of ifile as
243 your main source of newsgroup names."
244   :type 'boolean
245   :group 'spam-ifile)
246
247 (defgroup spam-bogofilter nil
248   "Spam bogofilter configuration."
249   :group 'spam)
250
251 (defcustom spam-bogofilter-path (exec-installed-p "bogofilter")
252   "File path of the Bogofilter executable program."
253   :type '(choice (file :tag "Location of bogofilter")
254                  (const :tag "Bogofilter is not installed"))
255   :group 'spam-bogofilter)
256
257 (defcustom spam-bogofilter-header "X-Bogosity"
258   "The header that Bogofilter inserts in messages."
259   :type 'string
260   :group 'spam-bogofilter)
261
262 (defcustom spam-bogofilter-bogosity-positive-spam-header "^\\(Yes\\|Spam\\)"
263   "The regex on `spam-bogofilter-header' for positive spam identification."
264   :type 'regexp
265   :group 'spam-bogofilter)
266
267 (defcustom spam-bogofilter-database-directory nil
268   "Directory path of the Bogofilter databases."
269   :type '(choice (directory :tag "Location of the Bogofilter database directory")
270                  (const :tag "Use the default"))
271   :group 'spam-ifile)
272
273 ;;; Key bindings for spam control.
274
275 (gnus-define-keys gnus-summary-mode-map
276   "St" spam-bogofilter-score
277   "Sx" gnus-summary-mark-as-spam
278   "Mst" spam-bogofilter-score
279   "Msx" gnus-summary-mark-as-spam
280   "\M-d" gnus-summary-mark-as-spam)
281
282 ;;; How to highlight a spam summary line.
283
284 ;; TODO: How do we redo this every time spam-face is customized?
285
286 (push '((eq mark gnus-spam-mark) . spam-face)
287       gnus-summary-highlight)
288
289 ;; convenience functions
290 (defun spam-group-spam-contents-p (group)
291   (if (stringp group)
292       (or (member group spam-junk-mailgroups)
293           (memq 'gnus-group-spam-classification-spam 
294                 (gnus-parameter-spam-contents group)))
295     nil))
296   
297 (defun spam-group-ham-contents-p (group)
298   (if (stringp group)
299       (memq 'gnus-group-spam-classification-ham 
300             (gnus-parameter-spam-contents group))
301     nil))
302
303 (defun spam-group-processor-p (group processor)
304   (if (and (stringp group)
305            (symbolp processor))
306       (member processor (car (gnus-parameter-spam-process group)))
307     nil))
308
309 (defun spam-group-spam-processor-bogofilter-p (group)
310   (spam-group-processor-p group 'gnus-group-spam-exit-processor-bogofilter))
311
312 (defun spam-group-spam-processor-blacklist-p (group)
313   (spam-group-processor-p group 'gnus-group-spam-exit-processor-blacklist))
314
315 (defun spam-group-spam-processor-ifile-p (group)
316   (spam-group-processor-p group 'gnus-group-spam-exit-processor-ifile))
317
318 (defun spam-group-ham-processor-ifile-p (group)
319   (spam-group-processor-p group 'gnus-group-ham-exit-processor-ifile))
320
321 (defun spam-group-ham-processor-bogofilter-p (group)
322   (spam-group-processor-p group 'gnus-group-ham-exit-processor-bogofilter))
323
324 (defun spam-group-spam-processor-stat-p (group)
325   (spam-group-processor-p group 'gnus-group-spam-exit-processor-stat))
326
327 (defun spam-group-ham-processor-stat-p (group)
328   (spam-group-processor-p group 'gnus-group-ham-exit-processor-stat))
329
330 (defun spam-group-ham-processor-whitelist-p (group)
331   (spam-group-processor-p group 'gnus-group-ham-exit-processor-whitelist))
332
333 (defun spam-group-ham-processor-BBDB-p (group)
334   (spam-group-processor-p group 'gnus-group-ham-exit-processor-BBDB))
335
336 ;;; Summary entry and exit processing.
337
338 (defun spam-summary-prepare ()
339   (spam-mark-junk-as-spam-routine))
340
341 (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
342
343 (defun spam-summary-prepare-exit ()
344   ;; The spam processors are invoked for any group, spam or ham or neither
345   (gnus-message 6 "Exiting summary buffer and applying spam rules")
346   (when (and spam-bogofilter-path
347              (spam-group-spam-processor-bogofilter-p gnus-newsgroup-name))
348     (gnus-message 5 "Registering spam with bogofilter")
349     (spam-bogofilter-register-spam-routine))
350   
351   (when (and spam-ifile-path
352              (spam-group-spam-processor-ifile-p gnus-newsgroup-name))
353     (gnus-message 5 "Registering spam with ifile")
354     (spam-ifile-register-spam-routine))
355   
356   (when (spam-group-spam-processor-stat-p gnus-newsgroup-name)
357     (gnus-message 5 "Registering spam with spam-stat")
358     (spam-stat-register-spam-routine))
359
360   (when (spam-group-spam-processor-blacklist-p gnus-newsgroup-name)
361     (gnus-message 5 "Registering spam with the blacklist")
362     (spam-blacklist-register-routine))
363
364   (if spam-move-spam-nonspam-groups-only      
365       (when (not (spam-group-spam-contents-p gnus-newsgroup-name))
366         (spam-mark-spam-as-expired-and-move-routine
367          (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
368     (gnus-message 5 "Marking spam as expired and moving it")
369     (spam-mark-spam-as-expired-and-move-routine 
370      (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
371
372   ;; now we redo spam-mark-spam-as-expired-and-move-routine to only
373   ;; expire spam, in case the above did not expire them
374   (spam-mark-spam-as-expired-and-move-routine nil)
375
376   (when (spam-group-ham-contents-p gnus-newsgroup-name)
377     (when (spam-group-ham-processor-whitelist-p gnus-newsgroup-name)
378       (gnus-message 5 "Registering ham with the whitelist")
379       (spam-whitelist-register-routine))
380     (when (spam-group-ham-processor-ifile-p gnus-newsgroup-name)
381       (gnus-message 5 "Registering ham with ifile")
382       (spam-ifile-register-ham-routine))
383     (when (spam-group-ham-processor-bogofilter-p gnus-newsgroup-name)
384       (gnus-message 5 "Registering ham with Bogofilter")
385       (spam-bogofilter-register-ham-routine))
386     (when (spam-group-ham-processor-stat-p gnus-newsgroup-name)
387       (gnus-message 5 "Registering ham with spam-stat")
388       (spam-stat-register-ham-routine))
389     (when (spam-group-ham-processor-BBDB-p gnus-newsgroup-name)
390       (gnus-message 5 "Registering ham with the BBDB")
391       (spam-BBDB-register-routine)))
392
393   ;; now move all ham articles out of spam groups
394   (when (spam-group-spam-contents-p gnus-newsgroup-name)
395     (gnus-message 5 "Moving ham messages from spam group")
396     (spam-ham-move-routine
397      (gnus-parameter-ham-process-destination gnus-newsgroup-name))))
398
399 (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
400
401 (defun spam-mark-junk-as-spam-routine ()
402   ;; check the global list of group names spam-junk-mailgroups and the
403   ;; group parameters
404   (when (spam-group-spam-contents-p gnus-newsgroup-name)
405     (gnus-message 5 "Marking unread articles as spam")
406     (let ((articles gnus-newsgroup-articles)
407           article)
408       (while articles
409         (setq article (pop articles))
410         (when (eq (gnus-summary-article-mark article) gnus-unread-mark)
411           (gnus-summary-mark-article article gnus-spam-mark))))))
412
413 (defun spam-mark-spam-as-expired-and-move-routine (&optional group)
414   (let ((articles gnus-newsgroup-articles)
415         article)
416     (while articles
417       (setq article (pop articles))
418       (when (eq (gnus-summary-article-mark article) gnus-spam-mark)
419         (gnus-summary-mark-article article gnus-expirable-mark)
420         (when (stringp group)
421           (let ((gnus-current-article article))
422             (gnus-summary-move-article nil group)))))))
423  
424 (defun spam-ham-move-routine (&optional group)
425   (let ((articles gnus-newsgroup-articles)
426         article ham-mark-values mark)
427
428     (dolist (mark spam-ham-marks)
429       (push (symbol-value mark) ham-mark-values))
430     
431     (dolist (article articles)
432       (when (and (memq (gnus-summary-article-mark article) ham-mark-values)
433                  (stringp group))
434         (let ((gnus-current-article article))
435           (gnus-summary-move-article nil group))))))
436  
437 (defun spam-generic-register-routine (spam-func ham-func)
438   (let ((articles gnus-newsgroup-articles)
439         article mark ham-articles spam-articles spam-mark-values 
440         ham-mark-values)
441
442     ;; marks are stored as symbolic values, so we have to dereference
443     ;; them for memq to work.  we wouldn't have to do this if
444     ;; gnus-summary-article-mark returned a symbol.
445     (dolist (mark spam-ham-marks)
446       (push (symbol-value mark) ham-mark-values))
447
448     (dolist (mark spam-spam-marks)
449       (push (symbol-value mark) spam-mark-values))
450
451     (while articles
452       (setq article (pop articles)
453             mark (gnus-summary-article-mark article))
454       (cond ((memq mark spam-mark-values) (push article spam-articles))
455             ((memq article gnus-newsgroup-saved))
456             ((memq mark ham-mark-values) (push article ham-articles))))
457     (when (and ham-articles ham-func)
458       (mapc ham-func ham-articles))     ; we use mapc because unlike
459                                         ; mapcar it discards the
460                                         ; return values
461     (when (and spam-articles spam-func)
462       (mapc spam-func spam-articles)))) ; we use mapc because unlike
463                                         ; mapcar it discards the
464                                         ; return values
465
466 (eval-and-compile
467   (defalias 'spam-point-at-eol (if (fboundp 'point-at-eol)
468                                    'point-at-eol
469                                  'line-end-position)))
470
471 (defun spam-get-article-as-string (article)
472   (let ((article-buffer (spam-get-article-as-buffer article))
473                         article-string)
474     (when article-buffer
475       (save-window-excursion
476         (set-buffer article-buffer)
477         (setq article-string (buffer-string))))
478   article-string))
479
480 (defun spam-get-article-as-buffer (article)
481   (let ((article-buffer))
482     (when (numberp article)
483       (save-window-excursion
484         (gnus-summary-goto-subject article)
485         (gnus-summary-show-article t)
486         (setq article-buffer (get-buffer gnus-article-buffer))))
487     article-buffer))
488
489 (defun spam-get-article-as-filename (article)
490   (let ((article-filename))
491     (when (numberp article)
492       (nnml-possibly-change-directory (gnus-group-real-name gnus-newsgroup-name))
493       (setq article-filename (expand-file-name (int-to-string article) nnml-current-directory)))
494     (if (file-exists-p article-filename)
495         article-filename
496       nil)))
497
498 (defun spam-fetch-field-from-fast (article)
499   "Fetch the `from' field quickly, using the internal gnus-data-list function"
500   (if (and (numberp article)
501            (assoc article (gnus-data-list nil)))
502       (mail-header-from (gnus-data-header (assoc article (gnus-data-list nil))))
503     nil))
504
505 (defun spam-fetch-field-subject-fast (article)
506   "Fetch the `subject' field quickly, using the internal gnus-data-list function"
507   (if (and (numberp article)
508            (assoc article (gnus-data-list nil)))
509       (mail-header-subject (gnus-data-header (assoc article (gnus-data-list nil))))
510     nil))
511
512 \f
513 ;;;; Spam determination.
514
515 (defvar spam-list-of-checks
516   '((spam-use-blacklist                 .       spam-check-blacklist)
517     (spam-use-regex-headers             .       spam-check-regex-headers)
518     (spam-use-whitelist                 .       spam-check-whitelist)
519     (spam-use-BBDB                      .       spam-check-BBDB)
520     (spam-use-ifile                     .       spam-check-ifile)
521     (spam-use-stat                      .       spam-check-stat)
522     (spam-use-blackholes                .       spam-check-blackholes)
523     (spam-use-bogofilter-headers        .       spam-check-bogofilter-headers)
524     (spam-use-bogofilter                .       spam-check-bogofilter))
525 "The spam-list-of-checks list contains pairs associating a parameter
526 variable with a spam checking function.  If the parameter variable is
527 true, then the checking function is called, and its value decides what
528 happens.  Each individual check may return nil, t, or a mailgroup
529 name.  The value nil means that the check does not yield a decision,
530 and so, that further checks are needed.  The value t means that the
531 message is definitely not spam, and that further spam checks should be
532 inhibited.  Otherwise, a mailgroup name is returned where the mail
533 should go, and further checks are also inhibited.  The usual mailgroup
534 name is the value of `spam-split-group', meaning that the message is
535 definitely a spam.")
536
537 (defun spam-split ()
538   "Split this message into the `spam' group if it is spam.
539 This function can be used as an entry in `nnmail-split-fancy', for
540 example like this: (: spam-split)
541
542 See the Info node `(gnus)Fancy Mail Splitting' for more details."
543   (interactive)
544   
545   ;; load the spam-stat tables if needed
546   (when spam-use-stat (spam-stat-load))
547
548   (let ((list-of-checks spam-list-of-checks)
549         decision)
550     (while (and list-of-checks (not decision))
551       (let ((pair (pop list-of-checks)))
552         (when (symbol-value (car pair))
553           (gnus-message 5 "spam-split: calling the %s function" (symbol-name (cdr pair)))
554           (setq decision (funcall (cdr pair))))))
555     (if (eq decision t)
556         nil
557       decision)))
558 \f
559 ;;;; Regex headers
560
561 (defun spam-check-regex-headers ()
562   (let (ret found)
563     (dolist (h-regex spam-regex-headers-ham)
564       (unless found
565         (goto-char (point-min))
566         (when (re-search-forward h-regex nil t)
567           (message "Ham regex header search positive.")
568           (setq found t))))
569     (dolist (s-regex spam-regex-headers-spam)
570       (unless found
571         (goto-char (point-min))
572         (when (re-search-forward s-regex nil t)
573           (message "Spam regex header search positive." (match-string 1))
574           (setq found t)
575           (setq ret spam-split-group))))
576     ret))
577
578 \f
579 ;;;; Blackholes.
580
581 (defun spam-check-blackholes ()
582   "Check the Received headers for blackholed relays."
583   (let ((headers (message-fetch-field "received"))
584         ips matches)
585     (when headers
586       (with-temp-buffer
587         (insert headers)
588         (goto-char (point-min))
589         (gnus-message 5 "Checking headers for relay addresses")
590         (while (re-search-forward
591                 "\\[\\([0-9]+.[0-9]+.[0-9]+.[0-9]+\\)\\]" nil t)
592           (gnus-message 9 "Blackhole search found host IP %s." (match-string 1))
593           (push (mapconcat 'identity
594                            (nreverse (split-string (match-string 1) "\\."))
595                            ".")
596                 ips)))
597       (dolist (server spam-blackhole-servers)
598         (dolist (ip ips)
599           (unless (and spam-blackhole-good-server-regex
600                        (string-match spam-blackhole-good-server-regex ip))
601             (let ((query-string (concat ip "." server)))
602               (if spam-use-dig
603                   (let ((query-result (query-dig query-string)))
604                     (when query-result
605                       (gnus-message 5 "(DIG): positive blackhole check '%s'" query-result)
606                       (push (list ip server query-result)
607                             matches)))
608                 ;; else, if not using dig.el
609                 (when (query-dns query-string)
610                   (gnus-message 5 "positive blackhole check")
611                   (push (list ip server (query-dns query-string 'TXT))
612                         matches))))))))
613     (when matches
614       spam-split-group)))
615 \f
616 ;;;; BBDB 
617
618 ;;; original idea for spam-check-BBDB from Alexander Kotelnikov
619 ;;; <sacha@giotto.sj.ru>
620
621 ;; all this is done inside a condition-case to trap errors
622
623 (condition-case nil
624     (progn
625       (require 'bbdb)
626       (require 'bbdb-com)
627       
628   (defun spam-enter-ham-BBDB (from)
629     "Enter an address into the BBDB; implies ham (non-spam) sender"
630     (when (stringp from)
631       (let* ((parsed-address (gnus-extract-address-components from))
632              (name (or (car parsed-address) "Ham Sender"))
633              (net-address (car (cdr parsed-address))))
634         (gnus-message 5 "Adding address %s to BBDB" from)
635         (when (and net-address
636                    (not (bbdb-search-simple nil net-address)))
637           (bbdb-create-internal name nil net-address nil nil 
638                                 "ham sender added by spam.el")))))
639
640   (defun spam-BBDB-register-routine ()
641     (spam-generic-register-routine 
642      ;; spam function
643      nil
644      ;; ham function
645      (lambda (article)
646        (spam-enter-ham-BBDB (spam-fetch-field-from-fast article)))))
647
648   (defun spam-check-BBDB ()
649     "Mail from people in the BBDB is classified as ham or non-spam"
650     (let ((who (message-fetch-field "from")))
651       (when who
652         (setq who (cadr (gnus-extract-address-components who)))
653         (if (bbdb-search-simple nil who)
654             t 
655           (if spam-use-BBDB-exclusive
656               spam-split-group
657             nil))))))
658
659   (file-error (progn
660                 (defalias 'bbdb-search-simple 'ignore)
661                 (defalias 'spam-check-BBDB 'ignore)
662                 (defalias 'spam-BBDB-register-routine 'ignore)
663                 (defalias 'spam-enter-ham-BBDB 'ignore)
664                 (defalias 'bbdb-create-internal 'ignore)
665                 (defalias 'bbdb-records 'ignore))))
666
667 \f
668 ;;;; ifile
669
670 ;;; check the ifile backend; return nil if the mail was NOT classified
671 ;;; as spam
672
673 (defun spam-get-ifile-database-parameter ()
674   "Get the command-line parameter for ifile's database from spam-ifile-database-path."
675   (if spam-ifile-database-path
676       (format "--db-file=%s" spam-ifile-database-path)
677     nil))
678     
679 (defun spam-check-ifile ()
680   "Check the ifile backend for the classification of this message"
681   (let ((article-buffer-name (buffer-name)) 
682         category return)
683     (with-temp-buffer
684       (let ((temp-buffer-name (buffer-name))
685             (db-param (spam-get-ifile-database-parameter)))
686         (save-excursion
687           (set-buffer article-buffer-name)
688           (if db-param
689               (call-process-region (point-min) (point-max) spam-ifile-path
690                                    nil temp-buffer-name nil "-q" "-c" db-param)
691             (call-process-region (point-min) (point-max) spam-ifile-path
692                                  nil temp-buffer-name nil "-q" "-c")))
693         (goto-char (point-min))
694         (if (not (eobp))
695             (setq category (buffer-substring (point) (spam-point-at-eol))))
696         (when (not (zerop (length category))) ; we need a category here
697           (if spam-ifile-all-categories
698               (setq return category)
699             ;; else, if spam-ifile-all-categories is not set...
700             (when (string-equal spam-ifile-spam-category category)
701               (setq return spam-split-group))))))
702     return))
703
704 (defun spam-ifile-register-with-ifile (article-string category)
705   "Register an article, given as a string, with a category.
706 Uses `gnus-newsgroup-name' if category is nil (for ham registration)."
707   (when (stringp article-string)
708     (let ((category (or category gnus-newsgroup-name))
709           (db-param (spam-get-ifile-database-parameter)))
710       (with-temp-buffer
711         (insert-string article-string)
712         (if db-param
713             (call-process-region (point-min) (point-max) spam-ifile-path 
714                                  nil nil nil 
715                                  "-h" "-i" category db-param)
716           (call-process-region (point-min) (point-max) spam-ifile-path 
717                                nil nil nil 
718                                "-h" "-i" category))))))
719
720 (defun spam-ifile-register-spam-routine ()
721   (spam-generic-register-routine 
722    (lambda (article)
723      (spam-ifile-register-with-ifile 
724       (spam-get-article-as-string article) spam-ifile-spam-category))
725    nil))
726
727 (defun spam-ifile-register-ham-routine ()
728   (spam-generic-register-routine 
729    nil
730    (lambda (article)
731      (spam-ifile-register-with-ifile 
732       (spam-get-article-as-string article) spam-ifile-ham-category))))
733
734 \f
735 ;;;; spam-stat
736
737 (condition-case nil
738     (progn
739       (let ((spam-stat-install-hooks nil))
740         (require 'spam-stat))
741       
742       (defun spam-check-stat ()
743         "Check the spam-stat backend for the classification of this message"
744         (let ((spam-stat-split-fancy-spam-group spam-split-group) ; override
745               (spam-stat-buffer (buffer-name)) ; stat the current buffer
746               category return)
747           (spam-stat-split-fancy)))
748
749       (defun spam-stat-register-spam-routine ()
750         (spam-generic-register-routine 
751          (lambda (article)
752            (let ((article-string (spam-get-article-as-string article)))
753              (with-temp-buffer
754                (insert-string article-string)
755                (spam-stat-buffer-is-spam))))
756          nil)
757         (spam-stat-save))
758
759       (defun spam-stat-register-ham-routine ()
760         (spam-generic-register-routine 
761          nil
762          (lambda (article)
763            (let ((article-string (spam-get-article-as-string article)))
764              (with-temp-buffer
765                (insert-string article-string)
766                (spam-stat-buffer-is-non-spam)))))
767         (spam-stat-save)))
768
769   (file-error (progn
770                 (defalias 'spam-stat-register-ham-routine 'ignore)
771                 (defalias 'spam-stat-register-spam-routine 'ignore)
772                 (defalias 'spam-stat-buffer-is-spam 'ignore)
773                 (defalias 'spam-stat-buffer-is-non-spam 'ignore)
774                 (defalias 'spam-stat-split-fancy 'ignore)
775                 (defalias 'spam-stat-load 'ignore)
776                 (defalias 'spam-stat-save 'ignore)
777                 (defalias 'spam-check-stat 'ignore))))
778
779 \f
780
781 ;;;; Blacklists and whitelists.
782
783 (defvar spam-whitelist-cache nil)
784 (defvar spam-blacklist-cache nil)
785
786 (defun spam-enter-whitelist (address)
787   "Enter ADDRESS into the whitelist."
788   (interactive "sAddress: ")
789   (spam-enter-list address spam-whitelist)
790   (setq spam-whitelist-cache nil))
791
792 (defun spam-enter-blacklist (address)
793   "Enter ADDRESS into the blacklist."
794   (interactive "sAddress: ")
795   (spam-enter-list address spam-blacklist)
796   (setq spam-blacklist-cache nil))
797
798 (defun spam-enter-list (address file)
799   "Enter ADDRESS into the given FILE, either the whitelist or the blacklist."
800   (unless (file-exists-p (file-name-directory file))
801     (make-directory (file-name-directory file) t))
802   (save-excursion
803     (set-buffer
804      (find-file-noselect file))
805     (goto-char (point-max))
806     (unless (bobp)
807       (insert "\n"))
808     (insert address "\n")
809     (save-buffer)))
810
811 ;;; returns t if the sender is in the whitelist, nil or spam-split-group otherwise
812 (defun spam-check-whitelist ()
813   ;; FIXME!  Should it detect when file timestamps change?
814   (unless spam-whitelist-cache
815     (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
816   (if (spam-from-listed-p spam-whitelist-cache) 
817       t
818     (if spam-use-whitelist-exclusive
819         spam-split-group
820       nil)))
821
822 (defun spam-check-blacklist ()
823   ;; FIXME!  Should it detect when file timestamps change?
824   (unless spam-blacklist-cache
825     (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
826   (and (spam-from-listed-p spam-blacklist-cache) spam-split-group))
827
828 (defun spam-parse-list (file)
829   (when (file-readable-p file)
830     (let (contents address)
831       (with-temp-buffer
832         (insert-file-contents file)
833         (while (not (eobp))
834           (setq address (buffer-substring (point) (spam-point-at-eol)))
835           (forward-line 1)
836           (unless (zerop (length address))
837             (setq address (regexp-quote address))
838             (while (string-match "\\\\\\*" address)
839               (setq address (replace-match ".*" t t address)))
840             (push address contents))))
841       (nreverse contents))))
842
843 (defun spam-from-listed-p (cache)
844   (let ((from (message-fetch-field "from"))
845         found)
846     (while cache
847       (when (string-match (pop cache) from)
848         (setq found t
849               cache nil)))
850     found))
851
852 (defun spam-blacklist-register-routine ()
853   (spam-generic-register-routine 
854    ;; the spam function
855    (lambda (article)
856      (let ((from (spam-fetch-field-from-fast article)))
857        (when (stringp from)
858            (spam-enter-blacklist from))))
859    ;; the ham function
860    nil))
861
862 (defun spam-whitelist-register-routine ()
863   (spam-generic-register-routine 
864    ;; the spam function
865    nil 
866    ;; the ham function
867    (lambda (article)
868      (let ((from (spam-fetch-field-from-fast article)))
869        (when (stringp from)
870            (spam-enter-whitelist from))))))
871
872 \f
873 ;;;; Bogofilter
874
875 (defun spam-check-bogofilter-headers (&optional score)
876   (let ((header (message-fetch-field spam-bogofilter-header)))
877       (when (and header
878                  (string-match spam-bogofilter-bogosity-positive-spam-header
879                                header))
880           (if score
881               (when (string-match "spamicity=\\([0-9.]+\\)" header)
882                 (match-string 1 header))
883             spam-split-group))))
884
885 ;; return something sensible if the score can't be determined
886 (defun spam-bogofilter-score ()
887   "Get the Bogofilter spamicity score"
888   (interactive)
889   (save-window-excursion
890     (gnus-summary-show-article t)
891     (set-buffer gnus-article-buffer)
892     (let ((score (spam-check-bogofilter t)))
893       (message "Spamicity score %s" score)
894       (or score "0"))))
895
896 (defun spam-check-bogofilter (&optional score)
897   "Check the Bogofilter backend for the classification of this message"
898   (let ((article-buffer-name (buffer-name)) 
899         return)
900     (with-temp-buffer
901       (let ((temp-buffer-name (buffer-name)))
902         (save-excursion
903           (set-buffer article-buffer-name)
904           (if spam-bogofilter-database-directory
905               (call-process-region (point-min) (point-max) 
906                                    spam-bogofilter-path
907                                    nil temp-buffer-name nil "-v"
908                                    "-d" spam-bogofilter-database-directory)
909             (call-process-region (point-min) (point-max) spam-bogofilter-path
910                                  nil temp-buffer-name nil "-v")))
911         (setq return (spam-check-bogofilter-headers score))))
912     return))
913
914 (defun spam-bogofilter-register-with-bogofilter (article-string spam)
915   "Register an article, given as a string, as spam or non-spam."
916   (when (stringp article-string)
917     (let ((switch (if spam "-s" "-n")))
918       (with-temp-buffer
919         (insert-string article-string)
920         (if spam-bogofilter-database-directory
921             (call-process-region (point-min) (point-max) 
922                                  spam-bogofilter-path
923                                  nil nil nil "-v" switch
924                                  "-d" spam-bogofilter-database-directory)
925           (call-process-region (point-min) (point-max) spam-bogofilter-path
926                                nil nil nil "-v" switch))))))
927
928 (defun spam-bogofilter-register-spam-routine ()
929   (spam-generic-register-routine 
930    (lambda (article)
931      (spam-bogofilter-register-with-bogofilter
932       (spam-get-article-as-string article) t))
933    nil))
934
935 (defun spam-bogofilter-register-ham-routine ()
936   (spam-generic-register-routine 
937    nil
938    (lambda (article)
939      (spam-bogofilter-register-with-bogofilter
940       (spam-get-article-as-string article) nil))))
941
942 (provide 'spam)
943
944 ;;; spam.el ends here.