Synch to Oort Gnus.
[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           (gnus-summary-set-process-mark 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     (dolist (article articles)      
431       (when (and (memq (gnus-summary-article-mark article) ham-mark-values)
432                  (stringp group))
433         (gnus-summary-set-process-mark article)
434         (gnus-summary-move-article nil group)))))
435  
436 (defun spam-generic-register-routine (spam-func ham-func)
437   (let ((articles gnus-newsgroup-articles)
438         article mark ham-articles spam-articles spam-mark-values 
439         ham-mark-values)
440
441     ;; marks are stored as symbolic values, so we have to dereference
442     ;; them for memq to work.  we wouldn't have to do this if
443     ;; gnus-summary-article-mark returned a symbol.
444     (dolist (mark spam-ham-marks)
445       (push (symbol-value mark) ham-mark-values))
446
447     (dolist (mark spam-spam-marks)
448       (push (symbol-value mark) spam-mark-values))
449
450     (while articles
451       (setq article (pop articles)
452             mark (gnus-summary-article-mark article))
453       (cond ((memq mark spam-mark-values) (push article spam-articles))
454             ((memq article gnus-newsgroup-saved))
455             ((memq mark ham-mark-values) (push article ham-articles))))
456     (when (and ham-articles ham-func)
457       (mapc ham-func ham-articles))     ; we use mapc because unlike
458                                         ; mapcar it discards the
459                                         ; return values
460     (when (and spam-articles spam-func)
461       (mapc spam-func spam-articles)))) ; we use mapc because unlike
462                                         ; mapcar it discards the
463                                         ; return values
464
465 (eval-and-compile
466   (defalias 'spam-point-at-eol (if (fboundp 'point-at-eol)
467                                    'point-at-eol
468                                  'line-end-position)))
469
470 (defun spam-get-article-as-string (article)
471   (let ((article-buffer (spam-get-article-as-buffer article))
472                         article-string)
473     (when article-buffer
474       (save-window-excursion
475         (set-buffer article-buffer)
476         (setq article-string (buffer-string))))
477   article-string))
478
479 (defun spam-get-article-as-buffer (article)
480   (let ((article-buffer))
481     (when (numberp article)
482       (save-window-excursion
483         (gnus-summary-goto-subject article)
484         (gnus-summary-show-article t)
485         (setq article-buffer (get-buffer gnus-article-buffer))))
486     article-buffer))
487
488 (defun spam-get-article-as-filename (article)
489   (let ((article-filename))
490     (when (numberp article)
491       (nnml-possibly-change-directory (gnus-group-real-name gnus-newsgroup-name))
492       (setq article-filename (expand-file-name (int-to-string article) nnml-current-directory)))
493     (if (file-exists-p article-filename)
494         article-filename
495       nil)))
496
497 (defun spam-fetch-field-from-fast (article)
498   "Fetch the `from' field quickly, using the internal gnus-data-list function"
499   (if (and (numberp article)
500            (assoc article (gnus-data-list nil)))
501       (mail-header-from (gnus-data-header (assoc article (gnus-data-list nil))))
502     nil))
503
504 (defun spam-fetch-field-subject-fast (article)
505   "Fetch the `subject' field quickly, using the internal gnus-data-list function"
506   (if (and (numberp article)
507            (assoc article (gnus-data-list nil)))
508       (mail-header-subject (gnus-data-header (assoc article (gnus-data-list nil))))
509     nil))
510
511 \f
512 ;;;; Spam determination.
513
514 (defvar spam-list-of-checks
515   '((spam-use-blacklist                 .       spam-check-blacklist)
516     (spam-use-regex-headers             .       spam-check-regex-headers)
517     (spam-use-whitelist                 .       spam-check-whitelist)
518     (spam-use-BBDB                      .       spam-check-BBDB)
519     (spam-use-ifile                     .       spam-check-ifile)
520     (spam-use-stat                      .       spam-check-stat)
521     (spam-use-blackholes                .       spam-check-blackholes)
522     (spam-use-bogofilter-headers        .       spam-check-bogofilter-headers)
523     (spam-use-bogofilter                .       spam-check-bogofilter))
524 "The spam-list-of-checks list contains pairs associating a parameter
525 variable with a spam checking function.  If the parameter variable is
526 true, then the checking function is called, and its value decides what
527 happens.  Each individual check may return nil, t, or a mailgroup
528 name.  The value nil means that the check does not yield a decision,
529 and so, that further checks are needed.  The value t means that the
530 message is definitely not spam, and that further spam checks should be
531 inhibited.  Otherwise, a mailgroup name is returned where the mail
532 should go, and further checks are also inhibited.  The usual mailgroup
533 name is the value of `spam-split-group', meaning that the message is
534 definitely a spam.")
535
536 (defun spam-split ()
537   "Split this message into the `spam' group if it is spam.
538 This function can be used as an entry in `nnmail-split-fancy', for
539 example like this: (: spam-split)
540
541 See the Info node `(gnus)Fancy Mail Splitting' for more details."
542   (interactive)
543   
544   ;; load the spam-stat tables if needed
545   (when spam-use-stat (spam-stat-load))
546
547   (let ((list-of-checks spam-list-of-checks)
548         decision)
549     (while (and list-of-checks (not decision))
550       (let ((pair (pop list-of-checks)))
551         (when (symbol-value (car pair))
552           (gnus-message 5 "spam-split: calling the %s function" (symbol-name (cdr pair)))
553           (setq decision (funcall (cdr pair))))))
554     (if (eq decision t)
555         nil
556       decision)))
557 \f
558 ;;;; Regex headers
559
560 (defun spam-check-regex-headers ()
561   (let (ret found)
562     (dolist (h-regex spam-regex-headers-ham)
563       (unless found
564         (goto-char (point-min))
565         (when (re-search-forward h-regex nil t)
566           (message "Ham regex header search positive.")
567           (setq found t))))
568     (dolist (s-regex spam-regex-headers-spam)
569       (unless found
570         (goto-char (point-min))
571         (when (re-search-forward s-regex nil t)
572           (message "Spam regex header search positive." (match-string 1))
573           (setq found t)
574           (setq ret spam-split-group))))
575     ret))
576
577 \f
578 ;;;; Blackholes.
579
580 (defun spam-check-blackholes ()
581   "Check the Received headers for blackholed relays."
582   (let ((headers (message-fetch-field "received"))
583         ips matches)
584     (when headers
585       (with-temp-buffer
586         (insert headers)
587         (goto-char (point-min))
588         (gnus-message 5 "Checking headers for relay addresses")
589         (while (re-search-forward
590                 "\\[\\([0-9]+.[0-9]+.[0-9]+.[0-9]+\\)\\]" nil t)
591           (gnus-message 9 "Blackhole search found host IP %s." (match-string 1))
592           (push (mapconcat 'identity
593                            (nreverse (split-string (match-string 1) "\\."))
594                            ".")
595                 ips)))
596       (dolist (server spam-blackhole-servers)
597         (dolist (ip ips)
598           (unless (and spam-blackhole-good-server-regex
599                        (string-match spam-blackhole-good-server-regex ip))
600             (let ((query-string (concat ip "." server)))
601               (if spam-use-dig
602                   (let ((query-result (query-dig query-string)))
603                     (when query-result
604                       (gnus-message 5 "(DIG): positive blackhole check '%s'" query-result)
605                       (push (list ip server query-result)
606                             matches)))
607                 ;; else, if not using dig.el
608                 (when (query-dns query-string)
609                   (gnus-message 5 "positive blackhole check")
610                   (push (list ip server (query-dns query-string 'TXT))
611                         matches))))))))
612     (when matches
613       spam-split-group)))
614 \f
615 ;;;; BBDB 
616
617 ;;; original idea for spam-check-BBDB from Alexander Kotelnikov
618 ;;; <sacha@giotto.sj.ru>
619
620 ;; all this is done inside a condition-case to trap errors
621
622 (condition-case nil
623     (progn
624       (require 'bbdb)
625       (require 'bbdb-com)
626       
627   (defun spam-enter-ham-BBDB (from)
628     "Enter an address into the BBDB; implies ham (non-spam) sender"
629     (when (stringp from)
630       (let* ((parsed-address (gnus-extract-address-components from))
631              (name (or (car parsed-address) "Ham Sender"))
632              (net-address (car (cdr parsed-address))))
633         (gnus-message 5 "Adding address %s to BBDB" from)
634         (when (and net-address
635                    (not (bbdb-search-simple nil net-address)))
636           (bbdb-create-internal name nil net-address nil nil 
637                                 "ham sender added by spam.el")))))
638
639   (defun spam-BBDB-register-routine ()
640     (spam-generic-register-routine 
641      ;; spam function
642      nil
643      ;; ham function
644      (lambda (article)
645        (spam-enter-ham-BBDB (spam-fetch-field-from-fast article)))))
646
647   (defun spam-check-BBDB ()
648     "Mail from people in the BBDB is classified as ham or non-spam"
649     (let ((who (message-fetch-field "from")))
650       (when who
651         (setq who (cadr (gnus-extract-address-components who)))
652         (if (bbdb-search-simple nil who)
653             t 
654           (if spam-use-BBDB-exclusive
655               spam-split-group
656             nil))))))
657
658   (file-error (progn
659                 (defalias 'bbdb-search-simple 'ignore)
660                 (defalias 'spam-check-BBDB 'ignore)
661                 (defalias 'spam-BBDB-register-routine 'ignore)
662                 (defalias 'spam-enter-ham-BBDB 'ignore)
663                 (defalias 'bbdb-create-internal 'ignore)
664                 (defalias 'bbdb-records 'ignore))))
665
666 \f
667 ;;;; ifile
668
669 ;;; check the ifile backend; return nil if the mail was NOT classified
670 ;;; as spam
671
672 (defun spam-get-ifile-database-parameter ()
673   "Get the command-line parameter for ifile's database from spam-ifile-database-path."
674   (if spam-ifile-database-path
675       (format "--db-file=%s" spam-ifile-database-path)
676     nil))
677     
678 (defun spam-check-ifile ()
679   "Check the ifile backend for the classification of this message"
680   (let ((article-buffer-name (buffer-name)) 
681         category return)
682     (with-temp-buffer
683       (let ((temp-buffer-name (buffer-name))
684             (db-param (spam-get-ifile-database-parameter)))
685         (save-excursion
686           (set-buffer article-buffer-name)
687           (if db-param
688               (call-process-region (point-min) (point-max) spam-ifile-path
689                                    nil temp-buffer-name nil "-q" "-c" db-param)
690             (call-process-region (point-min) (point-max) spam-ifile-path
691                                  nil temp-buffer-name nil "-q" "-c")))
692         (goto-char (point-min))
693         (if (not (eobp))
694             (setq category (buffer-substring (point) (spam-point-at-eol))))
695         (when (not (zerop (length category))) ; we need a category here
696           (if spam-ifile-all-categories
697               (setq return category)
698             ;; else, if spam-ifile-all-categories is not set...
699             (when (string-equal spam-ifile-spam-category category)
700               (setq return spam-split-group))))))
701     return))
702
703 (defun spam-ifile-register-with-ifile (article-string category)
704   "Register an article, given as a string, with a category.
705 Uses `gnus-newsgroup-name' if category is nil (for ham registration)."
706   (when (stringp article-string)
707     (let ((category (or category gnus-newsgroup-name))
708           (db-param (spam-get-ifile-database-parameter)))
709       (with-temp-buffer
710         (insert-string article-string)
711         (if db-param
712             (call-process-region (point-min) (point-max) spam-ifile-path 
713                                  nil nil nil 
714                                  "-h" "-i" category db-param)
715           (call-process-region (point-min) (point-max) spam-ifile-path 
716                                nil nil nil 
717                                "-h" "-i" category))))))
718
719 (defun spam-ifile-register-spam-routine ()
720   (spam-generic-register-routine 
721    (lambda (article)
722      (spam-ifile-register-with-ifile 
723       (spam-get-article-as-string article) spam-ifile-spam-category))
724    nil))
725
726 (defun spam-ifile-register-ham-routine ()
727   (spam-generic-register-routine 
728    nil
729    (lambda (article)
730      (spam-ifile-register-with-ifile 
731       (spam-get-article-as-string article) spam-ifile-ham-category))))
732
733 \f
734 ;;;; spam-stat
735
736 (condition-case nil
737     (progn
738       (let ((spam-stat-install-hooks nil))
739         (require 'spam-stat))
740       
741       (defun spam-check-stat ()
742         "Check the spam-stat backend for the classification of this message"
743         (let ((spam-stat-split-fancy-spam-group spam-split-group) ; override
744               (spam-stat-buffer (buffer-name)) ; stat the current buffer
745               category return)
746           (spam-stat-split-fancy)))
747
748       (defun spam-stat-register-spam-routine ()
749         (spam-generic-register-routine 
750          (lambda (article)
751            (let ((article-string (spam-get-article-as-string article)))
752              (with-temp-buffer
753                (insert-string article-string)
754                (spam-stat-buffer-is-spam))))
755          nil)
756         (spam-stat-save))
757
758       (defun spam-stat-register-ham-routine ()
759         (spam-generic-register-routine 
760          nil
761          (lambda (article)
762            (let ((article-string (spam-get-article-as-string article)))
763              (with-temp-buffer
764                (insert-string article-string)
765                (spam-stat-buffer-is-non-spam)))))
766         (spam-stat-save)))
767
768   (file-error (progn
769                 (defalias 'spam-stat-register-ham-routine 'ignore)
770                 (defalias 'spam-stat-register-spam-routine 'ignore)
771                 (defalias 'spam-stat-buffer-is-spam 'ignore)
772                 (defalias 'spam-stat-buffer-is-non-spam 'ignore)
773                 (defalias 'spam-stat-split-fancy 'ignore)
774                 (defalias 'spam-stat-load 'ignore)
775                 (defalias 'spam-stat-save 'ignore)
776                 (defalias 'spam-check-stat 'ignore))))
777
778 \f
779
780 ;;;; Blacklists and whitelists.
781
782 (defvar spam-whitelist-cache nil)
783 (defvar spam-blacklist-cache nil)
784
785 (defun spam-enter-whitelist (address)
786   "Enter ADDRESS into the whitelist."
787   (interactive "sAddress: ")
788   (spam-enter-list address spam-whitelist)
789   (setq spam-whitelist-cache nil))
790
791 (defun spam-enter-blacklist (address)
792   "Enter ADDRESS into the blacklist."
793   (interactive "sAddress: ")
794   (spam-enter-list address spam-blacklist)
795   (setq spam-blacklist-cache nil))
796
797 (defun spam-enter-list (address file)
798   "Enter ADDRESS into the given FILE, either the whitelist or the blacklist."
799   (unless (file-exists-p (file-name-directory file))
800     (make-directory (file-name-directory file) t))
801   (save-excursion
802     (set-buffer
803      (find-file-noselect file))
804     (goto-char (point-max))
805     (unless (bobp)
806       (insert "\n"))
807     (insert address "\n")
808     (save-buffer)))
809
810 ;;; returns t if the sender is in the whitelist, nil or spam-split-group otherwise
811 (defun spam-check-whitelist ()
812   ;; FIXME!  Should it detect when file timestamps change?
813   (unless spam-whitelist-cache
814     (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
815   (if (spam-from-listed-p spam-whitelist-cache) 
816       t
817     (if spam-use-whitelist-exclusive
818         spam-split-group
819       nil)))
820
821 (defun spam-check-blacklist ()
822   ;; FIXME!  Should it detect when file timestamps change?
823   (unless spam-blacklist-cache
824     (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
825   (and (spam-from-listed-p spam-blacklist-cache) spam-split-group))
826
827 (defun spam-parse-list (file)
828   (when (file-readable-p file)
829     (let (contents address)
830       (with-temp-buffer
831         (insert-file-contents file)
832         (while (not (eobp))
833           (setq address (buffer-substring (point) (spam-point-at-eol)))
834           (forward-line 1)
835           (unless (zerop (length address))
836             (setq address (regexp-quote address))
837             (while (string-match "\\\\\\*" address)
838               (setq address (replace-match ".*" t t address)))
839             (push address contents))))
840       (nreverse contents))))
841
842 (defun spam-from-listed-p (cache)
843   (let ((from (message-fetch-field "from"))
844         found)
845     (while cache
846       (when (string-match (pop cache) from)
847         (setq found t
848               cache nil)))
849     found))
850
851 (defun spam-blacklist-register-routine ()
852   (spam-generic-register-routine 
853    ;; the spam function
854    (lambda (article)
855      (let ((from (spam-fetch-field-from-fast article)))
856        (when (stringp from)
857            (spam-enter-blacklist from))))
858    ;; the ham function
859    nil))
860
861 (defun spam-whitelist-register-routine ()
862   (spam-generic-register-routine 
863    ;; the spam function
864    nil 
865    ;; the ham function
866    (lambda (article)
867      (let ((from (spam-fetch-field-from-fast article)))
868        (when (stringp from)
869            (spam-enter-whitelist from))))))
870
871 \f
872 ;;;; Bogofilter
873
874 (defun spam-check-bogofilter-headers (&optional score)
875   (let ((header (message-fetch-field spam-bogofilter-header)))
876       (when (and header
877                  (string-match spam-bogofilter-bogosity-positive-spam-header
878                                header))
879           (if score
880               (when (string-match "spamicity=\\([0-9.]+\\)" header)
881                 (match-string 1 header))
882             spam-split-group))))
883
884 ;; return something sensible if the score can't be determined
885 (defun spam-bogofilter-score ()
886   "Get the Bogofilter spamicity score"
887   (interactive)
888   (save-window-excursion
889     (gnus-summary-show-article t)
890     (set-buffer gnus-article-buffer)
891     (let ((score (spam-check-bogofilter t)))
892       (message "Spamicity score %s" score)
893       (or score "0"))))
894
895 (defun spam-check-bogofilter (&optional score)
896   "Check the Bogofilter backend for the classification of this message"
897   (let ((article-buffer-name (buffer-name)) 
898         return)
899     (with-temp-buffer
900       (let ((temp-buffer-name (buffer-name)))
901         (save-excursion
902           (set-buffer article-buffer-name)
903           (if spam-bogofilter-database-directory
904               (call-process-region (point-min) (point-max) 
905                                    spam-bogofilter-path
906                                    nil temp-buffer-name nil "-v"
907                                    "-d" spam-bogofilter-database-directory)
908             (call-process-region (point-min) (point-max) spam-bogofilter-path
909                                  nil temp-buffer-name nil "-v")))
910         (setq return (spam-check-bogofilter-headers score))))
911     return))
912
913 (defun spam-bogofilter-register-with-bogofilter (article-string spam)
914   "Register an article, given as a string, as spam or non-spam."
915   (when (stringp article-string)
916     (let ((switch (if spam "-s" "-n")))
917       (with-temp-buffer
918         (insert-string article-string)
919         (if spam-bogofilter-database-directory
920             (call-process-region (point-min) (point-max) 
921                                  spam-bogofilter-path
922                                  nil nil nil "-v" switch
923                                  "-d" spam-bogofilter-database-directory)
924           (call-process-region (point-min) (point-max) spam-bogofilter-path
925                                nil nil nil "-v" switch))))))
926
927 (defun spam-bogofilter-register-spam-routine ()
928   (spam-generic-register-routine 
929    (lambda (article)
930      (spam-bogofilter-register-with-bogofilter
931       (spam-get-article-as-string article) t))
932    nil))
933
934 (defun spam-bogofilter-register-ham-routine ()
935   (spam-generic-register-routine 
936    nil
937    (lambda (article)
938      (spam-bogofilter-register-with-bogofilter
939       (spam-get-article-as-string article) nil))))
940
941 (provide 'spam)
942
943 ;;; spam.el ends here.