* spam.el (spam-use-spamassassin, spam-use-spamassassin-headers)
[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.
134 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-use-spamassassin nil
249   "Whether spamassassin should be invoked by `spam-split'.
250 Enable this if you want Gnus to invoke SpamAssassin on new messages."
251   :type 'boolean
252   :group 'spam)
253
254 (defcustom spam-use-spamassassin-headers nil
255   "Whether spamassassin headers should be checked by `spam-split'.
256 Enable this if you pre-process messages with SpamAssassin BEFORE Gnus sees
257 them."
258   :type 'boolean
259   :group 'spam)
260
261 (defcustom spam-install-hooks (or
262                                spam-use-dig
263                                spam-use-blacklist
264                                spam-use-whitelist
265                                spam-use-whitelist-exclusive
266                                spam-use-blackholes
267                                spam-use-hashcash
268                                spam-use-regex-headers
269                                spam-use-regex-body
270                                spam-use-bogofilter
271                                spam-use-bogofilter-headers
272                                spam-use-spamassassin
273                                spam-use-spamassassin-headers
274                                spam-use-BBDB
275                                spam-use-BBDB-exclusive
276                                spam-use-ifile
277                                spam-use-stat
278                                spam-use-spamoracle)
279   "Whether the spam hooks should be installed.
280 Default to t if one of the spam-use-* variables is set."
281   :group 'spam
282   :type 'boolean)
283
284 (defcustom spam-split-group "spam"
285   "Group name where incoming spam should be put by `spam-split'."
286   :type 'string
287   :group 'spam)
288
289 ;;; TODO: deprecate this variable, it's confusing since it's a list of strings,
290 ;;; not regular expressions
291 (defcustom spam-junk-mailgroups (cons
292                                  spam-split-group
293                                  '("mail.junk" "poste.pourriel"))
294   "Mailgroups with spam contents.
295 All unmarked article in such group receive the spam mark on group entry."
296   :type '(repeat (string :tag "Group"))
297   :group 'spam)
298
299 (defcustom spam-blackhole-servers '("bl.spamcop.net" "relays.ordb.org"
300                                     "dev.null.dk" "relays.visi.com")
301   "List of blackhole servers."
302   :type '(repeat (string :tag "Server"))
303   :group 'spam)
304
305 (defcustom spam-blackhole-good-server-regex nil
306   "String matching IP addresses that should not be checked in the blackholes."
307   :type '(radio (const nil)
308                 (regexp :format "%t: %v\n" :size 0))
309   :group 'spam)
310
311 (defcustom spam-face 'gnus-splash-face
312   "Face for spam-marked articles."
313   :type 'face
314   :group 'spam)
315
316 (defcustom spam-regex-headers-spam '("^X-Spam-Flag: YES")
317   "Regular expression for positive header spam matches."
318   :type '(repeat (regexp :tag "Regular expression to match spam header"))
319   :group 'spam)
320
321 (defcustom spam-regex-headers-ham '("^X-Spam-Flag: NO")
322   "Regular expression for positive header ham matches."
323   :type '(repeat (regexp :tag "Regular expression to match ham header"))
324   :group 'spam)
325
326 (defcustom spam-regex-body-spam '()
327   "Regular expression for positive body spam matches."
328   :type '(repeat (regexp :tag "Regular expression to match spam body"))
329   :group 'spam)
330
331 (defcustom spam-regex-body-ham '()
332   "Regular expression for positive body ham matches."
333   :type '(repeat (regexp :tag "Regular expression to match ham body"))
334   :group 'spam)
335
336 (defgroup spam-ifile nil
337   "Spam ifile configuration."
338   :group 'spam)
339
340 (defcustom spam-ifile-path (executable-find "ifile")
341   "File path of the ifile executable program."
342   :type '(choice (file :tag "Location of ifile")
343                  (const :tag "ifile is not installed"))
344   :group 'spam-ifile)
345
346 (defcustom spam-ifile-database-path nil
347   "File path of the ifile database."
348   :type '(choice (file :tag "Location of the ifile database")
349                  (const :tag "Use the default"))
350   :group 'spam-ifile)
351
352 (defcustom spam-ifile-spam-category "spam"
353   "Name of the spam ifile category."
354   :type 'string
355   :group 'spam-ifile)
356
357 (defcustom spam-ifile-ham-category nil
358   "Name of the ham ifile category.
359 If nil, the current group name will be used."
360   :type '(choice (string :tag "Use a fixed category")
361                  (const :tag "Use the current group name"))
362   :group 'spam-ifile)
363
364 (defcustom spam-ifile-all-categories nil
365   "Whether the ifile check will return all categories, or just spam.
366 Set this to t if you want to use the `spam-split' invocation of ifile as
367 your main source of newsgroup names."
368   :type 'boolean
369   :group 'spam-ifile)
370
371 (defgroup spam-bogofilter nil
372   "Spam bogofilter configuration."
373   :group 'spam)
374
375 (defcustom spam-bogofilter-path (executable-find "bogofilter")
376   "File path of the Bogofilter executable program."
377   :type '(choice (file :tag "Location of bogofilter")
378                  (const :tag "Bogofilter is not installed"))
379   :group 'spam-bogofilter)
380
381 (defcustom spam-bogofilter-header "X-Bogosity"
382   "The header that Bogofilter inserts in messages."
383   :type 'string
384   :group 'spam-bogofilter)
385
386 (defcustom spam-bogofilter-spam-switch "-s"
387   "The switch that Bogofilter uses to register spam messages."
388   :type 'string
389   :group 'spam-bogofilter)
390
391 (defcustom spam-bogofilter-ham-switch "-n"
392   "The switch that Bogofilter uses to register ham messages."
393   :type 'string
394   :group 'spam-bogofilter)
395
396 (defcustom spam-bogofilter-spam-strong-switch "-S"
397   "The switch that Bogofilter uses to unregister ham messages."
398   :type 'string
399   :group 'spam-bogofilter)
400
401 (defcustom spam-bogofilter-ham-strong-switch "-N"
402   "The switch that Bogofilter uses to unregister spam messages."
403   :type 'string
404   :group 'spam-bogofilter)
405
406 (defcustom spam-bogofilter-bogosity-positive-spam-header "^\\(Yes\\|Spam\\)"
407   "The regex on `spam-bogofilter-header' for positive spam identification."
408   :type 'regexp
409   :group 'spam-bogofilter)
410
411 (defcustom spam-bogofilter-database-directory nil
412   "Directory path of the Bogofilter databases."
413   :type '(choice (directory
414                   :tag "Location of the Bogofilter database directory")
415                  (const :tag "Use the default"))
416   :group 'spam-bogofilter)
417
418 (defgroup spam-spamoracle nil
419   "Spam spamoracle configuration."
420   :group 'spam)
421
422 (defcustom spam-spamoracle-database nil
423   "Location of spamoracle database file.
424 When nil, use the default spamoracle database."
425   :type '(choice (directory :tag "Location of spamoracle database file.")
426                  (const :tag "Use the default"))
427   :group 'spam-spamoracle)
428
429 (defcustom spam-spamoracle-binary (executable-find "spamoracle")
430   "Location of the spamoracle binary."
431   :type '(choice (directory :tag "Location of the spamoracle binary")
432                  (const :tag "Use the default"))
433   :group 'spam-spamoracle)
434
435 (defgroup spam-spamassassin nil
436   "Spam SpamAssassin configuration."
437   :group 'spam)
438
439 (defcustom spam-spamassassin-path (executable-find "spamassassin")
440   "File path of the spamassassin executable program.
441 Hint: set this to \"spamc\" if you have spamd running.  See the spamc and
442 spamd man pages for more information on these programs."
443   :type '(choice (file :tag "Location of spamc")
444                  (const :tag "spamassassin is not installed"))
445   :group 'spam-spamassassin)
446
447 (defcustom spam-spamassassin-arguments ()
448   "Arguments to pass to the spamassassin executable.
449 This must be a list.  For example, `(\"-C\" \"configfile\")'."
450   :type '(restricted-sexp :match-alternatives (listp))
451   :group 'spam-spamassassin)
452
453 (defcustom spam-spamassassin-spam-flag-header "X-Spam-Flag"
454   "The header inserted by SpamAssassin to flag spam."
455   :type 'string
456   :group 'spam-spamassassin)
457
458 (defcustom spam-spamassassin-positive-spam-flag-header "YES"
459   "The regex on `spam-spamassassin-spam-flag-header' for positive spam
460 identification"
461   :type 'string
462   :group 'spam-spamassassin)
463
464 (defcustom spam-spamassassin-spam-status-header "X-Spam-Status"
465   "The header inserted by SpamAssassin, giving extended scoring information"
466   :type 'string
467   :group 'spam-spamassassin)
468
469 (defcustom spam-sa-learn-path (executable-find "sa-learn")
470   "File path of the sa-learn executable program."
471   :type '(choice (file :tag "Location of spamassassin")
472                  (const :tag "spamassassin is not installed"))
473   :group 'spam-spamassassin)
474
475 (defcustom spam-sa-learn-rebuild t
476   "Whether sa-learn should rebuild the database every time it is called
477 Enable this if you want sa-learn to rebuild the database automatically.  Doing
478 this will slightly increase the running time of the spam registration process.
479 If you choose not to do this, you will have to run \"sa-learn --rebuild\" in
480 order for SpamAssassin to recognize the new registered spam."
481   :type 'boolean
482   :group 'spam-spamassassin)
483
484 (defcustom spam-sa-learn-spam-switch "--spam"
485   "The switch that sa-learn uses to register spam messages"
486   :type 'string
487   :group 'spam-spamassassin)
488
489 (defcustom spam-sa-learn-ham-switch "--ham"
490   "The switch that sa-learn uses to register ham messages"
491   :type 'string
492   :group 'spam-spamassassin)
493
494 (defcustom spam-sa-learn-unregister-switch "--forget"
495   "The switch that sa-learn uses to unregister messages messages"
496   :type 'string
497   :group 'spam-spamassassin)
498
499 ;;; Key bindings for spam control.
500
501 (gnus-define-keys gnus-summary-mode-map
502   "St" spam-bogofilter-score
503   "Sx" gnus-summary-mark-as-spam
504   "Mst" spam-bogofilter-score
505   "Msx" gnus-summary-mark-as-spam
506   "\M-d" gnus-summary-mark-as-spam)
507
508 (defvar spam-cache-lookups t
509   "Whether spam.el will try to cache lookups using `spam-caches'.")
510
511 (defvar spam-caches (make-hash-table
512                      :size 10
513                      :test 'equal)
514   "Cache of spam detection entries.")
515
516 (defvar spam-old-ham-articles nil
517   "List of old ham articles, generated when a group is entered.")
518
519 (defvar spam-old-spam-articles nil
520   "List of old spam articles, generated when a group is entered.")
521
522 (defvar spam-split-disabled nil
523   "If non-nil, `spam-split' is disabled, and always returns nil.")
524
525 (defvar spam-split-last-successful-check nil
526   "Internal variable.
527 `spam-split' will set this to nil or a spam-use-XYZ check if it
528 finds ham or spam.")
529
530 ;; convenience functions
531 (defun spam-clear-cache (symbol)
532   "Clear the spam-caches entry for a check."
533   (remhash symbol spam-caches))
534
535 (defun spam-xor (a b)
536   "Logical A xor B."
537   (and (or a b) (not (and a b))))
538
539 (defun spam-group-ham-mark-p (group mark &optional spam)
540   "Checks if MARK is considered a ham mark in GROUP."
541   (when (stringp group)
542     (let* ((marks (spam-group-ham-marks group spam))
543            (marks (if (symbolp mark)
544                       marks
545                     (mapcar 'symbol-value marks))))
546       (memq mark marks))))
547
548 (defun spam-group-spam-mark-p (group mark)
549   "Checks if MARK is considered a spam mark in GROUP."
550   (spam-group-ham-mark-p group mark t))
551
552 (defun spam-group-ham-marks (group &optional spam)
553   "In GROUP, get all the ham marks."
554   (when (stringp group)
555     (let* ((marks (if spam
556                       (gnus-parameter-spam-marks group)
557                     (gnus-parameter-ham-marks group)))
558            (marks (car marks))
559            (marks (if (listp (car marks)) (car marks) marks)))
560       marks)))
561
562 (defun spam-group-spam-marks (group)
563   "In GROUP, get all the spam marks."
564   (spam-group-ham-marks group t))
565
566 (defun spam-group-spam-contents-p (group)
567   "Is GROUP a spam group?"
568   (if (stringp group)
569       (or (member group spam-junk-mailgroups)
570           (memq 'gnus-group-spam-classification-spam
571                 (gnus-parameter-spam-contents group)))
572     nil))
573
574 (defun spam-group-ham-contents-p (group)
575   "Is GROUP a ham group?"
576   (if (stringp group)
577       (memq 'gnus-group-spam-classification-ham
578             (gnus-parameter-spam-contents group))
579     nil))
580
581 (defvar spam-list-of-processors
582   '((gnus-group-spam-exit-processor-report-gmane spam spam-use-gmane)
583     (gnus-group-spam-exit-processor-bogofilter   spam spam-use-bogofilter)
584     (gnus-group-spam-exit-processor-blacklist    spam spam-use-blacklist)
585     (gnus-group-spam-exit-processor-ifile        spam spam-use-ifile)
586     (gnus-group-spam-exit-processor-stat         spam spam-use-stat)
587     (gnus-group-spam-exit-processor-spamoracle   spam spam-use-spamoracle)
588     (gnus-group-spam-exit-processor-spamassassin spam spam-use-spam-spamassassin)
589     (gnus-group-ham-exit-processor-ifile         ham spam-use-ifile)
590     (gnus-group-ham-exit-processor-bogofilter    ham spam-use-bogofilter)
591     (gnus-group-ham-exit-processor-stat          ham spam-use-stat)
592     (gnus-group-ham-exit-processor-whitelist     ham spam-use-whitelist)
593     (gnus-group-ham-exit-processor-BBDB          ham spam-use-BBDB)
594     (gnus-group-ham-exit-processor-copy          ham spam-use-ham-copy)
595     (gnus-group-ham-exit-processor-spamassassin  ham spam-use-ham-spamassassin)
596     (gnus-group-ham-exit-processor-spamoracle    ham spam-use-spamoracle))
597   "The `spam-list-of-processors' list.
598 This list contains pairs associating a ham/spam exit processor
599 variable with a classification and a spam-use-* variable.")
600
601 (defun spam-group-processor-p (group processor)
602   (if (and (stringp group)
603            (symbolp processor))
604       (or (member processor (nth 0 (gnus-parameter-spam-process group)))
605           (spam-group-processor-multiple-p
606            group
607            (cdr-safe (assoc processor spam-list-of-processors))))
608     nil))
609
610 (defun spam-group-processor-multiple-p (group processor-info)
611   (let* ((classification (nth 0 processor-info))
612          (check (nth 1 processor-info))
613          (parameters (nth 0 (gnus-parameter-spam-process group)))
614          found)
615     (dolist (parameter parameters)
616       (when (and (null found)
617                  (listp parameter)
618                  (eq classification (nth 0 parameter))
619                  (eq check (nth 1 parameter)))
620         (setq found t)))
621     found))
622
623 (defun spam-group-spam-processor-report-gmane-p (group)
624   (spam-group-processor-p group 'gnus-group-spam-exit-processor-report-gmane))
625
626 (defun spam-group-spam-processor-bogofilter-p (group)
627   (spam-group-processor-p group 'gnus-group-spam-exit-processor-bogofilter))
628
629 (defun spam-group-spam-processor-blacklist-p (group)
630   (spam-group-processor-p group 'gnus-group-spam-exit-processor-blacklist))
631
632 (defun spam-group-spam-processor-ifile-p (group)
633   (spam-group-processor-p group 'gnus-group-spam-exit-processor-ifile))
634
635 (defun spam-group-ham-processor-ifile-p (group)
636   (spam-group-processor-p group 'gnus-group-ham-exit-processor-ifile))
637
638 (defun spam-group-spam-processor-spamoracle-p (group)
639   (spam-group-processor-p group 'gnus-group-spam-exit-processor-spamoracle))
640
641 (defun spam-group-ham-processor-bogofilter-p (group)
642   (spam-group-processor-p group 'gnus-group-ham-exit-processor-bogofilter))
643
644 (defun spam-group-spam-processor-stat-p (group)
645   (spam-group-processor-p group 'gnus-group-spam-exit-processor-stat))
646
647 (defun spam-group-ham-processor-stat-p (group)
648   (spam-group-processor-p group 'gnus-group-ham-exit-processor-stat))
649
650 (defun spam-group-ham-processor-whitelist-p (group)
651   (spam-group-processor-p group 'gnus-group-ham-exit-processor-whitelist))
652
653 (defun spam-group-ham-processor-BBDB-p (group)
654   (spam-group-processor-p group 'gnus-group-ham-exit-processor-BBDB))
655
656 (defun spam-group-ham-processor-copy-p (group)
657   (spam-group-processor-p group 'gnus-group-ham-exit-processor-copy))
658
659 (defun spam-group-ham-processor-spamoracle-p (group)
660   (spam-group-processor-p group 'gnus-group-ham-exit-processor-spamoracle))
661
662 (defun spam-report-articles-gmane (n)
663   "Report the current message as spam.
664 Respects the process/prefix convention."
665   (interactive "P")
666   (dolist (article (gnus-summary-work-articles n))
667     (gnus-summary-remove-process-mark article)
668     (spam-report-gmane article)))
669
670 ;;; Summary entry and exit processing.
671
672 (defun spam-summary-prepare ()
673   (setq spam-old-ham-articles
674         (spam-list-articles gnus-newsgroup-articles 'ham))
675   (setq spam-old-spam-articles
676         (spam-list-articles gnus-newsgroup-articles 'spam))
677   (spam-mark-junk-as-spam-routine))
678
679 ;; The spam processors are invoked for any group, spam or ham or neither
680 (defun spam-summary-prepare-exit ()
681   (unless gnus-group-is-exiting-without-update-p
682     (gnus-message 6 "Exiting summary buffer and applying spam rules")
683
684     ;; first of all, unregister any articles that are no longer ham or spam
685     ;; we have to iterate over the processors, or else we'll be too slow
686     (dolist (classification '(spam ham))
687       (let* ((old-articles (if (eq classification 'spam)
688                                spam-old-spam-articles
689                              spam-old-ham-articles))
690              (new-articles (spam-list-articles
691                             gnus-newsgroup-articles
692                             classification))
693              (changed-articles (gnus-set-difference old-articles new-articles)))
694         ;; now that we have the changed articles, we go through the processors
695         (dolist (processor-param spam-list-of-processors)
696           (let ((processor (nth 0 processor-param))
697                 (processor-classification (nth 1 processor-param))
698                 (check (nth 2 processor-param))
699                 unregister-list)
700             (dolist (article changed-articles)
701               (let ((id (spam-fetch-field-message-id-fast article)))
702                 (when (spam-log-unregistration-needed-p
703                        id 'process classification check)
704                   (push article unregister-list))))
705             ;; call spam-register-routine with specific articles to unregister,
706             ;; when there are articles to unregister and the check is enabled
707             (when (and unregister-list (symbol-value check))
708               (spam-register-routine classification check t unregister-list))))))
709
710     ;; find all the spam processors applicable to this group
711     (dolist (processor-param spam-list-of-processors)
712       (let ((processor (nth 0 processor-param))
713             (classification (nth 1 processor-param))
714             (check (nth 2 processor-param)))
715         (when (and (eq 'spam classification)
716                    (spam-group-processor-p gnus-newsgroup-name processor))
717           (spam-register-routine classification check))))
718
719     (if spam-move-spam-nonspam-groups-only
720         (when (not (spam-group-spam-contents-p gnus-newsgroup-name))
721           (spam-mark-spam-as-expired-and-move-routine
722            (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
723       (gnus-message 5 "Marking spam as expired and moving it to %s"
724                     gnus-newsgroup-name)
725       (spam-mark-spam-as-expired-and-move-routine
726        (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
727
728     ;; now we redo spam-mark-spam-as-expired-and-move-routine to only
729     ;; expire spam, in case the above did not expire them
730     (gnus-message 5 "Marking spam as expired without moving it")
731     (spam-mark-spam-as-expired-and-move-routine nil)
732
733     (when (or (spam-group-ham-contents-p gnus-newsgroup-name)
734               (and (spam-group-spam-contents-p gnus-newsgroup-name)
735                    spam-process-ham-in-spam-groups)
736               spam-process-ham-in-nonham-groups)
737       ;; find all the ham processors applicable to this group
738       (dolist (processor-param spam-list-of-processors)
739         (let ((processor (nth 0 processor-param))
740               (classification (nth 1 processor-param))
741               (check (nth 2 processor-param)))
742           (when (and (eq 'ham classification)
743                      (spam-group-processor-p gnus-newsgroup-name processor))
744             (spam-register-routine classification check)))))
745
746     (when (spam-group-ham-processor-copy-p gnus-newsgroup-name)
747       (gnus-message 5 "Copying ham")
748       (spam-ham-copy-routine
749        (gnus-parameter-ham-process-destination gnus-newsgroup-name)))
750
751     ;; now move all ham articles out of spam groups
752     (when (spam-group-spam-contents-p gnus-newsgroup-name)
753       (gnus-message 5 "Moving ham messages from spam group")
754       (spam-ham-move-routine
755        (gnus-parameter-ham-process-destination gnus-newsgroup-name))))
756
757   (setq spam-old-ham-articles nil)
758   (setq spam-old-spam-articles nil))
759
760 (defun spam-mark-junk-as-spam-routine ()
761   ;; check the global list of group names spam-junk-mailgroups and the
762   ;; group parameters
763   (when (spam-group-spam-contents-p gnus-newsgroup-name)
764     (gnus-message 5 "Marking %s articles as spam"
765                   (if spam-mark-only-unseen-as-spam
766                       "unseen"
767                     "unread"))
768     (let ((articles (if spam-mark-only-unseen-as-spam
769                         gnus-newsgroup-unseen
770                       gnus-newsgroup-unreads)))
771       (dolist (article articles)
772         (gnus-summary-mark-article article gnus-spam-mark)))))
773
774 (defun spam-mark-spam-as-expired-and-move-routine (&rest groups)
775   (if (and (car-safe groups) (listp (car-safe groups)))
776       (apply 'spam-mark-spam-as-expired-and-move-routine (car groups))
777     (gnus-summary-kill-process-mark)
778     (let ((articles gnus-newsgroup-articles)
779           (backend-supports-deletions
780            (gnus-check-backend-function
781             'request-move-article gnus-newsgroup-name))
782           article tomove deletep)
783       (dolist (article articles)
784         (when (eq (gnus-summary-article-mark article) gnus-spam-mark)
785           (gnus-summary-mark-article article gnus-expirable-mark)
786           (push article tomove)))
787
788       ;; now do the actual copies
789       (dolist (group groups)
790         (when (and tomove
791                    (stringp group))
792           (dolist (article tomove)
793             (gnus-summary-set-process-mark article))
794           (when tomove
795             (if (or (not backend-supports-deletions)
796                     (> (length groups) 1))
797                 (progn
798                   (gnus-summary-copy-article nil group)
799                   (setq deletep t))
800               (gnus-summary-move-article nil group)))))
801
802       ;; now delete the articles, if there was a copy done, and the
803       ;; backend allows it
804       (when (and deletep backend-supports-deletions)
805         (dolist (article tomove)
806           (gnus-summary-set-process-mark article))
807         (when tomove
808           (let ((gnus-novice-user nil)) ; don't ask me if I'm sure
809             (gnus-summary-delete-article nil))))
810
811       (gnus-summary-yank-process-mark))))
812
813 (defun spam-ham-copy-or-move-routine (copy groups)
814   (gnus-summary-kill-process-mark)
815   (let ((todo (spam-list-articles gnus-newsgroup-articles 'ham))
816         (backend-supports-deletions
817          (gnus-check-backend-function
818           'request-move-article gnus-newsgroup-name))
819         (respool-method (gnus-find-method-for-group gnus-newsgroup-name))
820         article mark todo deletep respool)
821
822     (when (member 'respool groups)
823       (setq respool t)                  ; boolean for later
824       (setq groups '("fake"))) ; when respooling, groups are dynamic so fake it
825
826     ;; now do the actual move
827     (dolist (group groups)
828       (when (and todo (stringp group))
829         (dolist (article todo)
830           (when spam-mark-ham-unread-before-move-from-spam-group
831             (gnus-summary-mark-article article gnus-unread-mark))
832           (gnus-summary-set-process-mark article))
833
834         (if respool                        ; respooling is with a "fake" group
835             (let ((spam-split-disabled
836                    (or spam-split-disabled
837                        spam-disable-spam-split-during-ham-respool)))
838               (gnus-summary-respool-article nil respool-method))
839           (if (or (not backend-supports-deletions) ; else, we are not respooling
840                   (> (length groups) 1))
841               (progn                ; if copying, copy and set deletep
842                 (gnus-summary-copy-article nil group)
843                 (setq deletep t))
844             (gnus-summary-move-article nil group))))) ; else move articles
845
846     ;; now delete the articles, unless a) copy is t, and there was a copy done
847     ;;                                 b) a move was done to a single group
848     ;;                                 c) backend-supports-deletions is nil
849     (unless copy
850       (when (and deletep backend-supports-deletions)
851         (dolist (article todo)
852           (gnus-summary-set-process-mark article))
853         (when todo
854           (let ((gnus-novice-user nil)) ; don't ask me if I'm sure
855             (gnus-summary-delete-article nil))))))
856
857   (gnus-summary-yank-process-mark))
858
859 (defun spam-ham-copy-routine (&rest groups)
860   (if (and (car-safe groups) (listp (car-safe groups)))
861       (apply 'spam-ham-copy-routine (car groups))
862     (spam-ham-copy-or-move-routine t groups)))
863
864 (defun spam-ham-move-routine (&rest groups)
865   (if (and (car-safe groups) (listp (car-safe groups)))
866       (apply 'spam-ham-move-routine (car groups))
867     (spam-ham-copy-or-move-routine nil groups)))
868
869 (defun spam-get-article-as-string (article)
870   (when (numberp article)
871     (with-temp-buffer
872       (gnus-request-article-this-buffer
873        article
874        gnus-newsgroup-name)
875       (buffer-string))))
876
877 ;; disabled for now
878 ;; (defun spam-get-article-as-filename (article)
879 ;;   (let ((article-filename))
880 ;;     (when (numberp article)
881 ;;       (nnml-possibly-change-directory
882 ;;        (gnus-group-real-name gnus-newsgroup-name))
883 ;;       (setq article-filename (expand-file-name
884 ;;                              (int-to-string article) nnml-current-directory)))
885 ;;     (if (file-exists-p article-filename)
886 ;;      article-filename
887 ;;       nil)))
888
889 (defun spam-fetch-field-fast (article field &optional prepared-data-header)
890   "Fetch a field quickly, using the internal gnus-data-list function"
891   (when (numberp article)
892     (let* ((data-header (or prepared-data-header
893                             (spam-fetch-article-header article))))
894       (if (arrayp data-header)
895         (cond
896          ((equal field 'from)
897           (mail-header-from data-header))
898          ((equal field 'message-id)
899           (mail-header-message-id data-header))
900          ((equal field 'subject)
901           (mail-header-subject data-header))
902          ((equal field 'references)
903           (mail-header-references data-header))
904          ((equal field 'date)
905           (mail-header-date data-header))
906          ((equal field 'xref)
907           (mail-header-xref data-header))
908          ((equal field 'extra)
909           (mail-header-extra data-header))
910          (t
911           nil))
912         (gnus-error 5 "Article %d has a nil data header" article)))))
913
914 (defun spam-fetch-field-from-fast (article &optional prepared-data-header)
915   (spam-fetch-field-fast article 'from prepared-data-header))
916
917 (defun spam-fetch-field-subject-fast (article &optional prepared-data-header)
918   (spam-fetch-field-fast article 'subject prepared-data-header))
919
920 (defun spam-fetch-field-message-id-fast (article &optional prepared-data-header)
921   (spam-fetch-field-fast article 'message-id prepared-data-header))
922
923 (defun spam-generate-fake-headers (article)
924   (let ((dh (spam-fetch-article-header article)))
925     (if dh
926         (concat
927          (format 
928           (concat "From: %s\nSubject: %s\nMessage-ID: %s\n"
929                   "Date: %s\nReferences: %s\nXref: %s\n")
930           (spam-fetch-field-fast article 'from dh)
931           (spam-fetch-field-fast article 'subject dh)
932           (spam-fetch-field-fast article 'message-id dh)
933           (spam-fetch-field-fast article 'date dh)
934           (spam-fetch-field-fast article 'references dh)
935           (spam-fetch-field-fast article 'xref dh))
936          (when (spam-fetch-field-fast article 'extra dh)
937            (format "%s\n" (spam-fetch-field-fast article 'extra dh))))
938       (gnus-error
939        5
940        "spam-generate-fake-headers: article %d didn't have a valid header"
941        article))))
942
943 (defun spam-fetch-article-header (article)
944   (save-excursion
945     (set-buffer gnus-summary-buffer)
946     (nth 3 (assq article gnus-newsgroup-data))))
947
948 \f
949 ;;;; Spam determination.
950
951 (defvar spam-list-of-checks
952   '((spam-use-blacklist                 .       spam-check-blacklist)
953     (spam-use-regex-headers             .       spam-check-regex-headers)
954     (spam-use-regex-body                .       spam-check-regex-body)
955     (spam-use-whitelist                 .       spam-check-whitelist)
956     (spam-use-BBDB                      .       spam-check-BBDB)
957     (spam-use-ifile                     .       spam-check-ifile)
958     (spam-use-spamoracle                .       spam-check-spamoracle)
959     (spam-use-stat                      .       spam-check-stat)
960     (spam-use-blackholes                .       spam-check-blackholes)
961     (spam-use-hashcash                  .       spam-check-hashcash)
962     (spam-use-spamassassin-headers      .       spam-check-spamassassin-headers)
963     (spam-use-spamassassin              .       spam-check-spamassassin)
964     (spam-use-bogofilter-headers        .       spam-check-bogofilter-headers)
965     (spam-use-bogofilter                .       spam-check-bogofilter))
966   "The spam-list-of-checks list contains pairs associating a
967 parameter variable with a spam checking function.  If the
968 parameter variable is true, then the checking function is called,
969 and its value decides what happens.  Each individual check may
970 return nil, t, or a mailgroup name.  The value nil means that the
971 check does not yield a decision, and so, that further checks are
972 needed.  The value t means that the message is definitely not
973 spam, and that further spam checks should be inhibited.
974 Otherwise, a mailgroup name or the symbol 'spam (depending on
975 spam-split-symbolic-return) is returned where the mail should go,
976 and further checks are also inhibited.  The usual mailgroup name
977 is the value of `spam-split-group', meaning that the message is
978 definitely a spam.")
979
980 (defvar spam-list-of-statistical-checks
981   '(spam-use-ifile
982     spam-use-regex-body
983     spam-use-stat
984     spam-use-bogofilter
985     spam-use-blackholes
986     spam-use-spamassassin
987     spam-use-spamoracle)
988   "The spam-list-of-statistical-checks list contains all the mail
989 splitters that need to have the full message body available.
990 Note that you should fetch extra headers if you don't like this,
991 e.g. fetch the 'Received' header for spam-use-blackholes.")
992
993 (defun spam-split (&rest specific-checks)
994   "Split this message into the `spam' group if it is spam.
995 This function can be used as an entry in the variable `nnmail-split-fancy',
996 for example like this: (: spam-split).  It can take checks as
997 parameters.  A string as a parameter will set the
998 spam-split-group to that string.
999
1000 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1001   (interactive)
1002   (setq spam-split-last-successful-check nil)
1003   (unless spam-split-disabled
1004     (let ((spam-split-group-choice spam-split-group))
1005       (dolist (check specific-checks)
1006         (when (stringp check)
1007           (setq spam-split-group-choice check)
1008           (setq specific-checks (delq check specific-checks))))
1009
1010       (let ((spam-split-group spam-split-group-choice))
1011         (save-excursion
1012           (save-restriction
1013             (dolist (check spam-list-of-statistical-checks)
1014               (when (and (symbolp check)
1015                          (or (symbol-value check)
1016                              (memq check specific-checks)))
1017                 (widen)
1018                 (gnus-message 8 "spam-split: widening the buffer (%s requires it)"
1019                               (symbol-name check))
1020                 (return)))
1021             ;;   (progn (widen) (debug (buffer-string)))
1022             (let ((list-of-checks spam-list-of-checks)
1023                   decision)
1024               (while (and list-of-checks (not decision))
1025                 (let ((pair (pop list-of-checks)))
1026                   (when (or
1027                          ;; either, given specific checks, this is one of them
1028                          (and specific-checks (memq (car pair) specific-checks))
1029                          ;; or, given no specific checks, spam-use-CHECK is set
1030                          (and (null specific-checks) (symbol-value (car pair))))
1031                     (gnus-message 5 "spam-split: calling the %s function"
1032                                   (symbol-name (cdr pair)))
1033                     (setq decision (funcall (cdr pair)))
1034                     ;; if we got a decision at all, save the current check
1035                     (when decision
1036                       (setq spam-split-last-successful-check (car pair)))
1037
1038                     (when (eq decision 'spam)
1039                       (unless spam-split-symbolic-return
1040                         (gnus-error
1041                          5
1042                          (format "spam-split got %s but %s is nil"
1043                                  (symbol-name decision)
1044                                  (symbol-name spam-split-symbolic-return))))))))
1045               (if (eq decision t)
1046                   (if spam-split-symbolic-return-positive 'ham nil)
1047                 decision))))))))
1048
1049 (defun spam-find-spam ()
1050   "This function will detect spam in the current newsgroup using spam-split."
1051   (interactive)
1052
1053   (let* ((group gnus-newsgroup-name)
1054          (autodetect (gnus-parameter-spam-autodetect group))
1055          (methods (gnus-parameter-spam-autodetect-methods group))
1056          (first-method (nth 0 methods))
1057          (articles (if spam-autodetect-recheck-messages
1058                        gnus-newsgroup-articles
1059                      gnus-newsgroup-unseen))
1060          article-cannot-be-faked)
1061
1062     (dolist (check spam-list-of-statistical-checks)
1063       (when (and (symbolp check)
1064                  (memq check methods))
1065         (setq article-cannot-be-faked t)
1066         (return)))
1067
1068     (when (memq 'default methods)
1069       (setq article-cannot-be-faked t))
1070
1071     (when (and autodetect
1072                (not (equal first-method 'none)))
1073     (mapcar
1074      (lambda (article)
1075        (let ((id (spam-fetch-field-message-id-fast article))
1076              (subject (spam-fetch-field-subject-fast article))
1077              (sender (spam-fetch-field-from-fast article))
1078              registry-lookup)
1079          
1080          (unless id
1081            (gnus-error 5 "Article %d has no message ID!" article))
1082          
1083          (when (and id spam-log-to-registry)
1084            (setq registry-lookup (spam-log-registration-type id 'incoming))
1085            (when registry-lookup
1086              (gnus-message
1087               9
1088               "spam-find-spam: message %s was already registered incoming"
1089               id)))
1090
1091          (let* ((spam-split-symbolic-return t)
1092                 (spam-split-symbolic-return-positive t)
1093                 (fake-headers (spam-generate-fake-headers article))
1094                 (split-return
1095                  (or registry-lookup
1096                      (with-temp-buffer
1097                        (if article-cannot-be-faked
1098                            (gnus-request-article-this-buffer
1099                             article
1100                             group)
1101                          ;; else, we fake the article
1102                          (when fake-headers (insert fake-headers)))
1103                        (if (or (null first-method)
1104                                (equal first-method 'default))
1105                            (spam-split)
1106                          (apply 'spam-split methods))))))
1107            (if (equal split-return 'spam)
1108                (gnus-summary-mark-article article gnus-spam-mark))
1109            
1110            (when (and id split-return spam-log-to-registry)
1111              (when (zerop (gnus-registry-group-count id))
1112                (gnus-registry-add-group
1113                 id group subject sender))
1114                
1115              (unless registry-lookup
1116                (spam-log-processing-to-registry
1117                 id
1118                 'incoming
1119                 split-return
1120                 spam-split-last-successful-check
1121                 group))))))
1122     articles))))
1123
1124 (defvar spam-registration-functions
1125   ;; first the ham register, second the spam register function
1126   ;; third the ham unregister, fourth the spam unregister function
1127   '((spam-use-blacklist  nil
1128                          spam-blacklist-register-routine
1129                          nil
1130                          spam-blacklist-unregister-routine)
1131     (spam-use-whitelist  spam-whitelist-register-routine
1132                          nil
1133                          spam-whitelist-unregister-routine
1134                          nil)
1135     (spam-use-BBDB       spam-BBDB-register-routine
1136                          nil
1137                          spam-BBDB-unregister-routine
1138                          nil)
1139     (spam-use-ifile      spam-ifile-register-ham-routine
1140                          spam-ifile-register-spam-routine
1141                          spam-ifile-unregister-ham-routine
1142                          spam-ifile-unregister-spam-routine)
1143     (spam-use-spamoracle spam-spamoracle-learn-ham
1144                          spam-spamoracle-learn-spam
1145                          spam-spamoracle-unlearn-ham
1146                          spam-spamoracle-unlearn-spam)
1147     (spam-use-stat       spam-stat-register-ham-routine
1148                          spam-stat-register-spam-routine
1149                          spam-stat-unregister-ham-routine
1150                          spam-stat-unregister-spam-routine)
1151     ;; note that spam-use-gmane is not a legitimate check
1152     (spam-use-gmane      nil
1153                          spam-report-gmane-register-routine
1154                          ;; does Gmane support unregistration?
1155                          nil
1156                          nil)
1157     (spam-use-spamassassin spam-spamassassin-register-ham-routine
1158                            spam-spamassassin-register-spam-routine
1159                            spam-spamassassin-unregister-ham-routine
1160                            spam-spamassassin-unregister-spam-routine)
1161     (spam-use-bogofilter spam-bogofilter-register-ham-routine
1162                          spam-bogofilter-register-spam-routine
1163                          spam-bogofilter-unregister-ham-routine
1164                          spam-bogofilter-unregister-spam-routine))
1165   "The spam-registration-functions list contains pairs
1166 associating a parameter variable with the ham and spam
1167 registration functions, and the ham and spam unregistration
1168 functions")
1169
1170 (defun spam-classification-valid-p (classification)
1171   (or  (eq classification 'spam)
1172        (eq classification 'ham)))
1173
1174 (defun spam-process-type-valid-p (process-type)
1175   (or  (eq process-type 'incoming)
1176        (eq process-type 'process)))
1177
1178 (defun spam-registration-check-valid-p (check)
1179   (assoc check spam-registration-functions))
1180
1181 (defun spam-unregistration-check-valid-p (check)
1182   (assoc check spam-registration-functions))
1183
1184 (defun spam-registration-function (classification check)
1185   (let ((flist (cdr-safe (assoc check spam-registration-functions))))
1186     (if (eq classification 'spam)
1187         (nth 1 flist)
1188       (nth 0 flist))))
1189
1190 (defun spam-unregistration-function (classification check)
1191   (let ((flist (cdr-safe (assoc check spam-registration-functions))))
1192     (if (eq classification 'spam)
1193         (nth 3 flist)
1194       (nth 2 flist))))
1195
1196 (defun spam-list-articles (articles classification)
1197   (let ((mark-check (if (eq classification 'spam)
1198                         'spam-group-spam-mark-p
1199                       'spam-group-ham-mark-p))
1200         list mark-cache-yes mark-cache-no)
1201     (dolist (article articles)
1202       (let ((mark (gnus-summary-article-mark article)))
1203         (unless (memq mark mark-cache-no)
1204           (if (memq mark mark-cache-yes)
1205               (push article list)
1206             ;; else, we have to actually check the mark
1207             (if (funcall mark-check
1208                          gnus-newsgroup-name
1209                          mark)
1210                 (progn
1211                   (push article list)
1212                   (push mark mark-cache-yes))
1213               (push mark mark-cache-no))))))
1214     list))
1215
1216 (defun spam-register-routine (classification
1217                               check
1218                               &optional unregister
1219                               specific-articles)
1220   (when (and (spam-classification-valid-p classification)
1221              (spam-registration-check-valid-p check))
1222     (let* ((register-function
1223             (spam-registration-function classification check))
1224            (unregister-function
1225             (spam-unregistration-function classification check))
1226            (run-function (if unregister
1227                              unregister-function
1228                            register-function))
1229            (log-function (if unregister
1230                              'spam-log-undo-registration
1231                            'spam-log-processing-to-registry))
1232            article articles)
1233
1234       (when run-function
1235         ;; make list of articles, using specific-articles if given
1236         (setq articles (or specific-articles
1237                            (spam-list-articles
1238                             gnus-newsgroup-articles
1239                             classification)))
1240         ;; process them
1241         (gnus-message 5 "%s %d %s articles with classification %s, check %s"
1242                       (if unregister "Unregistering" "Registering")
1243                       (length articles)
1244                       (if specific-articles "specific" "")
1245                       (symbol-name classification)
1246                       (symbol-name check))
1247         (funcall run-function articles)
1248         ;; now log all the registrations (or undo them, depending on unregister)
1249         (dolist (article articles)
1250           (funcall log-function
1251                    (spam-fetch-field-message-id-fast article)
1252                    'process
1253                    classification
1254                    check
1255                    gnus-newsgroup-name))))))
1256
1257 ;;; log a ham- or spam-processor invocation to the registry
1258 (defun spam-log-processing-to-registry (id type classification check group)
1259   (when spam-log-to-registry
1260     (if (and (stringp id)
1261              (stringp group)
1262              (spam-process-type-valid-p type)
1263              (spam-classification-valid-p classification)
1264              (spam-registration-check-valid-p check))
1265         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1266               (cell (list classification check group)))
1267           (push cell cell-list)
1268           (gnus-registry-store-extra-entry
1269            id
1270            type
1271            cell-list))
1272
1273       (gnus-error 5 (format "%s called with bad ID, type, classification, check, or group"
1274                             "spam-log-processing-to-registry")))))
1275
1276 ;;; check if a ham- or spam-processor registration has been done
1277 (defun spam-log-registered-p (id type)
1278   (when spam-log-to-registry
1279     (if (and (stringp id)
1280              (spam-process-type-valid-p type))
1281         (cdr-safe (gnus-registry-fetch-extra id type))
1282       (progn
1283         (gnus-error 5 (format "%s called with bad ID, type, classification, or check"
1284                               "spam-log-registered-p"))
1285         nil))))
1286
1287 ;;; check what a ham- or spam-processor registration says
1288 ;;; returns nil if conflicting registrations are found
1289 (defun spam-log-registration-type (id type)
1290   (let ((count 0)
1291         decision)
1292     (dolist (reg (spam-log-registered-p id type))
1293       (let ((classification (nth 0 reg)))
1294         (when (spam-classification-valid-p classification)
1295           (when (and decision
1296                      (not (eq classification decision)))
1297             (setq count (+ 1 count)))
1298           (setq decision classification))))
1299     (if (< 0 count)
1300         nil
1301       decision)))
1302
1303 ;;; check if a ham- or spam-processor registration needs to be undone
1304 (defun spam-log-unregistration-needed-p (id type classification check)
1305   (when spam-log-to-registry
1306     (if (and (stringp id)
1307              (spam-process-type-valid-p type)
1308              (spam-classification-valid-p classification)
1309              (spam-registration-check-valid-p check))
1310         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1311               found)
1312           (dolist (cell cell-list)
1313             (unless found
1314               (when (and (eq classification (nth 0 cell))
1315                          (eq check (nth 1 cell)))
1316                 (setq found t))))
1317           found)
1318       (progn
1319         (gnus-error 5 (format "%s called with bad ID, type, classification, or check"
1320                               "spam-log-unregistration-needed-p"))
1321         nil))))
1322
1323
1324 ;;; undo a ham- or spam-processor registration (the group is not used)
1325 (defun spam-log-undo-registration (id type classification check &optional group)
1326   (when (and spam-log-to-registry
1327              (spam-log-unregistration-needed-p id type classification check))
1328     (if (and (stringp id)
1329              (spam-process-type-valid-p type)
1330              (spam-classification-valid-p classification)
1331              (spam-registration-check-valid-p check))
1332         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1333               new-cell-list found)
1334           (dolist (cell cell-list)
1335             (unless (and (eq classification (nth 0 cell))
1336                          (eq check (nth 1 cell)))
1337               (push cell new-cell-list)))
1338           (gnus-registry-store-extra-entry
1339            id
1340            type
1341            new-cell-list))
1342       (progn
1343         (gnus-error 5 (format "%s called with bad ID, type, check, or group"
1344                               "spam-log-undo-registration"))
1345         nil))))
1346
1347 ;;; set up IMAP widening if it's necessary
1348 (defun spam-setup-widening ()
1349   (dolist (check spam-list-of-statistical-checks)
1350     (when (symbol-value check)
1351       (setq nnimap-split-download-body-default t))))
1352
1353 \f
1354 ;;;; Regex body
1355
1356 (defun spam-check-regex-body ()
1357   (let ((spam-regex-headers-ham spam-regex-body-ham)
1358         (spam-regex-headers-spam spam-regex-body-spam))
1359     (spam-check-regex-headers t)))
1360
1361 \f
1362 ;;;; Regex headers
1363
1364 (defun spam-check-regex-headers (&optional body)
1365   (let ((type (if body "body" "header"))
1366         (spam-split-group (if spam-split-symbolic-return
1367                               'spam
1368                             spam-split-group))
1369         ret found)
1370     (dolist (h-regex spam-regex-headers-ham)
1371       (unless found
1372         (goto-char (point-min))
1373         (when (re-search-forward h-regex nil t)
1374           (message "Ham regex %s search positive." type)
1375           (setq found t))))
1376     (dolist (s-regex spam-regex-headers-spam)
1377       (unless found
1378         (goto-char (point-min))
1379         (when (re-search-forward s-regex nil t)
1380           (message "Spam regex %s search positive." type)
1381           (setq found t)
1382           (setq ret spam-split-group))))
1383     ret))
1384
1385 \f
1386 ;;;; Blackholes.
1387
1388 (defun spam-reverse-ip-string (ip)
1389   (when (stringp ip)
1390     (mapconcat 'identity
1391                (nreverse (split-string ip "\\."))
1392                ".")))
1393
1394 (defun spam-check-blackholes ()
1395   "Check the Received headers for blackholed relays."
1396   (let ((headers (message-fetch-field "received"))
1397         (spam-split-group (if spam-split-symbolic-return
1398                               'spam
1399                             spam-split-group))
1400         ips matches)
1401     (when headers
1402       (with-temp-buffer
1403         (insert headers)
1404         (goto-char (point-min))
1405         (gnus-message 5 "Checking headers for relay addresses")
1406         (while (re-search-forward
1407                 "\\([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\\)" nil t)
1408           (gnus-message 9 "Blackhole search found host IP %s." (match-string 1))
1409           (push (spam-reverse-ip-string (match-string 1))
1410                 ips)))
1411       (dolist (server spam-blackhole-servers)
1412         (dolist (ip ips)
1413           (unless (and spam-blackhole-good-server-regex
1414                        ;; match the good-server-regex against the reversed (again) IP string
1415                        (string-match
1416                         spam-blackhole-good-server-regex
1417                         (spam-reverse-ip-string ip)))
1418             (unless matches
1419               (let ((query-string (concat ip "." server)))
1420                 (if spam-use-dig
1421                     (let ((query-result (query-dig query-string)))
1422                       (when query-result
1423                         (gnus-message 5 "(DIG): positive blackhole check '%s'"
1424                                       query-result)
1425                         (push (list ip server query-result)
1426                               matches)))
1427                   ;; else, if not using dig.el
1428                   (when (query-dns query-string)
1429                     (gnus-message 5 "positive blackhole check")
1430                     (push (list ip server (query-dns query-string 'TXT))
1431                           matches)))))))))
1432     (when matches
1433       spam-split-group)))
1434 \f
1435 ;;;; Hashcash.
1436
1437 (condition-case nil
1438     (progn
1439       (require 'hashcash)
1440
1441       (defun spam-check-hashcash ()
1442         "Check the headers for hashcash payments."
1443         (mail-check-payment)))   ;mail-check-payment returns a boolean
1444
1445   (file-error (progn
1446                 (defalias 'mail-check-payment 'ignore)
1447                 (defalias 'spam-check-hashcash 'ignore))))
1448 \f
1449 ;;;; BBDB
1450
1451 ;;; original idea for spam-check-BBDB from Alexander Kotelnikov
1452 ;;; <sacha@giotto.sj.ru>
1453
1454 ;; all this is done inside a condition-case to trap errors
1455
1456 (condition-case nil
1457     (progn
1458       (require 'bbdb)
1459       (require 'bbdb-com)
1460
1461       ;; when the BBDB changes, we want to clear out our cache
1462       (defun spam-clear-cache-BBDB (&rest immaterial)
1463         (spam-clear-cache 'spam-use-BBDB))
1464
1465       (add-hook 'bbdb-change-hook 'spam-clear-cache-BBDB)
1466
1467       (defun spam-enter-ham-BBDB (addresses &optional remove)
1468         "Enter an address into the BBDB; implies ham (non-spam) sender"
1469         (dolist (from addresses)
1470           (when (stringp from)
1471             (let* ((parsed-address (gnus-extract-address-components from))
1472                    (name (or (nth 0 parsed-address) "Ham Sender"))
1473                    (remove-function (if remove
1474                                         'bbdb-delete-record-internal
1475                                       'ignore))
1476                    (net-address (nth 1 parsed-address))
1477                    (record (and net-address
1478                                 (bbdb-search-simple nil net-address))))
1479               (when net-address
1480                 (gnus-message 5 "%s address %s %s BBDB"
1481                               (if remove "Deleting" "Adding")
1482                               from
1483                               (if remove "from" "to"))
1484                 (if record
1485                     (funcall remove-function record)
1486                   (bbdb-create-internal name nil net-address nil nil
1487                                         "ham sender added by spam.el")))))))
1488
1489       (defun spam-BBDB-register-routine (articles &optional unregister)
1490         (let (addresses)
1491           (dolist (article articles)
1492             (when (stringp (spam-fetch-field-from-fast article))
1493               (push (spam-fetch-field-from-fast article) addresses)))
1494           ;; now do the register/unregister action
1495           (spam-enter-ham-BBDB addresses unregister)))
1496
1497       (defun spam-BBDB-unregister-routine (articles)
1498         (spam-BBDB-register-routine articles t))
1499
1500       (defun spam-check-BBDB ()
1501         "Mail from people in the BBDB is classified as ham or non-spam"
1502         (let ((who (message-fetch-field "from"))
1503               (spam-split-group (if spam-split-symbolic-return
1504                                     'spam
1505                                   spam-split-group))
1506               bbdb-cache bbdb-hashtable)
1507           (when spam-cache-lookups
1508             (setq bbdb-cache (gethash 'spam-use-BBDB spam-caches))
1509             (unless bbdb-cache
1510               (setq bbdb-cache
1511                     ;; this is the expanded (bbdb-hashtable) macro
1512                     ;; without the debugging support
1513                     (with-current-buffer (bbdb-buffer)
1514                       (save-excursion
1515                         (save-window-excursion
1516                           (bbdb-records nil t)
1517                           bbdb-hashtable))))
1518               (puthash 'spam-use-BBDB bbdb-cache spam-caches)))
1519           (when who
1520             (setq who (nth 1 (gnus-extract-address-components who)))
1521             (if
1522                 (if spam-cache-lookups
1523                     (symbol-value
1524                      (intern-soft who bbdb-cache))
1525                   (bbdb-search-simple nil who))
1526                 t
1527               (if spam-use-BBDB-exclusive
1528                   spam-split-group
1529                 nil))))))
1530
1531   (file-error (progn
1532                 (defalias 'bbdb-search-simple 'ignore)
1533                 (defalias 'bbdb-records 'ignore)
1534                 (defalias 'bbdb-buffer 'ignore)
1535                 (defalias 'spam-check-BBDB 'ignore)
1536                 (defalias 'spam-BBDB-register-routine 'ignore)
1537                 (defalias 'spam-enter-ham-BBDB 'ignore)
1538                 (defalias 'bbdb-create-internal 'ignore)
1539                 (defalias 'bbdb-delete-record-internal 'ignore)
1540                 (defalias 'bbdb-records 'ignore))))
1541
1542 \f
1543 ;;;; ifile
1544
1545 ;;; check the ifile backend; return nil if the mail was NOT classified
1546 ;;; as spam
1547
1548 (defun spam-get-ifile-database-parameter ()
1549   "Get the command-line parameter for ifile's database from
1550   spam-ifile-database-path."
1551   (if spam-ifile-database-path
1552       (format "--db-file=%s" spam-ifile-database-path)
1553     nil))
1554
1555 (defun spam-check-ifile ()
1556   "Check the ifile backend for the classification of this message."
1557   (let ((article-buffer-name (buffer-name))
1558         (spam-split-group (if spam-split-symbolic-return
1559                               'spam
1560                             spam-split-group))
1561         category return)
1562     (with-temp-buffer
1563       (let ((temp-buffer-name (buffer-name))
1564             (db-param (spam-get-ifile-database-parameter)))
1565         (save-excursion
1566           (set-buffer article-buffer-name)
1567           (apply 'call-process-region
1568                  (point-min) (point-max) spam-ifile-path
1569                  nil temp-buffer-name nil "-c"
1570                  (if db-param `(,db-param "-q") `("-q"))))
1571         ;; check the return now (we're back in the temp buffer)
1572         (goto-char (point-min))
1573         (if (not (eobp))
1574             (setq category (buffer-substring (point) (point-at-eol))))
1575         (when (not (zerop (length category))) ; we need a category here
1576           (if spam-ifile-all-categories
1577               (setq return category)
1578             ;; else, if spam-ifile-all-categories is not set...
1579             (when (string-equal spam-ifile-spam-category category)
1580               (setq return spam-split-group)))))) ; note return is nil otherwise
1581     return))
1582
1583 (defun spam-ifile-register-with-ifile (articles category &optional unregister)
1584   "Register an article, given as a string, with a category.
1585 Uses `gnus-newsgroup-name' if category is nil (for ham registration)."
1586   (let ((category (or category gnus-newsgroup-name))
1587         (add-or-delete-option (if unregister "-d" "-i"))
1588         (db (spam-get-ifile-database-parameter))
1589         parameters)
1590     (with-temp-buffer
1591       (dolist (article articles)
1592         (let ((article-string (spam-get-article-as-string article)))
1593           (when (stringp article-string)
1594             (insert article-string))))
1595       (apply 'call-process-region
1596              (point-min) (point-max) spam-ifile-path
1597              nil nil nil
1598              add-or-delete-option category
1599              (if db `(,db "-h") `("-h"))))))
1600
1601 (defun spam-ifile-register-spam-routine (articles &optional unregister)
1602   (spam-ifile-register-with-ifile articles spam-ifile-spam-category unregister))
1603
1604 (defun spam-ifile-unregister-spam-routine (articles)
1605   (spam-ifile-register-spam-routine articles t))
1606
1607 (defun spam-ifile-register-ham-routine (articles &optional unregister)
1608   (spam-ifile-register-with-ifile articles spam-ifile-ham-category unregister))
1609
1610 (defun spam-ifile-unregister-ham-routine (articles)
1611   (spam-ifile-register-ham-routine articles t))
1612
1613 \f
1614 ;;;; spam-stat
1615
1616 (condition-case nil
1617     (progn
1618       (let ((spam-stat-install-hooks nil))
1619         (require 'spam-stat))
1620
1621       (defun spam-check-stat ()
1622         "Check the spam-stat backend for the classification of this message"
1623         (let ((spam-split-group (if spam-split-symbolic-return
1624                                     'spam
1625                                   spam-split-group))
1626               (spam-stat-split-fancy-spam-group spam-split-group) ; override
1627               (spam-stat-buffer (buffer-name)) ; stat the current buffer
1628               category return)
1629           (spam-stat-split-fancy)))
1630
1631       (defun spam-stat-register-spam-routine (articles &optional unregister)
1632         (dolist (article articles)
1633           (let ((article-string (spam-get-article-as-string article)))
1634             (with-temp-buffer
1635               (insert article-string)
1636               (if unregister
1637                   (spam-stat-buffer-change-to-non-spam)
1638               (spam-stat-buffer-is-spam))))))
1639
1640       (defun spam-stat-unregister-spam-routine (articles)
1641         (spam-stat-register-spam-routine articles t))
1642
1643       (defun spam-stat-register-ham-routine (articles &optional unregister)
1644         (dolist (article articles)
1645           (let ((article-string (spam-get-article-as-string article)))
1646             (with-temp-buffer
1647               (insert article-string)
1648               (if unregister
1649                   (spam-stat-buffer-change-to-spam)
1650               (spam-stat-buffer-is-non-spam))))))
1651
1652       (defun spam-stat-unregister-ham-routine (articles)
1653         (spam-stat-register-ham-routine articles t))
1654
1655       (defun spam-maybe-spam-stat-load ()
1656         (when spam-use-stat (spam-stat-load)))
1657
1658       (defun spam-maybe-spam-stat-save ()
1659         (when spam-use-stat (spam-stat-save))))
1660
1661   (file-error (progn
1662                 (defalias 'spam-stat-load 'ignore)
1663                 (defalias 'spam-stat-save 'ignore)
1664                 (defalias 'spam-maybe-spam-stat-load 'ignore)
1665                 (defalias 'spam-maybe-spam-stat-save 'ignore)
1666                 (defalias 'spam-stat-register-ham-routine 'ignore)
1667                 (defalias 'spam-stat-unregister-ham-routine 'ignore)
1668                 (defalias 'spam-stat-register-spam-routine 'ignore)
1669                 (defalias 'spam-stat-unregister-spam-routine 'ignore)
1670                 (defalias 'spam-stat-buffer-is-spam 'ignore)
1671                 (defalias 'spam-stat-buffer-change-to-spam 'ignore)
1672                 (defalias 'spam-stat-buffer-is-non-spam 'ignore)
1673                 (defalias 'spam-stat-buffer-change-to-non-spam 'ignore)
1674                 (defalias 'spam-stat-split-fancy 'ignore)
1675                 (defalias 'spam-check-stat 'ignore))))
1676
1677 \f
1678
1679 ;;;; Blacklists and whitelists.
1680
1681 (defvar spam-whitelist-cache nil)
1682 (defvar spam-blacklist-cache nil)
1683
1684 (defun spam-kill-whole-line ()
1685   (beginning-of-line)
1686   (let ((kill-whole-line t))
1687     (kill-line)))
1688
1689 ;;; address can be a list, too
1690 (defun spam-enter-whitelist (address &optional remove)
1691   "Enter ADDRESS (list or single) into the whitelist.
1692 With a non-nil REMOVE, remove them."
1693   (interactive "sAddress: ")
1694   (spam-enter-list address spam-whitelist remove)
1695   (setq spam-whitelist-cache nil)
1696   (spam-clear-cache 'spam-use-whitelist))
1697
1698 ;;; address can be a list, too
1699 (defun spam-enter-blacklist (address &optional remove)
1700   "Enter ADDRESS (list or single) into the blacklist.
1701 With a non-nil REMOVE, remove them."
1702   (interactive "sAddress: ")
1703   (spam-enter-list address spam-blacklist remove)
1704   (setq spam-blacklist-cache nil)
1705   (spam-clear-cache 'spam-use-whitelist))
1706
1707 (defun spam-enter-list (addresses file &optional remove)
1708   "Enter ADDRESSES into the given FILE.
1709 Either the whitelist or the blacklist files can be used.  With
1710 REMOVE not nil, remove the ADDRESSES."
1711   (if (stringp addresses)
1712       (spam-enter-list (list addresses) file remove)
1713     ;; else, we have a list of addresses here
1714     (unless (file-exists-p (file-name-directory file))
1715       (make-directory (file-name-directory file) t))
1716     (save-excursion
1717       (set-buffer
1718        (find-file-noselect file))
1719       (dolist (a addresses)
1720         (when (stringp a)
1721           (goto-char (point-min))
1722           (if (re-search-forward (regexp-quote a) nil t)
1723               ;; found the address
1724               (when remove
1725                 (spam-kill-whole-line))
1726             ;; else, the address was not found
1727             (unless remove
1728               (goto-char (point-max))
1729               (unless (bobp)
1730                 (insert "\n"))
1731               (insert a "\n")))))
1732       (save-buffer))))
1733
1734 (defun spam-filelist-build-cache (type)
1735   (let ((cache (if (eq type 'spam-use-blacklist)
1736                    spam-blacklist-cache
1737                  spam-whitelist-cache))
1738         parsed-cache)
1739     (unless (gethash type spam-caches)
1740       (while cache
1741         (let ((address (pop cache)))
1742           (unless (zerop (length address)) ; 0 for a nil address too
1743             (setq address (regexp-quote address))
1744             ;; fix regexp-quote's treatment of user-intended regexes
1745             (while (string-match "\\\\\\*" address)
1746               (setq address (replace-match ".*" t t address))))
1747           (push address parsed-cache)))
1748       (puthash type parsed-cache spam-caches))))
1749
1750 (defun spam-filelist-check-cache (type from)
1751   (when (stringp from)
1752     (spam-filelist-build-cache type)
1753     (let (found)
1754       (dolist (address (gethash type spam-caches))
1755         (when (and address (string-match address from))
1756           (setq found t)
1757           (return)))
1758       found)))
1759
1760 ;;; returns t if the sender is in the whitelist, nil or
1761 ;;; spam-split-group otherwise
1762 (defun spam-check-whitelist ()
1763   ;; FIXME!  Should it detect when file timestamps change?
1764   (let ((spam-split-group (if spam-split-symbolic-return
1765                               'spam
1766                             spam-split-group)))
1767     (unless spam-whitelist-cache
1768       (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
1769     (if (spam-from-listed-p 'spam-use-whitelist)
1770         t
1771       (if spam-use-whitelist-exclusive
1772           spam-split-group
1773         nil))))
1774
1775 (defun spam-check-blacklist ()
1776   ;; FIXME!  Should it detect when file timestamps change?
1777   (let ((spam-split-group (if spam-split-symbolic-return
1778                               'spam
1779                             spam-split-group)))
1780     (unless spam-blacklist-cache
1781       (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
1782     (and (spam-from-listed-p 'spam-use-blacklist) spam-split-group)))
1783
1784 (defun spam-parse-list (file)
1785   (when (file-readable-p file)
1786     (let (contents address)
1787       (with-temp-buffer
1788         (insert-file-contents file)
1789         (while (not (eobp))
1790           (setq address (buffer-substring (point) (point-at-eol)))
1791           (forward-line 1)
1792           ;; insert the e-mail address if detected, otherwise the raw data
1793           (unless (zerop (length address))
1794             (let ((pure-address (nth 1 (gnus-extract-address-components address))))
1795               (push (or pure-address address) contents)))))
1796       (nreverse contents))))
1797
1798 (defun spam-from-listed-p (type)
1799   (let ((from (message-fetch-field "from"))
1800         found)
1801     (spam-filelist-check-cache type from)))
1802
1803 (defun spam-filelist-register-routine (articles blacklist &optional unregister)
1804   (let ((de-symbol (if blacklist 'spam-use-whitelist 'spam-use-blacklist))
1805         (declassification (if blacklist 'ham 'spam))
1806         (enter-function
1807          (if blacklist 'spam-enter-blacklist 'spam-enter-whitelist))
1808         (remove-function
1809          (if blacklist 'spam-enter-whitelist 'spam-enter-blacklist))
1810         from addresses unregister-list)
1811     (dolist (article articles)
1812       (let ((from (spam-fetch-field-from-fast article))
1813             (id (spam-fetch-field-message-id-fast article))
1814             sender-ignored)
1815         (when (stringp from)
1816           (dolist (ignore-regex spam-blacklist-ignored-regexes)
1817             (when (and (not sender-ignored)
1818                        (stringp ignore-regex)
1819                        (string-match ignore-regex from))
1820               (setq sender-ignored t)))
1821           ;; remember the messages we need to unregister, unless remove is set
1822           (when (and
1823                  (null unregister)
1824                  (spam-log-unregistration-needed-p
1825                   id 'process declassification de-symbol))
1826             (push from unregister-list))
1827           (unless sender-ignored
1828             (push from addresses)))))
1829
1830     (if unregister
1831         (funcall enter-function addresses t) ; unregister all these addresses
1832       ;; else, register normally and unregister what we need to
1833       (funcall remove-function unregister-list t)
1834       (dolist (article unregister-list)
1835         (spam-log-undo-registration
1836          (spam-fetch-field-message-id-fast article)
1837          'process
1838          declassification
1839          de-symbol))
1840       (funcall enter-function addresses nil))))
1841
1842 (defun spam-blacklist-unregister-routine (articles)
1843   (spam-blacklist-register-routine articles t))
1844
1845 (defun spam-blacklist-register-routine (articles &optional unregister)
1846   (spam-filelist-register-routine articles t unregister))
1847
1848 (defun spam-whitelist-unregister-routine (articles)
1849   (spam-whitelist-register-routine articles t))
1850
1851 (defun spam-whitelist-register-routine (articles &optional unregister)
1852   (spam-filelist-register-routine articles nil unregister))
1853
1854 \f
1855 ;;;; Spam-report glue
1856 (defun spam-report-gmane-register-routine (articles)
1857   (when articles
1858     (apply 'spam-report-gmane articles)))
1859
1860 \f
1861 ;;;; Bogofilter
1862 (defun spam-check-bogofilter-headers (&optional score)
1863   (let ((header (message-fetch-field spam-bogofilter-header))
1864         (spam-split-group (if spam-split-symbolic-return
1865                               'spam
1866                             spam-split-group)))
1867     (when header                        ; return nil when no header
1868       (if score                         ; scoring mode
1869           (if (string-match "spamicity=\\([0-9.]+\\)" header)
1870               (match-string 1 header)
1871             "0")
1872         ;; spam detection mode
1873         (when (string-match spam-bogofilter-bogosity-positive-spam-header
1874                             header)
1875           spam-split-group)))))
1876
1877 ;; return something sensible if the score can't be determined
1878 (defun spam-bogofilter-score ()
1879   "Get the Bogofilter spamicity score"
1880   (interactive)
1881   (save-window-excursion
1882     (gnus-summary-show-article t)
1883     (set-buffer gnus-article-buffer)
1884     (let ((score (or (spam-check-bogofilter-headers t)
1885                      (spam-check-bogofilter t))))
1886       (gnus-summary-show-article)
1887       (message "Spamicity score %s" score)
1888       (or score "0"))))
1889
1890 (defun spam-check-bogofilter (&optional score)
1891   "Check the Bogofilter backend for the classification of this message"
1892   (let ((article-buffer-name (buffer-name))
1893         (db spam-bogofilter-database-directory)
1894         return)
1895     (with-temp-buffer
1896       (let ((temp-buffer-name (buffer-name)))
1897         (save-excursion
1898           (set-buffer article-buffer-name)
1899           (apply 'call-process-region
1900                  (point-min) (point-max)
1901                  spam-bogofilter-path
1902                  nil temp-buffer-name nil
1903                  (if db `("-d" ,db "-v") `("-v"))))
1904         (setq return (spam-check-bogofilter-headers score))))
1905     return))
1906
1907 (defun spam-bogofilter-register-with-bogofilter (articles
1908                                                  spam
1909                                                  &optional unregister)
1910   "Register an article, given as a string, as spam or non-spam."
1911   (dolist (article articles)
1912     (let ((article-string (spam-get-article-as-string article))
1913           (db spam-bogofilter-database-directory)
1914           (switch (if unregister
1915                       (if spam
1916                           spam-bogofilter-spam-strong-switch
1917                         spam-bogofilter-ham-strong-switch)
1918                     (if spam
1919                         spam-bogofilter-spam-switch
1920                       spam-bogofilter-ham-switch))))
1921       (when (stringp article-string)
1922         (with-temp-buffer
1923           (insert article-string)
1924
1925           (apply 'call-process-region
1926                  (point-min) (point-max)
1927                  spam-bogofilter-path
1928                  nil nil nil switch
1929                  (if db `("-d" ,db "-v") `("-v"))))))))
1930
1931 (defun spam-bogofilter-register-spam-routine (articles &optional unregister)
1932   (spam-bogofilter-register-with-bogofilter articles t unregister))
1933
1934 (defun spam-bogofilter-unregister-spam-routine (articles)
1935   (spam-bogofilter-register-spam-routine articles t))
1936
1937 (defun spam-bogofilter-register-ham-routine (articles &optional unregister)
1938   (spam-bogofilter-register-with-bogofilter articles nil unregister))
1939
1940 (defun spam-bogofilter-unregister-ham-routine (articles)
1941   (spam-bogofilter-register-ham-routine articles t))
1942
1943
1944 \f
1945 ;;;; spamoracle
1946 (defun spam-check-spamoracle ()
1947   "Run spamoracle on an article to determine whether it's spam."
1948   (let ((article-buffer-name (buffer-name))
1949         (spam-split-group (if spam-split-symbolic-return
1950                               'spam
1951                             spam-split-group)))
1952     (with-temp-buffer
1953       (let ((temp-buffer-name (buffer-name)))
1954         (save-excursion
1955           (set-buffer article-buffer-name)
1956           (let ((status
1957                  (apply 'call-process-region
1958                         (point-min) (point-max)
1959                         spam-spamoracle-binary
1960                         nil temp-buffer-name nil
1961                         (if spam-spamoracle-database
1962                             `("-f" ,spam-spamoracle-database "mark")
1963                           '("mark")))))
1964             (if (eq 0 status)
1965                 (progn
1966                   (set-buffer temp-buffer-name)
1967                   (goto-char (point-min))
1968                   (when (re-search-forward "^X-Spam: yes;" nil t)
1969                     spam-split-group))
1970               (error "Error running spamoracle" status))))))))
1971
1972 (defun spam-spamoracle-learn (articles article-is-spam-p &optional unregister)
1973   "Run spamoracle in training mode."
1974   (with-temp-buffer
1975     (let ((temp-buffer-name (buffer-name)))
1976       (save-excursion
1977         (goto-char (point-min))
1978         (dolist (article articles)
1979           (insert (spam-get-article-as-string article)))
1980         (let* ((arg (if (spam-xor unregister article-is-spam-p)
1981                         "-spam"
1982                       "-good"))
1983                (status
1984                 (apply 'call-process-region
1985                        (point-min) (point-max)
1986                        spam-spamoracle-binary
1987                        nil temp-buffer-name nil
1988                        (if spam-spamoracle-database
1989                            `("-f" ,spam-spamoracle-database
1990                              "add" ,arg)
1991                          `("add" ,arg)))))
1992           (when (not (eq 0 status))
1993             (error "Error running spamoracle" status)))))))
1994
1995 (defun spam-spamoracle-learn-ham (articles &optional unregister)
1996   (spam-spamoracle-learn articles nil unregister))
1997
1998 (defun spam-spamoracle-unlearn-ham (articles &optional unregister)
1999   (spam-spamoracle-learn-ham articles t))
2000
2001 (defun spam-spamoracle-learn-spam (articles &optional unregister)
2002   (spam-spamoracle-learn articles t unregister))
2003
2004 (defun spam-spamoracle-unlearn-spam (articles &optional unregister)
2005   (spam-spamoracle-learn-spam articles t))
2006
2007 \f
2008 ;;;; SpamAssassin
2009 ;;; based mostly on the bogofilter code
2010 (defun spam-check-spamassassin-headers (&optional score)
2011   "Check the SpamAssassin headers for the classification of this message."
2012   (if score                             ; scoring mode
2013       (let ((header (message-fetch-field spam-spamassassin-spam-status-header)))
2014         (when header
2015           (if (string-match "hits=\\(-?[0-9.]+\\)" header)
2016               (match-string 1 header)
2017             "0")))
2018     ;; spam detection mode
2019     (let ((header (message-fetch-field spam-spamassassin-spam-flag-header))
2020           (spam-split-group (if spam-split-symbolic-return
2021                                  'spam
2022                                spam-split-group)))
2023           (when header                  ; return nil when no header
2024             (when (string-match spam-spamassassin-positive-spam-flag-header
2025                                 header)
2026               spam-split-group)))))
2027
2028 (defun spam-check-spamassassin (&optional score)
2029   "Check the SpamAssassin backend for the classification of this message."
2030   (let ((article-buffer-name (buffer-name)))
2031     (with-temp-buffer
2032       (let ((temp-buffer-name (buffer-name)))
2033         (save-excursion
2034           (set-buffer article-buffer-name)
2035           (apply 'call-process-region
2036                  (point-min) (point-max) spam-spamassassin-path
2037                  nil temp-buffer-name nil spam-spamassassin-arguments))
2038         ;; check the return now (we're back in the temp buffer)
2039         (goto-char (point-min))
2040         (spam-check-spamassassin-headers score)))))
2041
2042 ;; return something sensible if the score can't be determined
2043 (defun spam-spamassassin-score ()
2044   "Get the SpamAssassin score"
2045   (interactive)
2046   (save-window-excursion
2047     (gnus-summary-show-article t)
2048     (set-buffer gnus-article-buffer)
2049     (let ((score (or (spam-check-spamassassin-headers t)
2050                      (spam-check-spamassassin t))))
2051       (gnus-summary-show-article)
2052       (message "SpamAssassin score %s" score)
2053       (or score "0"))))
2054
2055 (defun spam-spamassassin-register-with-sa-learn (articles spam
2056                                                  &optional unregister)
2057   "Register articles with spamassassin's sa-learn as spam or non-spam."
2058   (if articles
2059       (let ((action (if unregister spam-sa-learn-unregister-switch
2060                       (if spam spam-sa-learn-spam-switch
2061                         spam-sa-learn-ham-switch)))
2062             (summary-buffer-name (buffer-name)))
2063         (with-temp-buffer
2064           ;; group the articles into mbox format
2065           (dolist (article articles)
2066             (let (article-string)
2067               (save-excursion
2068                 (set-buffer summary-buffer-name)
2069                 (setq article-string (spam-get-article-as-string article)))
2070               (when (stringp article-string)
2071                 (insert "From \n") ; mbox separator (sa-learn only checks the
2072                                    ; first five chars, so we can get away with
2073                                    ; a bogus line))
2074                 (insert article-string)
2075                 (insert "\n"))))
2076           ;; call sa-learn on all messages at the same time
2077           (apply 'call-process-region
2078                  (point-min) (point-max)
2079                  spam-sa-learn-path
2080                  nil nil nil "--mbox"
2081                  (if spam-sa-learn-rebuild
2082                      (list action)
2083                    `("--no-rebuild" ,action)))))))
2084
2085 (defun spam-spamassassin-register-spam-routine (articles &optional unregister)
2086   (spam-spamassassin-register-with-sa-learn articles t unregister))
2087
2088 (defun spam-spamassassin-register-ham-routine (articles &optional unregister)
2089   (spam-spamassassin-register-with-sa-learn articles nil unregister))
2090
2091 (defun spam-assassin-register-spam-routine (articles)
2092   (spam-spamassassin-register-with-sa-learn articles t t))
2093
2094 (defun spam-assassin-register-ham-routine (articles)
2095   (spam-spamassassin-register-with-sa-learn articles nil t))
2096 \f
2097 ;;;; Hooks
2098
2099 ;;;###autoload
2100 (defun spam-initialize ()
2101   "Install the spam.el hooks and do other initialization"
2102   (interactive)
2103   (setq spam-install-hooks t)
2104   ;; TODO: How do we redo this every time spam-face is customized?
2105   (push '((eq mark gnus-spam-mark) . spam-face)
2106         gnus-summary-highlight)
2107   ;; Add hooks for loading and saving the spam stats
2108   (add-hook 'gnus-save-newsrc-hook 'spam-maybe-spam-stat-save)
2109   (add-hook 'gnus-get-top-new-news-hook 'spam-maybe-spam-stat-load)
2110   (add-hook 'gnus-startup-hook 'spam-maybe-spam-stat-load)
2111   (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
2112   (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
2113   (add-hook 'gnus-get-new-news-hook 'spam-setup-widening)
2114   (add-hook 'gnus-summary-prepared-hook 'spam-find-spam))
2115
2116 (defun spam-unload-hook ()
2117   "Uninstall the spam.el hooks"
2118   (interactive)
2119   (remove-hook 'gnus-save-newsrc-hook 'spam-maybe-spam-stat-save)
2120   (remove-hook 'gnus-get-top-new-news-hook 'spam-maybe-spam-stat-load)
2121   (remove-hook 'gnus-startup-hook 'spam-maybe-spam-stat-load)
2122   (remove-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
2123   (remove-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
2124   (remove-hook 'gnus-get-new-news-hook 'spam-setup-widening)
2125   (remove-hook 'gnus-summary-prepare-hook 'spam-find-spam))
2126
2127 (when spam-install-hooks
2128   (spam-initialize))
2129
2130 (provide 'spam)
2131
2132 ;;; spam.el ends here