* netrc.el: autoload password-read
[gnus] / lisp / spam.el
1 ;;; spam.el --- Identifying spam
2 ;; Copyright (C) 2002, 2003, 2004 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 ;; TODO: spam scores, detection of spam in newsgroups, cross-server splitting,
36 ;; remote processing, training through files
37
38 ;;; Code:
39
40 (eval-when-compile (require 'cl))
41
42 (require 'gnus-sum)
43
44 (require 'gnus-uu)                      ; because of key prefix issues
45 ;;; for the definitions of group content classification and spam processors
46 (require 'gnus)
47 (require 'message)              ;for the message-fetch-field functions
48
49 ;; for nnimap-split-download-body-default
50 (eval-when-compile (require 'nnimap))
51
52 ;; autoload query-dig
53 (eval-and-compile
54   (autoload 'query-dig "dig"))
55
56 ;; autoload spam-report
57 (eval-and-compile
58   (autoload 'spam-report-gmane "spam-report"))
59
60 ;; autoload gnus-registry
61 (eval-and-compile
62   (autoload 'gnus-registry-group-count "gnus-registry")
63   (autoload 'gnus-registry-add-group "gnus-registry")
64   (autoload 'gnus-registry-store-extra-entry "gnus-registry")
65   (autoload 'gnus-registry-fetch-extra "gnus-registry"))
66
67 ;; autoload query-dns
68 (eval-and-compile
69   (autoload 'query-dns "dns"))
70
71 ;;; Main parameters.
72
73 (defgroup spam nil
74   "Spam configuration.")
75
76 (defcustom spam-directory "~/News/spam/"
77   "Directory for spam whitelists and blacklists."
78   :type 'directory
79   :group 'spam)
80
81 (defcustom spam-move-spam-nonspam-groups-only t
82   "Whether spam should be moved in non-spam groups only.
83 When t, only ham and unclassified groups will have their spam moved
84 to the spam-process-destination.  When nil, spam will also be moved from
85 spam groups."
86   :type 'boolean
87   :group 'spam)
88
89 (defcustom spam-process-ham-in-nonham-groups nil
90   "Whether ham should be processed in non-ham groups."
91   :type 'boolean
92   :group 'spam)
93
94 (defcustom spam-log-to-registry nil
95   "Whether spam/ham processing should be logged in the registry."
96   :type 'boolean
97   :group 'spam)
98
99 (defcustom spam-split-symbolic-return nil
100   "Whether `spam-split' should work with symbols or group names."
101   :type 'boolean
102   :group 'spam)
103
104 (defcustom spam-split-symbolic-return-positive nil
105   "Whether `spam-split' should ALWAYS work with symbols or group names.
106 Do not set this if you use `spam-split' in a fancy split
107   method."
108   :type 'boolean
109   :group 'spam)
110
111 (defcustom spam-process-ham-in-spam-groups nil
112   "Whether ham should be processed in spam groups."
113   :type 'boolean
114   :group 'spam)
115
116 (defcustom spam-mark-only-unseen-as-spam t
117   "Whether only unseen articles should be marked as spam in spam groups.
118 When nil, all unread articles in a spam group are marked as
119 spam.  Set this if you want to leave an article unread in a spam group
120 without losing it to the automatic spam-marking process."
121   :type 'boolean
122   :group 'spam)
123
124 (defcustom spam-mark-ham-unread-before-move-from-spam-group nil
125   "Whether ham should be marked unread before it's moved.
126 The article is moved out of a spam group according to ham-process-destination.
127 This variable is an official entry in the international Longest Variable Name
128 Competition."
129   :type 'boolean
130   :group 'spam)
131
132 (defcustom spam-disable-spam-split-during-ham-respool nil
133   "Whether `spam-split' should be ignored while resplitting ham in a process
134 destination.  This is useful to prevent ham from ending up in the same spam
135 group after the resplit.  Don't set this to t if you have spam-split as the
136 last rule in your split configuration."
137   :type 'boolean
138   :group 'spam)
139
140 (defcustom spam-autodetect-recheck-messages nil
141   "Should spam.el recheck all meessages when autodetecting?
142 Normally this is nil, so only unseen messages will be checked."
143   :type 'boolean
144   :group 'spam)
145
146 (defcustom spam-whitelist (expand-file-name "whitelist" spam-directory)
147   "The location of the whitelist.
148 The file format is one regular expression per line.
149 The regular expression is matched against the address."
150   :type 'file
151   :group 'spam)
152
153 (defcustom spam-blacklist (expand-file-name "blacklist" spam-directory)
154   "The location of the blacklist.
155 The file format is one regular expression per line.
156 The regular expression is matched against the address."
157   :type 'file
158   :group 'spam)
159
160 (defcustom spam-use-dig t
161   "Whether `query-dig' should be used instead of `query-dns'."
162   :type 'boolean
163   :group 'spam)
164
165 (defcustom spam-use-blacklist nil
166   "Whether the blacklist should be used by `spam-split'."
167   :type 'boolean
168   :group 'spam)
169
170 (defcustom spam-blacklist-ignored-regexes nil
171   "Regular expressions that the blacklist should ignore."
172   :type '(repeat (regexp :tag "Regular expression to ignore when blacklisting"))
173   :group 'spam)
174
175 (defcustom spam-use-whitelist nil
176   "Whether the whitelist should be used by `spam-split'."
177   :type 'boolean
178   :group 'spam)
179
180 (defcustom spam-use-whitelist-exclusive nil
181   "Whether whitelist-exclusive should be used by `spam-split'.
182 Exclusive whitelisting means that all messages from senders not in the whitelist
183 are considered spam."
184   :type 'boolean
185   :group 'spam)
186
187 (defcustom spam-use-blackholes nil
188   "Whether blackholes should be used by `spam-split'."
189   :type 'boolean
190   :group 'spam)
191
192 (defcustom spam-use-hashcash nil
193   "Whether hashcash payments should be detected by `spam-split'."
194   :type 'boolean
195   :group 'spam)
196
197 (defcustom spam-use-regex-headers nil
198   "Whether a header regular expression match should be used by `spam-split'.
199 Also see the variables `spam-regex-headers-spam' and `spam-regex-headers-ham'."
200   :type 'boolean
201   :group 'spam)
202
203 (defcustom spam-use-regex-body nil
204   "Whether a body regular expression match should be used by `spam-split'.
205 Also see the variables `spam-regex-body-spam' and `spam-regex-body-ham'."
206   :type 'boolean
207   :group 'spam)
208
209 (defcustom spam-use-bogofilter-headers nil
210   "Whether bogofilter headers should be used by `spam-split'.
211 Enable this if you pre-process messages with Bogofilter BEFORE Gnus sees them."
212   :type 'boolean
213   :group 'spam)
214
215 (defcustom spam-use-bogofilter nil
216   "Whether bogofilter should be invoked by `spam-split'.
217 Enable this if you want Gnus to invoke Bogofilter on new messages."
218   :type 'boolean
219   :group 'spam)
220
221 (defcustom spam-use-BBDB nil
222   "Whether BBDB should be used by `spam-split'."
223   :type 'boolean
224   :group 'spam)
225
226 (defcustom spam-use-BBDB-exclusive nil
227   "Whether BBDB-exclusive should be used by `spam-split'.
228 Exclusive BBDB means that all messages from senders not in the BBDB are
229 considered spam."
230   :type 'boolean
231   :group 'spam)
232
233 (defcustom spam-use-ifile nil
234   "Whether ifile should be used by `spam-split'."
235   :type 'boolean
236   :group 'spam)
237
238 (defcustom spam-use-stat nil
239   "Whether `spam-stat' should be used by `spam-split'."
240   :type 'boolean
241   :group 'spam)
242
243 (defcustom spam-use-spamoracle nil
244   "Whether spamoracle should be used by `spam-split'."
245   :type 'boolean
246   :group 'spam)
247
248 (defcustom spam-install-hooks (or
249                                spam-use-dig
250                                spam-use-blacklist
251                                spam-use-whitelist
252                                spam-use-whitelist-exclusive
253                                spam-use-blackholes
254                                spam-use-hashcash
255                                spam-use-regex-headers
256                                spam-use-regex-body
257                                spam-use-bogofilter-headers
258                                spam-use-bogofilter
259                                spam-use-BBDB
260                                spam-use-BBDB-exclusive
261                                spam-use-ifile
262                                spam-use-stat
263                                spam-use-spamoracle)
264   "Whether the spam hooks should be installed.
265 Default to t if one of the spam-use-* variables is set."
266   :group 'spam
267   :type 'boolean)
268
269 (defcustom spam-split-group "spam"
270   "Group name where incoming spam should be put by `spam-split'."
271   :type 'string
272   :group 'spam)
273
274 ;;; TODO: deprecate this variable, it's confusing since it's a list of strings,
275 ;;; not regular expressions
276 (defcustom spam-junk-mailgroups (cons
277                                  spam-split-group
278                                  '("mail.junk" "poste.pourriel"))
279   "Mailgroups with spam contents.
280 All unmarked article in such group receive the spam mark on group entry."
281   :type '(repeat (string :tag "Group"))
282   :group 'spam)
283
284 (defcustom spam-blackhole-servers '("bl.spamcop.net" "relays.ordb.org"
285                                     "dev.null.dk" "relays.visi.com")
286   "List of blackhole servers."
287   :type '(repeat (string :tag "Server"))
288   :group 'spam)
289
290 (defcustom spam-blackhole-good-server-regex nil
291   "String matching IP addresses that should not be checked in the blackholes."
292   :type '(radio (const nil)
293                 (regexp :format "%t: %v\n" :size 0))
294   :group 'spam)
295
296 (defcustom spam-face 'gnus-splash-face
297   "Face for spam-marked articles."
298   :type 'face
299   :group 'spam)
300
301 (defcustom spam-regex-headers-spam '("^X-Spam-Flag: YES")
302   "Regular expression for positive header spam matches."
303   :type '(repeat (regexp :tag "Regular expression to match spam header"))
304   :group 'spam)
305
306 (defcustom spam-regex-headers-ham '("^X-Spam-Flag: NO")
307   "Regular expression for positive header ham matches."
308   :type '(repeat (regexp :tag "Regular expression to match ham header"))
309   :group 'spam)
310
311 (defcustom spam-regex-body-spam '()
312   "Regular expression for positive body spam matches."
313   :type '(repeat (regexp :tag "Regular expression to match spam body"))
314   :group 'spam)
315
316 (defcustom spam-regex-body-ham '()
317   "Regular expression for positive body ham matches."
318   :type '(repeat (regexp :tag "Regular expression to match ham body"))
319   :group 'spam)
320
321 (defgroup spam-ifile nil
322   "Spam ifile configuration."
323   :group 'spam)
324
325 (defcustom spam-ifile-path (executable-find "ifile")
326   "File path of the ifile executable program."
327   :type '(choice (file :tag "Location of ifile")
328                  (const :tag "ifile is not installed"))
329   :group 'spam-ifile)
330
331 (defcustom spam-ifile-database-path nil
332   "File path of the ifile database."
333   :type '(choice (file :tag "Location of the ifile database")
334                  (const :tag "Use the default"))
335   :group 'spam-ifile)
336
337 (defcustom spam-ifile-spam-category "spam"
338   "Name of the spam ifile category."
339   :type 'string
340   :group 'spam-ifile)
341
342 (defcustom spam-ifile-ham-category nil
343   "Name of the ham ifile category.
344 If nil, the current group name will be used."
345   :type '(choice (string :tag "Use a fixed category")
346                  (const :tag "Use the current group name"))
347   :group 'spam-ifile)
348
349 (defcustom spam-ifile-all-categories nil
350   "Whether the ifile check will return all categories, or just spam.
351 Set this to t if you want to use the `spam-split' invocation of ifile as
352 your main source of newsgroup names."
353   :type 'boolean
354   :group 'spam-ifile)
355
356 (defgroup spam-bogofilter nil
357   "Spam bogofilter configuration."
358   :group 'spam)
359
360 (defcustom spam-bogofilter-path (executable-find "bogofilter")
361   "File path of the Bogofilter executable program."
362   :type '(choice (file :tag "Location of bogofilter")
363                  (const :tag "Bogofilter is not installed"))
364   :group 'spam-bogofilter)
365
366 (defcustom spam-bogofilter-header "X-Bogosity"
367   "The header that Bogofilter inserts in messages."
368   :type 'string
369   :group 'spam-bogofilter)
370
371 (defcustom spam-bogofilter-spam-switch "-s"
372   "The switch that Bogofilter uses to register spam messages."
373   :type 'string
374   :group 'spam-bogofilter)
375
376 (defcustom spam-bogofilter-ham-switch "-n"
377   "The switch that Bogofilter uses to register ham messages."
378   :type 'string
379   :group 'spam-bogofilter)
380
381 (defcustom spam-bogofilter-spam-strong-switch "-S"
382   "The switch that Bogofilter uses to unregister ham messages."
383   :type 'string
384   :group 'spam-bogofilter)
385
386 (defcustom spam-bogofilter-ham-strong-switch "-N"
387   "The switch that Bogofilter uses to unregister spam messages."
388   :type 'string
389   :group 'spam-bogofilter)
390
391 (defcustom spam-bogofilter-bogosity-positive-spam-header "^\\(Yes\\|Spam\\)"
392   "The regex on `spam-bogofilter-header' for positive spam identification."
393   :type 'regexp
394   :group 'spam-bogofilter)
395
396 (defcustom spam-bogofilter-database-directory nil
397   "Directory path of the Bogofilter databases."
398   :type '(choice (directory
399                   :tag "Location of the Bogofilter database directory")
400                  (const :tag "Use the default"))
401   :group 'spam-bogofilter)
402
403 (defgroup spam-spamoracle nil
404   "Spam spamoracle configuration."
405   :group 'spam)
406
407 (defcustom spam-spamoracle-database nil
408   "Location of spamoracle database file. When nil, use the default
409 spamoracle database."
410   :type '(choice (directory :tag "Location of spamoracle database file.")
411                  (const :tag "Use the default"))
412   :group 'spam-spamoracle)
413
414 (defcustom spam-spamoracle-binary (executable-find "spamoracle")
415   "Location of the spamoracle binary."
416   :type '(choice (directory :tag "Location of the spamoracle binary")
417                  (const :tag "Use the default"))
418   :group 'spam-spamoracle)
419
420 ;;; Key bindings for spam control.
421
422 (gnus-define-keys gnus-summary-mode-map
423   "St" spam-bogofilter-score
424   "Sx" gnus-summary-mark-as-spam
425   "Mst" spam-bogofilter-score
426   "Msx" gnus-summary-mark-as-spam
427   "\M-d" gnus-summary-mark-as-spam)
428
429 (defvar spam-old-ham-articles nil
430   "List of old ham articles, generated when a group is entered.")
431
432 (defvar spam-old-spam-articles nil
433   "List of old spam articles, generated when a group is entered.")
434
435 (defvar spam-split-disabled nil
436   "If non-nil, `spam-split' is disabled, and always returns nil.")
437
438 (defvar spam-split-last-successful-check nil
439   "`spam-split' will set this to nil or a spam-use-XYZ check if it
440   finds ham or spam.")
441
442 ;; convenience functions
443 (defun spam-xor (a b)
444   "Logical exclusive `or'."
445   (and (or a b) (not (and a b))))
446
447 (defun spam-group-ham-mark-p (group mark &optional spam)
448   (when (stringp group)
449     (let* ((marks (spam-group-ham-marks group spam))
450            (marks (if (symbolp mark)
451                       marks
452                     (mapcar 'symbol-value marks))))
453       (memq mark marks))))
454
455 (defun spam-group-spam-mark-p (group mark)
456   (spam-group-ham-mark-p group mark t))
457
458 (defun spam-group-ham-marks (group &optional spam)
459   (when (stringp group)
460     (let* ((marks (if spam
461                       (gnus-parameter-spam-marks group)
462                     (gnus-parameter-ham-marks group)))
463            (marks (car marks))
464            (marks (if (listp (car marks)) (car marks) marks)))
465       marks)))
466
467 (defun spam-group-spam-marks (group)
468   (spam-group-ham-marks group t))
469
470 (defun spam-group-spam-contents-p (group)
471   (if (stringp group)
472       (or (member group spam-junk-mailgroups)
473           (memq 'gnus-group-spam-classification-spam
474                 (gnus-parameter-spam-contents group)))
475     nil))
476
477 (defun spam-group-ham-contents-p (group)
478   (if (stringp group)
479       (memq 'gnus-group-spam-classification-ham
480             (gnus-parameter-spam-contents group))
481     nil))
482
483 (defvar spam-list-of-processors
484   '((gnus-group-spam-exit-processor-report-gmane spam spam-use-gmane)
485     (gnus-group-spam-exit-processor-bogofilter   spam spam-use-bogofilter)
486     (gnus-group-spam-exit-processor-blacklist    spam spam-use-blacklist)
487     (gnus-group-spam-exit-processor-ifile        spam spam-use-ifile)
488     (gnus-group-spam-exit-processor-stat         spam spam-use-stat)
489     (gnus-group-spam-exit-processor-spamoracle   spam spam-use-spamoracle)
490     (gnus-group-ham-exit-processor-ifile         ham spam-use-ifile)
491     (gnus-group-ham-exit-processor-bogofilter    ham spam-use-bogofilter)
492     (gnus-group-ham-exit-processor-stat          ham spam-use-stat)
493     (gnus-group-ham-exit-processor-whitelist     ham spam-use-whitelist)
494     (gnus-group-ham-exit-processor-BBDB          ham spam-use-BBDB)
495     (gnus-group-ham-exit-processor-copy          ham spam-use-ham-copy)
496     (gnus-group-ham-exit-processor-spamoracle    ham spam-use-spamoracle))
497   "The spam-list-of-processors list contains pairs associating a
498 ham/spam exit processor variable with a classification and a
499 spam-use-* variable.")
500
501 (defun spam-group-processor-p (group processor)
502   (if (and (stringp group)
503            (symbolp processor))
504       (or (member processor (nth 0 (gnus-parameter-spam-process group)))
505           (spam-group-processor-multiple-p
506            group
507            (cdr-safe (assoc processor spam-list-of-processors))))
508     nil))
509
510 (defun spam-group-processor-multiple-p (group processor-info)
511   (let* ((classification (nth 0 processor-info))
512          (check (nth 1 processor-info))
513          (parameters (nth 0 (gnus-parameter-spam-process group)))
514          found)
515     (dolist (parameter parameters)
516       (when (and (null found)
517                  (listp parameter)
518                  (eq classification (nth 0 parameter))
519                  (eq check (nth 1 parameter)))
520         (setq found t)))
521     found))
522
523 (defun spam-group-spam-processor-report-gmane-p (group)
524   (spam-group-processor-p group 'gnus-group-spam-exit-processor-report-gmane))
525
526 (defun spam-group-spam-processor-bogofilter-p (group)
527   (spam-group-processor-p group 'gnus-group-spam-exit-processor-bogofilter))
528
529 (defun spam-group-spam-processor-blacklist-p (group)
530   (spam-group-processor-p group 'gnus-group-spam-exit-processor-blacklist))
531
532 (defun spam-group-spam-processor-ifile-p (group)
533   (spam-group-processor-p group 'gnus-group-spam-exit-processor-ifile))
534
535 (defun spam-group-ham-processor-ifile-p (group)
536   (spam-group-processor-p group 'gnus-group-ham-exit-processor-ifile))
537
538 (defun spam-group-spam-processor-spamoracle-p (group)
539   (spam-group-processor-p group 'gnus-group-spam-exit-processor-spamoracle))
540
541 (defun spam-group-ham-processor-bogofilter-p (group)
542   (spam-group-processor-p group 'gnus-group-ham-exit-processor-bogofilter))
543
544 (defun spam-group-spam-processor-stat-p (group)
545   (spam-group-processor-p group 'gnus-group-spam-exit-processor-stat))
546
547 (defun spam-group-ham-processor-stat-p (group)
548   (spam-group-processor-p group 'gnus-group-ham-exit-processor-stat))
549
550 (defun spam-group-ham-processor-whitelist-p (group)
551   (spam-group-processor-p group 'gnus-group-ham-exit-processor-whitelist))
552
553 (defun spam-group-ham-processor-BBDB-p (group)
554   (spam-group-processor-p group 'gnus-group-ham-exit-processor-BBDB))
555
556 (defun spam-group-ham-processor-copy-p (group)
557   (spam-group-processor-p group 'gnus-group-ham-exit-processor-copy))
558
559 (defun spam-group-ham-processor-spamoracle-p (group)
560   (spam-group-processor-p group 'gnus-group-ham-exit-processor-spamoracle))
561
562 ;;; Summary entry and exit processing.
563
564 (defun spam-summary-prepare ()
565   (setq spam-old-ham-articles
566         (spam-list-articles gnus-newsgroup-articles 'ham))
567   (setq spam-old-spam-articles
568         (spam-list-articles gnus-newsgroup-articles 'spam))
569   (spam-mark-junk-as-spam-routine))
570
571 ;; The spam processors are invoked for any group, spam or ham or neither
572 (defun spam-summary-prepare-exit ()
573   (unless gnus-group-is-exiting-without-update-p
574     (gnus-message 6 "Exiting summary buffer and applying spam rules")
575
576     ;; first of all, unregister any articles that are no longer ham or spam
577     ;; we have to iterate over the processors, or else we'll be too slow
578     (dolist (classification '(spam ham))
579       (let* ((old-articles (if (eq classification 'spam)
580                                spam-old-spam-articles
581                              spam-old-ham-articles))
582              (new-articles (spam-list-articles
583                             gnus-newsgroup-articles
584                             classification))
585              (changed-articles (gnus-set-difference old-articles new-articles)))
586         ;; now that we have the changed articles, we go through the processors
587         (dolist (processor-param spam-list-of-processors)
588           (let ((processor (nth 0 processor-param))
589                 (processor-classification (nth 1 processor-param))
590                 (check (nth 2 processor-param))
591                 unregister-list)
592             (dolist (article changed-articles)
593               (let ((id (spam-fetch-field-message-id-fast article)))
594                 (when (spam-log-unregistration-needed-p
595                        id 'process classification check)
596                   (push article unregister-list))))
597             ;; call spam-register-routine with specific articles to unregister,
598             ;; when there are articles to unregister and the check is enabled
599             (when (and unregister-list (symbol-value check))
600               (spam-register-routine classification check t unregister-list))))))
601
602     ;; find all the spam processors applicable to this group
603     (dolist (processor-param spam-list-of-processors)
604       (let ((processor (nth 0 processor-param))
605             (classification (nth 1 processor-param))
606             (check (nth 2 processor-param)))
607         (when (and (eq 'spam classification)
608                    (spam-group-processor-p gnus-newsgroup-name processor))
609           (spam-register-routine classification check))))
610
611     (if spam-move-spam-nonspam-groups-only
612         (when (not (spam-group-spam-contents-p gnus-newsgroup-name))
613           (spam-mark-spam-as-expired-and-move-routine
614            (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
615       (gnus-message 5 "Marking spam as expired and moving it to %s"
616                     gnus-newsgroup-name)
617       (spam-mark-spam-as-expired-and-move-routine
618        (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
619
620     ;; now we redo spam-mark-spam-as-expired-and-move-routine to only
621     ;; expire spam, in case the above did not expire them
622     (gnus-message 5 "Marking spam as expired without moving it")
623     (spam-mark-spam-as-expired-and-move-routine nil)
624
625     (when (or (spam-group-ham-contents-p gnus-newsgroup-name)
626               (and (spam-group-spam-contents-p gnus-newsgroup-name)
627                    spam-process-ham-in-spam-groups)
628               spam-process-ham-in-nonham-groups)
629       ;; find all the ham processors applicable to this group
630       (dolist (processor-param spam-list-of-processors)
631         (let ((processor (nth 0 processor-param))
632               (classification (nth 1 processor-param))
633               (check (nth 2 processor-param)))
634           (when (and (eq 'ham classification)
635                      (spam-group-processor-p gnus-newsgroup-name processor))
636             (spam-register-routine classification check)))))
637
638     (when (spam-group-ham-processor-copy-p gnus-newsgroup-name)
639       (gnus-message 5 "Copying ham")
640       (spam-ham-copy-routine
641        (gnus-parameter-ham-process-destination gnus-newsgroup-name)))
642
643     ;; now move all ham articles out of spam groups
644     (when (spam-group-spam-contents-p gnus-newsgroup-name)
645       (gnus-message 5 "Moving ham messages from spam group")
646       (spam-ham-move-routine
647        (gnus-parameter-ham-process-destination gnus-newsgroup-name))))
648
649   (setq spam-old-ham-articles nil)
650   (setq spam-old-spam-articles nil))
651
652 (defun spam-mark-junk-as-spam-routine ()
653   ;; check the global list of group names spam-junk-mailgroups and the
654   ;; group parameters
655   (when (spam-group-spam-contents-p gnus-newsgroup-name)
656     (gnus-message 5 "Marking %s articles as spam"
657                   (if spam-mark-only-unseen-as-spam
658                       "unseen"
659                     "unread"))
660     (let ((articles (if spam-mark-only-unseen-as-spam
661                         gnus-newsgroup-unseen
662                       gnus-newsgroup-unreads)))
663       (dolist (article articles)
664         (gnus-summary-mark-article article gnus-spam-mark)))))
665
666 (defun spam-mark-spam-as-expired-and-move-routine (&rest groups)
667   (if (and (car-safe groups) (listp (car-safe groups)))
668       (apply 'spam-mark-spam-as-expired-and-move-routine (car groups))
669     (gnus-summary-kill-process-mark)
670     (let ((articles gnus-newsgroup-articles)
671           (backend-supports-deletions
672            (gnus-check-backend-function
673             'request-move-article gnus-newsgroup-name))
674           article tomove deletep)
675       (dolist (article articles)
676         (when (eq (gnus-summary-article-mark article) gnus-spam-mark)
677           (gnus-summary-mark-article article gnus-expirable-mark)
678           (push article tomove)))
679
680       ;; now do the actual copies
681       (dolist (group groups)
682         (when (and tomove
683                    (stringp group))
684           (dolist (article tomove)
685             (gnus-summary-set-process-mark article))
686           (when tomove
687             (if (or (not backend-supports-deletions)
688                     (> (length groups) 1))
689                 (progn
690                   (gnus-summary-copy-article nil group)
691                   (setq deletep t))
692               (gnus-summary-move-article nil group)))))
693
694       ;; now delete the articles, if there was a copy done, and the
695       ;; backend allows it
696       (when (and deletep backend-supports-deletions)
697         (dolist (article tomove)
698           (gnus-summary-set-process-mark article))
699         (when tomove
700           (let ((gnus-novice-user nil)) ; don't ask me if I'm sure
701             (gnus-summary-delete-article nil))))
702
703       (gnus-summary-yank-process-mark))))
704
705 (defun spam-ham-copy-or-move-routine (copy groups)
706   (gnus-summary-kill-process-mark)
707   (let ((todo (spam-list-articles gnus-newsgroup-articles 'ham))
708         (backend-supports-deletions
709          (gnus-check-backend-function
710           'request-move-article gnus-newsgroup-name))
711         (respool-method (gnus-find-method-for-group gnus-newsgroup-name))
712         article mark todo deletep respool)
713
714     (when (member 'respool groups)
715       (setq respool t)                  ; boolean for later
716       (setq groups '("fake"))) ; when respooling, groups are dynamic so fake it
717
718     ;; now do the actual move
719     (dolist (group groups)
720       (when (and todo (stringp group))
721         (dolist (article todo)
722           (when spam-mark-ham-unread-before-move-from-spam-group
723             (gnus-summary-mark-article article gnus-unread-mark))
724           (gnus-summary-set-process-mark article))
725
726         (if respool                        ; respooling is with a "fake" group
727             (let ((spam-split-disabled
728                    (or spam-split-disabled
729                        spam-disable-spam-split-during-ham-respool)))
730               (gnus-summary-respool-article nil respool-method))
731           (if (or (not backend-supports-deletions) ; else, we are not respooling
732                   (> (length groups) 1))
733               (progn                ; if copying, copy and set deletep
734                 (gnus-summary-copy-article nil group)
735                 (setq deletep t))
736             (gnus-summary-move-article nil group))))) ; else move articles
737
738     ;; now delete the articles, unless a) copy is t, and there was a copy done
739     ;;                                 b) a move was done to a single group
740     ;;                                 c) backend-supports-deletions is nil
741     (unless copy
742       (when (and deletep backend-supports-deletions)
743         (dolist (article todo)
744           (gnus-summary-set-process-mark article))
745         (when todo
746           (let ((gnus-novice-user nil)) ; don't ask me if I'm sure
747             (gnus-summary-delete-article nil))))))
748
749   (gnus-summary-yank-process-mark))
750
751 (defun spam-ham-copy-routine (&rest groups)
752   (if (and (car-safe groups) (listp (car-safe groups)))
753       (apply 'spam-ham-copy-routine (car groups))
754     (spam-ham-copy-or-move-routine t groups)))
755
756 (defun spam-ham-move-routine (&rest groups)
757   (if (and (car-safe groups) (listp (car-safe groups)))
758       (apply 'spam-ham-move-routine (car groups))
759     (spam-ham-copy-or-move-routine nil groups)))
760
761 (defun spam-get-article-as-string (article)
762   (let ((article-buffer (spam-get-article-as-buffer article))
763         article-string)
764     (when article-buffer
765       (save-window-excursion
766         (set-buffer article-buffer)
767         (setq article-string (buffer-string))))
768     article-string))
769
770 (defun spam-get-article-as-buffer (article)
771   (let ((article-buffer))
772     (when (numberp article)
773       (save-window-excursion
774         (gnus-summary-goto-subject article)
775         (gnus-summary-show-article t)
776         (setq article-buffer (get-buffer gnus-article-buffer))))
777     article-buffer))
778
779 ;; disabled for now
780 ;; (defun spam-get-article-as-filename (article)
781 ;;   (let ((article-filename))
782 ;;     (when (numberp article)
783 ;;       (nnml-possibly-change-directory
784 ;;        (gnus-group-real-name gnus-newsgroup-name))
785 ;;       (setq article-filename (expand-file-name
786 ;;                              (int-to-string article) nnml-current-directory)))
787 ;;     (if (file-exists-p article-filename)
788 ;;      article-filename
789 ;;       nil)))
790
791 (defun spam-fetch-field-from-fast (article)
792   "Fetch the `from' field quickly, using the internal gnus-data-list function"
793   (if (and (numberp article)
794            (assoc article (gnus-data-list nil)))
795       (mail-header-from
796        (gnus-data-header (assoc article (gnus-data-list nil))))
797     nil))
798
799 (defun spam-fetch-field-subject-fast (article)
800   "Fetch the `subject' field quickly, using the internal
801   gnus-data-list function"
802   (if (and (numberp article)
803            (assoc article (gnus-data-list nil)))
804       (mail-header-subject
805        (gnus-data-header (assoc article (gnus-data-list nil))))
806     nil))
807
808 (defun spam-fetch-field-message-id-fast (article)
809   "Fetch the `Message-ID' field quickly, using the internal
810   gnus-data-list function"
811   (if (and (numberp article)
812            (assoc article (gnus-data-list nil)))
813       (mail-header-message-id
814        (gnus-data-header (assoc article (gnus-data-list nil))))
815     nil))
816
817 \f
818 ;;;; Spam determination.
819
820 (defvar spam-list-of-checks
821   '((spam-use-blacklist          . spam-check-blacklist)
822     (spam-use-regex-headers      . spam-check-regex-headers)
823     (spam-use-regex-body         . spam-check-regex-body)
824     (spam-use-whitelist          . spam-check-whitelist)
825     (spam-use-BBDB               . spam-check-BBDB)
826     (spam-use-ifile              . spam-check-ifile)
827     (spam-use-spamoracle         . spam-check-spamoracle)
828     (spam-use-stat               . spam-check-stat)
829     (spam-use-blackholes         . spam-check-blackholes)
830     (spam-use-hashcash           . spam-check-hashcash)
831     (spam-use-bogofilter-headers . spam-check-bogofilter-headers)
832     (spam-use-bogofilter         . spam-check-bogofilter))
833   "The spam-list-of-checks list contains pairs associating a
834 parameter variable with a spam checking function.  If the
835 parameter variable is true, then the checking function is called,
836 and its value decides what happens.  Each individual check may
837 return nil, t, or a mailgroup name.  The value nil means that the
838 check does not yield a decision, and so, that further checks are
839 needed.  The value t means that the message is definitely not
840 spam, and that further spam checks should be inhibited.
841 Otherwise, a mailgroup name or the symbol 'spam (depending on
842 spam-split-symbolic-return) is returned where the mail should go,
843 and further checks are also inhibited.  The usual mailgroup name
844 is the value of `spam-split-group', meaning that the message is
845 definitely a spam.")
846
847 (defvar spam-list-of-statistical-checks
848   '(spam-use-ifile
849     spam-use-regex-body
850     spam-use-stat
851     spam-use-bogofilter
852     spam-use-spamoracle)
853   "The spam-list-of-statistical-checks list contains all the mail
854 splitters that need to have the full message body available.")
855
856 ;;;TODO: modify to invoke self with each check if invoked without specifics
857 (defun spam-split (&rest specific-checks)
858   "Split this message into the `spam' group if it is spam.
859 This function can be used as an entry in the variable `nnmail-split-fancy',
860 for example like this: (: spam-split).  It can take checks as
861 parameters.  A string as a parameter will set the
862 spam-split-group to that string.
863
864 See the Info node `(gnus)Fancy Mail Splitting' for more details."
865   (interactive)
866   (setq spam-split-last-successful-check nil)
867   (unless spam-split-disabled
868     (let ((spam-split-group-choice spam-split-group))
869       (dolist (check specific-checks)
870         (when (stringp check)
871           (setq spam-split-group-choice check)
872           (setq specific-checks (delq check specific-checks))))
873
874       (let ((spam-split-group spam-split-group-choice))
875         (save-excursion
876           (save-restriction
877             (dolist (check spam-list-of-statistical-checks)
878               (when (and (symbolp check) (symbol-value check))
879                 (widen)
880                 (gnus-message 8 "spam-split: widening the buffer (%s requires it)"
881                               (symbol-name check))
882                 (return)))
883             ;;   (progn (widen) (debug (buffer-string)))
884             (let ((list-of-checks spam-list-of-checks)
885                   decision)
886               (while (and list-of-checks (not decision))
887                 (let ((pair (pop list-of-checks)))
888                   (when (and (symbol-value (car pair))
889                              (or (null specific-checks)
890                                  (memq (car pair) specific-checks)))
891                     (gnus-message 5 "spam-split: calling the %s function"
892                                   (symbol-name (cdr pair)))
893                     (setq decision (funcall (cdr pair)))
894                     ;; if we got a decision at all, save the current check
895                     (when decision
896                       (setq spam-split-last-successful-check (car pair)))
897
898                     (when (eq decision 'spam)
899                       (if spam-split-symbolic-return
900                           (setq decision spam-split-group)
901                         (gnus-error
902                          5
903                          (format "spam-split got %s but %s is nil"
904                                  (symbol-name decision)
905                                  (symbol-name spam-split-symbolic-return))))))))
906               (if (eq decision t)
907                   (if spam-split-symbolic-return-positive 'ham nil)
908                 decision))))))))
909
910 (defun spam-find-spam ()
911   "This function will detect spam in the current newsgroup using spam-split."
912   (interactive)
913
914   (let* ((group gnus-newsgroup-name)
915          (autodetect (gnus-parameter-spam-autodetect group))
916          (methods (gnus-parameter-spam-autodetect-methods group))
917          (first-method (nth 0 methods)))
918   (when (and autodetect
919              (not (equal first-method 'none)))
920     (mapcar
921      (lambda (article)
922        (let ((id (spam-fetch-field-message-id-fast article))
923              (subject (spam-fetch-field-subject-fast article))
924              (sender (spam-fetch-field-from-fast article)))
925          (unless (and spam-log-to-registry
926                       (spam-log-registered-p id 'incoming))
927            (let* ((spam-split-symbolic-return t)
928                   (spam-split-symbolic-return-positive t)
929                   (split-return
930                    (with-temp-buffer
931                      (gnus-request-article-this-buffer
932                       article
933                       group)
934                      (if (or (null first-method)
935                              (equal first-method 'default))
936                          (spam-split)
937                        (apply 'spam-split methods)))))
938              (if (equal split-return 'spam)
939                  (gnus-summary-mark-article article gnus-spam-mark))
940
941              (when (and split-return spam-log-to-registry)
942                (when (zerop (gnus-registry-group-count id))
943                  (gnus-registry-add-group
944                   id group subject sender))
945
946                (spam-log-processing-to-registry
947                 id
948                 'incoming
949                 split-return
950                 spam-split-last-successful-check
951                 group))))))
952      (if spam-autodetect-recheck-messages
953          gnus-newsgroup-articles
954        gnus-newsgroup-unseen)))))
955
956 (defvar spam-registration-functions
957   ;; first the ham register, second the spam register function
958   ;; third the ham unregister, fourth the spam unregister function
959   '((spam-use-blacklist  nil
960                          spam-blacklist-register-routine
961                          nil
962                          spam-blacklist-unregister-routine)
963     (spam-use-whitelist  spam-whitelist-register-routine
964                          nil
965                          spam-whitelist-unregister-routine
966                          nil)
967     (spam-use-BBDB       spam-BBDB-register-routine
968                          nil
969                          spam-BBDB-unregister-routine
970                          nil)
971     (spam-use-ifile      spam-ifile-register-ham-routine
972                          spam-ifile-register-spam-routine
973                          spam-ifile-unregister-ham-routine
974                          spam-ifile-unregister-spam-routine)
975     (spam-use-spamoracle spam-spamoracle-learn-ham
976                          spam-spamoracle-learn-spam
977                          spam-spamoracle-unlearn-ham
978                          spam-spamoracle-unlearn-spam)
979     (spam-use-stat       spam-stat-register-ham-routine
980                          spam-stat-register-spam-routine
981                          spam-stat-unregister-ham-routine
982                          spam-stat-unregister-spam-routine)
983     ;; note that spam-use-gmane is not a legitimate check
984     (spam-use-gmane      nil
985                          spam-report-gmane-register-routine
986                          ;; does Gmane support unregistration?
987                          nil
988                          nil)
989     (spam-use-bogofilter spam-bogofilter-register-ham-routine
990                          spam-bogofilter-register-spam-routine
991                          spam-bogofilter-unregister-ham-routine
992                          spam-bogofilter-unregister-spam-routine))
993   "The spam-registration-functions list contains pairs
994 associating a parameter variable with the ham and spam
995 registration functions, and the ham and spam unregistration
996 functions")
997
998 (defun spam-classification-valid-p (classification)
999   (or  (eq classification 'spam)
1000        (eq classification 'ham)))
1001
1002 (defun spam-process-type-valid-p (process-type)
1003   (or  (eq process-type 'incoming)
1004        (eq process-type 'process)))
1005
1006 (defun spam-registration-check-valid-p (check)
1007   (assoc check spam-registration-functions))
1008
1009 (defun spam-unregistration-check-valid-p (check)
1010   (assoc check spam-registration-functions))
1011
1012 (defun spam-registration-function (classification check)
1013   (let ((flist (cdr-safe (assoc check spam-registration-functions))))
1014     (if (eq classification 'spam)
1015         (nth 1 flist)
1016       (nth 0 flist))))
1017
1018 (defun spam-unregistration-function (classification check)
1019   (let ((flist (cdr-safe (assoc check spam-registration-functions))))
1020     (if (eq classification 'spam)
1021         (nth 3 flist)
1022       (nth 2 flist))))
1023
1024 (defun spam-list-articles (articles classification)
1025   (let ((mark-check (if (eq classification 'spam)
1026                         'spam-group-spam-mark-p
1027                       'spam-group-ham-mark-p))
1028         list mark-cache-yes mark-cache-no)
1029     (dolist (article articles)
1030       (let ((mark (gnus-summary-article-mark article)))
1031         (unless (memq mark mark-cache-no)
1032           (if (memq mark mark-cache-yes)
1033               (push article list)
1034             ;; else, we have to actually check the mark
1035             (if (funcall mark-check
1036                          gnus-newsgroup-name
1037                          mark)
1038                 (progn
1039                   (push article list)
1040                   (push mark mark-cache-yes))
1041               (push mark mark-cache-no))))))
1042     list))
1043
1044 (defun spam-register-routine (classification
1045                               check
1046                               &optional unregister
1047                               specific-articles)
1048   (when (and (spam-classification-valid-p classification)
1049              (spam-registration-check-valid-p check))
1050     (let* ((register-function
1051             (spam-registration-function classification check))
1052            (unregister-function
1053             (spam-unregistration-function classification check))
1054            (run-function (if unregister
1055                              unregister-function
1056                            register-function))
1057            (log-function (if unregister
1058                              'spam-log-undo-registration
1059                            'spam-log-processing-to-registry))
1060            article articles)
1061
1062       (when run-function
1063         ;; make list of articles, using specific-articles if given
1064         (setq articles (or specific-articles
1065                            (spam-list-articles
1066                             gnus-newsgroup-articles
1067                             classification)))
1068         ;; process them
1069         (gnus-message 5 "%s %d %s articles with classification %s, check %s"
1070                       (if unregister "Unregistering" "Registering")
1071                       (length articles)
1072                       (if specific-articles "specific" "")
1073                       (symbol-name classification)
1074                       (symbol-name check))
1075         (funcall run-function articles)
1076         ;; now log all the registrations (or undo them, depending on unregister)
1077         (dolist (article articles)
1078           (funcall log-function
1079                    (spam-fetch-field-message-id-fast article)
1080                    'process
1081                    classification
1082                    check
1083                    gnus-newsgroup-name))))))
1084
1085 ;;; log a ham- or spam-processor invocation to the registry
1086 (defun spam-log-processing-to-registry (id type classification check group)
1087   (when spam-log-to-registry
1088     (if (and (stringp id)
1089              (stringp group)
1090              (spam-process-type-valid-p type)
1091              (spam-classification-valid-p classification)
1092              (spam-registration-check-valid-p check))
1093         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1094               (cell (list classification check group)))
1095           (push cell cell-list)
1096           (gnus-registry-store-extra-entry
1097            id
1098            type
1099            cell-list))
1100
1101       (gnus-message 5 (format "%s called with bad ID, type, classification, check, or group"
1102                               "spam-log-processing-to-registry")))))
1103
1104 ;;; check if a ham- or spam-processor registration has been done
1105 (defun spam-log-registered-p (id type)
1106   (when spam-log-to-registry
1107     (if (and (stringp id)
1108              (spam-process-type-valid-p type))
1109         (cdr-safe (gnus-registry-fetch-extra id type))
1110       (progn
1111         (gnus-message 5 (format "%s called with bad ID, type, classification, or check"
1112                                 "spam-log-registered-p"))
1113         nil))))
1114
1115 ;;; check if a ham- or spam-processor registration needs to be undone
1116 (defun spam-log-unregistration-needed-p (id type classification check)
1117   (when spam-log-to-registry
1118     (if (and (stringp id)
1119              (spam-process-type-valid-p type)
1120              (spam-classification-valid-p classification)
1121              (spam-registration-check-valid-p check))
1122         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1123               found)
1124           (dolist (cell cell-list)
1125             (unless found
1126               (when (and (eq classification (nth 0 cell))
1127                          (eq check (nth 1 cell)))
1128                 (setq found t))))
1129           found)
1130       (progn
1131         (gnus-message 5 (format "%s called with bad ID, type, classification, or check"
1132                                 "spam-log-unregistration-needed-p"))
1133         nil))))
1134
1135
1136 ;;; undo a ham- or spam-processor registration (the group is not used)
1137 (defun spam-log-undo-registration (id type classification check &optional group)
1138   (when (and spam-log-to-registry
1139              (spam-log-unregistration-needed-p id type classification check))
1140     (if (and (stringp id)
1141              (spam-process-type-valid-p type)
1142              (spam-classification-valid-p classification)
1143              (spam-registration-check-valid-p check))
1144         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1145               new-cell-list found)
1146           (dolist (cell cell-list)
1147             (unless (and (eq classification (nth 0 cell))
1148                          (eq check (nth 1 cell)))
1149               (push cell new-cell-list)))
1150           (gnus-registry-store-extra-entry
1151            id
1152            type
1153            new-cell-list))
1154       (progn
1155         (gnus-message 5 (format "%s called with bad ID, type, check, or group"
1156                                 "spam-log-undo-registration"))
1157         nil))))
1158
1159 ;;; set up IMAP widening if it's necessary
1160 (defun spam-setup-widening ()
1161   (dolist (check spam-list-of-statistical-checks)
1162     (when (symbol-value check)
1163       (setq nnimap-split-download-body-default t))))
1164
1165 \f
1166 ;;;; Regex body
1167
1168 (defun spam-check-regex-body ()
1169   (let ((spam-regex-headers-ham spam-regex-body-ham)
1170         (spam-regex-headers-spam spam-regex-body-spam))
1171     (spam-check-regex-headers t)))
1172
1173 \f
1174 ;;;; Regex headers
1175
1176 (defun spam-check-regex-headers (&optional body)
1177   (let ((type (if body "body" "header"))
1178         (spam-split-group (if spam-split-symbolic-return
1179                               'spam
1180                             spam-split-group))
1181         ret found)
1182     (dolist (h-regex spam-regex-headers-ham)
1183       (unless found
1184         (goto-char (point-min))
1185         (when (re-search-forward h-regex nil t)
1186           (message "Ham regex %s search positive." type)
1187           (setq found t))))
1188     (dolist (s-regex spam-regex-headers-spam)
1189       (unless found
1190         (goto-char (point-min))
1191         (when (re-search-forward s-regex nil t)
1192           (message "Spam regex %s search positive." type)
1193           (setq found t)
1194           (setq ret spam-split-group))))
1195     ret))
1196
1197 \f
1198 ;;;; Blackholes.
1199
1200 (defun spam-reverse-ip-string (ip)
1201   (when (stringp ip)
1202     (mapconcat 'identity
1203                (nreverse (split-string ip "\\."))
1204                ".")))
1205
1206 (defun spam-check-blackholes ()
1207   "Check the Received headers for blackholed relays."
1208   (let ((headers (nnmail-fetch-field "received"))
1209         (spam-split-group (if spam-split-symbolic-return
1210                               'spam
1211                             spam-split-group))
1212         ips matches)
1213     (when headers
1214       (with-temp-buffer
1215         (insert headers)
1216         (goto-char (point-min))
1217         (gnus-message 5 "Checking headers for relay addresses")
1218         (while (re-search-forward
1219                 "\\([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\\)" nil t)
1220           (gnus-message 9 "Blackhole search found host IP %s." (match-string 1))
1221           (push (spam-reverse-ip-string (match-string 1))
1222                 ips)))
1223       (dolist (server spam-blackhole-servers)
1224         (dolist (ip ips)
1225           (unless (and spam-blackhole-good-server-regex
1226                        ;; match the good-server-regex against the reversed (again) IP string
1227                        (string-match
1228                         spam-blackhole-good-server-regex
1229                         (spam-reverse-ip-string ip)))
1230             (unless matches
1231               (let ((query-string (concat ip "." server)))
1232                 (if spam-use-dig
1233                     (let ((query-result (query-dig query-string)))
1234                       (when query-result
1235                         (gnus-message 5 "(DIG): positive blackhole check '%s'"
1236                                       query-result)
1237                         (push (list ip server query-result)
1238                               matches)))
1239                   ;; else, if not using dig.el
1240                   (when (query-dns query-string)
1241                     (gnus-message 5 "positive blackhole check")
1242                     (push (list ip server (query-dns query-string 'TXT))
1243                           matches)))))))))
1244     (when matches
1245       spam-split-group)))
1246 \f
1247 ;;;; Hashcash.
1248
1249 (condition-case nil
1250     (progn
1251       (require 'hashcash)
1252
1253       (defun spam-check-hashcash ()
1254         "Check the headers for hashcash payments."
1255         (mail-check-payment)))   ;mail-check-payment returns a boolean
1256
1257   (file-error (progn
1258                 (defalias 'mail-check-payment 'ignore)
1259                 (defalias 'spam-check-hashcash 'ignore))))
1260 \f
1261 ;;;; BBDB
1262
1263 ;;; original idea for spam-check-BBDB from Alexander Kotelnikov
1264 ;;; <sacha@giotto.sj.ru>
1265
1266 ;; all this is done inside a condition-case to trap errors
1267
1268 (condition-case nil
1269     (progn
1270       (require 'bbdb)
1271       (require 'bbdb-com)
1272
1273       (defun spam-enter-ham-BBDB (addresses &optional remove)
1274         "Enter an address into the BBDB; implies ham (non-spam) sender"
1275         (dolist (from addresses)
1276           (when (stringp from)
1277             (let* ((parsed-address (gnus-extract-address-components from))
1278                    (name (or (nth 0 parsed-address) "Ham Sender"))
1279                    (remove-function (if remove
1280                                         'bbdb-delete-record-internal
1281                                       'ignore))
1282                    (net-address (nth 1 parsed-address))
1283                    (record (and net-address
1284                                 (bbdb-search-simple nil net-address))))
1285               (when net-address
1286                 (gnus-message 5 "%s address %s %s BBDB"
1287                               (if remove "Deleting" "Adding")
1288                               from
1289                               (if remove "from" "to"))
1290                 (if record
1291                     (funcall remove-function record)
1292                   (bbdb-create-internal name nil net-address nil nil
1293                                         "ham sender added by spam.el")))))))
1294
1295       (defun spam-BBDB-register-routine (articles &optional unregister)
1296         (let (addresses)
1297           (dolist (article articles)
1298             (when (stringp (spam-fetch-field-from-fast article))
1299               (push (spam-fetch-field-from-fast article) addresses)))
1300           ;; now do the register/unregister action
1301           (spam-enter-ham-BBDB addresses unregister)))
1302
1303       (defun spam-BBDB-unregister-routine (articles)
1304         (spam-BBDB-register-routine articles t))
1305
1306       (defun spam-check-BBDB ()
1307         "Mail from people in the BBDB is classified as ham or non-spam"
1308         (let ((who (nnmail-fetch-field "from"))
1309               (spam-split-group (if spam-split-symbolic-return
1310                                     'spam
1311                                   spam-split-group)))
1312           (when who
1313             (setq who (nth 1 (gnus-extract-address-components who)))
1314             (if (bbdb-search-simple nil who)
1315                 t
1316               (if spam-use-BBDB-exclusive
1317                   spam-split-group
1318                 nil))))))
1319
1320   (file-error (progn
1321                 (defalias 'bbdb-search-simple 'ignore)
1322                 (defalias 'spam-check-BBDB 'ignore)
1323                 (defalias 'spam-BBDB-register-routine 'ignore)
1324                 (defalias 'spam-enter-ham-BBDB 'ignore)
1325                 (defalias 'bbdb-create-internal 'ignore)
1326                 (defalias 'bbdb-delete-record-internal 'ignore)
1327                 (defalias 'bbdb-records 'ignore))))
1328
1329 \f
1330 ;;;; ifile
1331
1332 ;;; check the ifile backend; return nil if the mail was NOT classified
1333 ;;; as spam
1334
1335 (defun spam-get-ifile-database-parameter ()
1336   "Get the command-line parameter for ifile's database from
1337   spam-ifile-database-path."
1338   (if spam-ifile-database-path
1339       (format "--db-file=%s" spam-ifile-database-path)
1340     nil))
1341
1342 (defun spam-check-ifile ()
1343   "Check the ifile backend for the classification of this message."
1344   (let ((article-buffer-name (buffer-name))
1345         (spam-split-group (if spam-split-symbolic-return
1346                               'spam
1347                             spam-split-group))
1348         category return)
1349     (with-temp-buffer
1350       (let ((temp-buffer-name (buffer-name))
1351             (db-param (spam-get-ifile-database-parameter)))
1352         (save-excursion
1353           (set-buffer article-buffer-name)
1354           (apply 'call-process-region
1355                  (point-min) (point-max) spam-ifile-path
1356                  nil temp-buffer-name nil "-c"
1357                  (if db-param `(,db-param "-q") `("-q"))))
1358         ;; check the return now (we're back in the temp buffer)
1359         (goto-char (point-min))
1360         (if (not (eobp))
1361             (setq category (buffer-substring (point) (point-at-eol))))
1362         (when (not (zerop (length category))) ; we need a category here
1363           (if spam-ifile-all-categories
1364               (setq return category)
1365             ;; else, if spam-ifile-all-categories is not set...
1366             (when (string-equal spam-ifile-spam-category category)
1367               (setq return spam-split-group)))))) ; note return is nil otherwise
1368     return))
1369
1370 (defun spam-ifile-register-with-ifile (articles category &optional unregister)
1371   "Register an article, given as a string, with a category.
1372 Uses `gnus-newsgroup-name' if category is nil (for ham registration)."
1373   (let ((category (or category gnus-newsgroup-name))
1374         (add-or-delete-option (if unregister "-d" "-i"))
1375         (db (spam-get-ifile-database-parameter))
1376         parameters)
1377     (with-temp-buffer
1378       (dolist (article articles)
1379         (let ((article-string (spam-get-article-as-string article)))
1380           (when (stringp article-string)
1381             (insert article-string))))
1382       (apply 'call-process-region
1383              (point-min) (point-max) spam-ifile-path
1384              nil nil nil
1385              add-or-delete-option category
1386              (if db `(,db "-h") `("-h"))))))
1387
1388 (defun spam-ifile-register-spam-routine (articles &optional unregister)
1389   (spam-ifile-register-with-ifile articles spam-ifile-spam-category unregister))
1390
1391 (defun spam-ifile-unregister-spam-routine (articles)
1392   (spam-ifile-register-spam-routine articles t))
1393
1394 (defun spam-ifile-register-ham-routine (articles &optional unregister)
1395   (spam-ifile-register-with-ifile articles spam-ifile-ham-category unregister))
1396
1397 (defun spam-ifile-unregister-ham-routine (articles)
1398   (spam-ifile-register-ham-routine articles t))
1399
1400 \f
1401 ;;;; spam-stat
1402
1403 (condition-case nil
1404     (progn
1405       (let ((spam-stat-install-hooks nil))
1406         (require 'spam-stat))
1407
1408       (defun spam-check-stat ()
1409         "Check the spam-stat backend for the classification of this message"
1410         (let ((spam-split-group (if spam-split-symbolic-return
1411                                     'spam
1412                                   spam-split-group))
1413               (spam-stat-split-fancy-spam-group spam-split-group) ; override
1414               (spam-stat-buffer (buffer-name)) ; stat the current buffer
1415               category return)
1416           (spam-stat-split-fancy)))
1417
1418       (defun spam-stat-register-spam-routine (articles &optional unregister)
1419         (dolist (article articles)
1420           (let ((article-string (spam-get-article-as-string article)))
1421             (with-temp-buffer
1422               (insert article-string)
1423               (if unregister
1424                   (spam-stat-buffer-change-to-non-spam)
1425               (spam-stat-buffer-is-spam))))))
1426
1427       (defun spam-stat-unregister-spam-routine (articles)
1428         (spam-stat-register-spam-routine articles t))
1429
1430       (defun spam-stat-register-ham-routine (articles &optional unregister)
1431         (dolist (article articles)
1432           (let ((article-string (spam-get-article-as-string article)))
1433             (with-temp-buffer
1434               (insert article-string)
1435               (if unregister
1436                   (spam-stat-buffer-change-to-spam)
1437               (spam-stat-buffer-is-non-spam))))))
1438
1439       (defun spam-stat-unregister-ham-routine (articles)
1440         (spam-stat-register-ham-routine articles t))
1441
1442       (defun spam-maybe-spam-stat-load ()
1443         (when spam-use-stat (spam-stat-load)))
1444
1445       (defun spam-maybe-spam-stat-save ()
1446         (when spam-use-stat (spam-stat-save))))
1447
1448   (file-error (progn
1449                 (defalias 'spam-stat-load 'ignore)
1450                 (defalias 'spam-stat-save 'ignore)
1451                 (defalias 'spam-maybe-spam-stat-load 'ignore)
1452                 (defalias 'spam-maybe-spam-stat-save 'ignore)
1453                 (defalias 'spam-stat-register-ham-routine 'ignore)
1454                 (defalias 'spam-stat-unregister-ham-routine 'ignore)
1455                 (defalias 'spam-stat-register-spam-routine 'ignore)
1456                 (defalias 'spam-stat-unregister-spam-routine 'ignore)
1457                 (defalias 'spam-stat-buffer-is-spam 'ignore)
1458                 (defalias 'spam-stat-buffer-change-to-spam 'ignore)
1459                 (defalias 'spam-stat-buffer-is-non-spam 'ignore)
1460                 (defalias 'spam-stat-buffer-change-to-non-spam 'ignore)
1461                 (defalias 'spam-stat-split-fancy 'ignore)
1462                 (defalias 'spam-check-stat 'ignore))))
1463
1464 \f
1465
1466 ;;;; Blacklists and whitelists.
1467
1468 (defvar spam-whitelist-cache nil)
1469 (defvar spam-blacklist-cache nil)
1470
1471 (defun spam-kill-whole-line ()
1472   (beginning-of-line)
1473   (let ((kill-whole-line t))
1474     (kill-line)))
1475
1476 ;;; address can be a list, too
1477 (defun spam-enter-whitelist (address &optional remove)
1478   "Enter ADDRESS (list or single) into the whitelist.
1479 With a non-nil REMOVE, remove them."
1480   (interactive "sAddress: ")
1481   (spam-enter-list address spam-whitelist remove)
1482   (setq spam-whitelist-cache nil))
1483
1484 ;;; address can be a list, too
1485 (defun spam-enter-blacklist (address &optional remove)
1486   "Enter ADDRESS (list or single) into the blacklist.
1487 With a non-nil REMOVE, remove them."
1488   (interactive "sAddress: ")
1489   (spam-enter-list address spam-blacklist remove)
1490   (setq spam-blacklist-cache nil))
1491
1492 (defun spam-enter-list (addresses file &optional remove)
1493   "Enter ADDRESSES into the given FILE.
1494 Either the whitelist or the blacklist files can be used.  With
1495 REMOVE not nil, remove the ADDRESSES."
1496   (if (stringp addresses)
1497       (spam-enter-list (list addresses) file remove)
1498     ;; else, we have a list of addresses here
1499     (unless (file-exists-p (file-name-directory file))
1500       (make-directory (file-name-directory file) t))
1501     (save-excursion
1502       (set-buffer
1503        (find-file-noselect file))
1504       (dolist (a addresses)
1505         (when (stringp a)
1506           (goto-char (point-min))
1507           (if (re-search-forward (regexp-quote a) nil t)
1508               ;; found the address
1509               (when remove
1510                 (spam-kill-whole-line))
1511             ;; else, the address was not found
1512             (unless remove
1513               (goto-char (point-max))
1514               (unless (bobp)
1515                 (insert "\n"))
1516               (insert a "\n")))))
1517       (save-buffer))))
1518
1519 ;;; returns t if the sender is in the whitelist, nil or
1520 ;;; spam-split-group otherwise
1521 (defun spam-check-whitelist ()
1522   ;; FIXME!  Should it detect when file timestamps change?
1523   (let ((spam-split-group (if spam-split-symbolic-return
1524                               'spam
1525                             spam-split-group)))
1526     (unless spam-whitelist-cache
1527       (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
1528     (if (spam-from-listed-p spam-whitelist-cache)
1529         t
1530       (if spam-use-whitelist-exclusive
1531           spam-split-group
1532         nil))))
1533
1534 (defun spam-check-blacklist ()
1535   ;; FIXME!  Should it detect when file timestamps change?
1536   (let ((spam-split-group (if spam-split-symbolic-return
1537                               'spam
1538                             spam-split-group)))
1539     (unless spam-blacklist-cache
1540       (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
1541     (and (spam-from-listed-p spam-blacklist-cache) spam-split-group)))
1542
1543 (defun spam-parse-list (file)
1544   (when (file-readable-p file)
1545     (let (contents address)
1546       (with-temp-buffer
1547         (insert-file-contents file)
1548         (while (not (eobp))
1549           (setq address (buffer-substring (point) (point-at-eol)))
1550           (forward-line 1)
1551           ;; insert the e-mail address if detected, otherwise the raw data
1552           (unless (zerop (length address))
1553             (let ((pure-address (nth 1 (gnus-extract-address-components address))))
1554               (push (or pure-address address) contents)))))
1555       (nreverse contents))))
1556
1557 (defun spam-from-listed-p (cache)
1558   (let ((from (nnmail-fetch-field "from"))
1559         found)
1560     (while cache
1561       (let ((address (pop cache)))
1562         (unless (zerop (length address)) ; 0 for a nil address too
1563           (setq address (regexp-quote address))
1564           ;; fix regexp-quote's treatment of user-intended regexes
1565           (while (string-match "\\\\\\*" address)
1566             (setq address (replace-match ".*" t t address))))
1567         (when (and address (string-match address from))
1568           (setq found t
1569                 cache nil))))
1570     found))
1571
1572 (defun spam-filelist-register-routine (articles blacklist &optional unregister)
1573   (let ((de-symbol (if blacklist 'spam-use-whitelist 'spam-use-blacklist))
1574         (declassification (if blacklist 'ham 'spam))
1575         (enter-function
1576          (if blacklist 'spam-enter-blacklist 'spam-enter-whitelist))
1577         (remove-function
1578          (if blacklist 'spam-enter-whitelist 'spam-enter-blacklist))
1579         from addresses unregister-list)
1580     (dolist (article articles)
1581       (let ((from (spam-fetch-field-from-fast article))
1582             (id (spam-fetch-field-message-id-fast article))
1583             sender-ignored)
1584         (when (stringp from)
1585           (dolist (ignore-regex spam-blacklist-ignored-regexes)
1586             (when (and (not sender-ignored)
1587                        (stringp ignore-regex)
1588                        (string-match ignore-regex from))
1589               (setq sender-ignored t)))
1590           ;; remember the messages we need to unregister, unless remove is set
1591           (when (and
1592                  (null unregister)
1593                  (spam-log-unregistration-needed-p
1594                   id 'process declassification de-symbol))
1595             (push from unregister-list))
1596           (unless sender-ignored
1597             (push from addresses)))))
1598
1599     (if unregister
1600         (funcall enter-function addresses t) ; unregister all these addresses
1601       ;; else, register normally and unregister what we need to
1602       (funcall remove-function unregister-list t)
1603       (dolist (article unregister-list)
1604         (spam-log-undo-registration
1605          (spam-fetch-field-message-id-fast article)
1606          'process
1607          declassification
1608          de-symbol))
1609       (funcall enter-function addresses nil))))
1610
1611 (defun spam-blacklist-unregister-routine (articles)
1612   (spam-blacklist-register-routine articles t))
1613
1614 (defun spam-blacklist-register-routine (articles &optional unregister)
1615   (spam-filelist-register-routine articles t unregister))
1616
1617 (defun spam-whitelist-unregister-routine (articles)
1618   (spam-whitelist-register-routine articles t))
1619
1620 (defun spam-whitelist-register-routine (articles &optional unregister)
1621   (spam-filelist-register-routine articles nil unregister))
1622
1623 \f
1624 ;;;; Spam-report glue
1625 (defun spam-report-gmane-register-routine (articles)
1626   (when articles
1627     (apply 'spam-report-gmane articles)))
1628
1629 \f
1630 ;;;; Bogofilter
1631 (defun spam-check-bogofilter-headers (&optional score)
1632   (let ((header (nnmail-fetch-field spam-bogofilter-header))
1633         (spam-split-group (if spam-split-symbolic-return
1634                               'spam
1635                             spam-split-group)))
1636     (when header                        ; return nil when no header
1637       (if score                         ; scoring mode
1638           (if (string-match "spamicity=\\([0-9.]+\\)" header)
1639               (match-string 1 header)
1640             "0")
1641         ;; spam detection mode
1642         (when (string-match spam-bogofilter-bogosity-positive-spam-header
1643                             header)
1644           spam-split-group)))))
1645
1646 ;; return something sensible if the score can't be determined
1647 (defun spam-bogofilter-score ()
1648   "Get the Bogofilter spamicity score"
1649   (interactive)
1650   (save-window-excursion
1651     (gnus-summary-show-article t)
1652     (set-buffer gnus-article-buffer)
1653     (let ((score (or (spam-check-bogofilter-headers t)
1654                      (spam-check-bogofilter t))))
1655       (message "Spamicity score %s" score)
1656       (or score "0"))
1657     (gnus-summary-show-article)))
1658
1659 (defun spam-check-bogofilter (&optional score)
1660   "Check the Bogofilter backend for the classification of this message"
1661   (let ((article-buffer-name (buffer-name))
1662         (db spam-bogofilter-database-directory)
1663         return)
1664     (with-temp-buffer
1665       (let ((temp-buffer-name (buffer-name)))
1666         (save-excursion
1667           (set-buffer article-buffer-name)
1668           (apply 'call-process-region
1669                  (point-min) (point-max)
1670                  spam-bogofilter-path
1671                  nil temp-buffer-name nil
1672                  (if db `("-d" ,db "-v") `("-v"))))
1673         (setq return (spam-check-bogofilter-headers score))))
1674     return))
1675
1676 (defun spam-bogofilter-register-with-bogofilter (articles
1677                                                  spam
1678                                                  &optional unregister)
1679   "Register an article, given as a string, as spam or non-spam."
1680   (dolist (article articles)
1681     (let ((article-string (spam-get-article-as-string article))
1682           (db spam-bogofilter-database-directory)
1683           (switch (if unregister
1684                       (if spam
1685                           spam-bogofilter-spam-strong-switch
1686                         spam-bogofilter-ham-strong-switch)
1687                     (if spam
1688                         spam-bogofilter-spam-switch
1689                       spam-bogofilter-ham-switch))))
1690       (when (stringp article-string)
1691         (with-temp-buffer
1692           (insert article-string)
1693
1694           (apply 'call-process-region
1695                  (point-min) (point-max)
1696                  spam-bogofilter-path
1697                  nil nil nil switch
1698                  (if db `("-d" ,db "-v") `("-v"))))))))
1699
1700 (defun spam-bogofilter-register-spam-routine (articles &optional unregister)
1701   (spam-bogofilter-register-with-bogofilter articles t unregister))
1702
1703 (defun spam-bogofilter-unregister-spam-routine (articles)
1704   (spam-bogofilter-register-spam-routine articles t))
1705
1706 (defun spam-bogofilter-register-ham-routine (articles &optional unregister)
1707   (spam-bogofilter-register-with-bogofilter articles nil unregister))
1708
1709 (defun spam-bogofilter-unregister-ham-routine (articles)
1710   (spam-bogofilter-register-ham-routine articles t))
1711
1712
1713 \f
1714 ;;;; spamoracle
1715 (defun spam-check-spamoracle ()
1716   "Run spamoracle on an article to determine whether it's spam."
1717   (let ((article-buffer-name (buffer-name))
1718         (spam-split-group (if spam-split-symbolic-return
1719                               'spam
1720                             spam-split-group)))
1721     (with-temp-buffer
1722       (let ((temp-buffer-name (buffer-name)))
1723         (save-excursion
1724           (set-buffer article-buffer-name)
1725           (let ((status
1726                  (apply 'call-process-region
1727                         (point-min) (point-max)
1728                         spam-spamoracle-binary
1729                         nil temp-buffer-name nil
1730                         (if spam-spamoracle-database
1731                             `("-f" ,spam-spamoracle-database "mark")
1732                           '("mark")))))
1733             (if (eq 0 status)
1734                 (progn
1735                   (set-buffer temp-buffer-name)
1736                   (goto-char (point-min))
1737                   (when (re-search-forward "^X-Spam: yes;" nil t)
1738                     spam-split-group))
1739               (error "Error running spamoracle" status))))))))
1740
1741 (defun spam-spamoracle-learn (articles article-is-spam-p &optional unregister)
1742   "Run spamoracle in training mode."
1743   (with-temp-buffer
1744     (let ((temp-buffer-name (buffer-name)))
1745       (save-excursion
1746         (goto-char (point-min))
1747         (dolist (article articles)
1748           (insert (spam-get-article-as-string article)))
1749         (let* ((arg (if (spam-xor unregister article-is-spam-p)
1750                         "-spam"
1751                       "-good"))
1752                (status
1753                 (apply 'call-process-region
1754                        (point-min) (point-max)
1755                        spam-spamoracle-binary
1756                        nil temp-buffer-name nil
1757                        (if spam-spamoracle-database
1758                            `("-f" ,spam-spamoracle-database
1759                              "add" ,arg)
1760                          `("add" ,arg)))))
1761           (when (not (eq 0 status))
1762             (error "Error running spamoracle" status)))))))
1763
1764 (defun spam-spamoracle-learn-ham (articles &optional unregister)
1765   (spam-spamoracle-learn articles nil unregister))
1766
1767 (defun spam-spamoracle-unlearn-ham (articles &optional unregister)
1768   (spam-spamoracle-learn-ham articles t))
1769
1770 (defun spam-spamoracle-learn-spam (articles &optional unregister)
1771   (spam-spamoracle-learn articles t unregister))
1772
1773 (defun spam-spamoracle-unlearn-spam (articles &optional unregister)
1774   (spam-spamoracle-learn-spam articles t))
1775
1776 \f
1777 ;;;; Hooks
1778
1779 ;;;###autoload
1780 (defun spam-initialize ()
1781   "Install the spam.el hooks and do other initialization"
1782   (interactive)
1783   (setq spam-install-hooks t)
1784   ;; TODO: How do we redo this every time spam-face is customized?
1785   (push '((eq mark gnus-spam-mark) . spam-face)
1786         gnus-summary-highlight)
1787   ;; Add hooks for loading and saving the spam stats
1788   (add-hook 'gnus-save-newsrc-hook 'spam-maybe-spam-stat-save)
1789   (add-hook 'gnus-get-top-new-news-hook 'spam-maybe-spam-stat-load)
1790   (add-hook 'gnus-startup-hook 'spam-maybe-spam-stat-load)
1791   (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
1792   (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
1793   (add-hook 'gnus-get-new-news-hook 'spam-setup-widening)
1794   (add-hook 'gnus-summary-prepare-hook 'spam-find-spam))
1795
1796 (defun spam-unload-hook ()
1797   "Uninstall the spam.el hooks"
1798   (interactive)
1799   (remove-hook 'gnus-save-newsrc-hook 'spam-maybe-spam-stat-save)
1800   (remove-hook 'gnus-get-top-new-news-hook 'spam-maybe-spam-stat-load)
1801   (remove-hook 'gnus-startup-hook 'spam-maybe-spam-stat-load)
1802   (remove-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
1803   (remove-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
1804   (remove-hook 'gnus-get-new-news-hook 'spam-setup-widening)
1805   (remove-hook 'gnus-summary-prepare-hook 'spam-find-spam))
1806
1807 (when spam-install-hooks
1808   (spam-initialize))
1809
1810 (provide 'spam)
1811
1812 ;;; spam.el ends here.
1813
1814 (provide 'spam)
1815
1816 ;;; spam.el ends here