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