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