(mail-source-delete-old-incoming-confirm): Fixed
[gnus] / lisp / mail-source.el
1 ;;; mail-source.el --- functions for fetching mail
2 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: news, mail
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 ;;; Code:
27
28 (eval-when-compile
29   (require 'cl)
30   (require 'imap)
31   (eval-when-compile (defvar display-time-mail-function)))
32 (eval-and-compile
33   (autoload 'pop3-movemail "pop3")
34   (autoload 'pop3-get-message-count "pop3")
35   (autoload 'nnheader-cancel-timer "nnheader")
36   (autoload 'nnheader-run-at-time "nnheader"))
37 (require 'format-spec)
38 (require 'mm-util)
39 (require 'message) ;; for `message-directory'
40
41 (defgroup mail-source nil
42   "The mail-fetching library."
43   :version "21.1"
44   :group 'gnus)
45
46 ;; Define these at compile time to avoid dragging in imap always.
47 (defconst mail-source-imap-authenticators
48   (eval-when-compile
49     (mapcar (lambda (a)
50               (list 'const (car a)))
51      imap-authenticator-alist)))
52 (defconst mail-source-imap-streams
53   (eval-when-compile
54     (mapcar (lambda (a)
55               (list 'const (car a)))
56      imap-stream-alist)))
57
58 (defcustom mail-sources nil
59   "*Where the mail backends will look for incoming mail.
60 This variable is a list of mail source specifiers.
61 See Info node `(gnus)Mail Source Specifiers'."
62   :group 'mail-source
63   :link '(custom-manual "(gnus)Mail Source Specifiers")
64   :type `(repeat
65           (choice :format "%[Value Menu%] %v"
66                   :value (file)
67                   (cons :tag "Spool file"
68                         (const :format "" file)
69                         (checklist :tag "Options" :greedy t
70                                    (group :inline t
71                                           (const :format "" :value :path)
72                                           file)))
73                   (cons :tag "Several files in a directory"
74                         (const :format "" directory)
75                         (checklist :tag "Options" :greedy t
76                                    (group :inline t
77                                           (const :format "" :value :path)
78                                           (directory :tag "Path"))
79                                    (group :inline t
80                                           (const :format "" :value :suffix)
81                                           (string :tag "Suffix"))
82                                    (group :inline t
83                                           (const :format "" :value :predicate)
84                                           (function :tag "Predicate"))
85                                    (group :inline t
86                                           (const :format "" :value :prescript)
87                                           (choice :tag "Prescript"
88                                                   :value nil
89                                                   (string :format "%v")
90                                                   (function :format "%v")))
91                                    (group :inline t
92                                           (const :format "" :value :postscript)
93                                           (choice :tag "Postscript"
94                                                   :value nil
95                                                   (string :format "%v")
96                                                   (function :format "%v")))
97                                    (group :inline t
98                                           (const :format "" :value :plugged)
99                                           (boolean :tag "Plugged"))))
100                   (cons :tag "POP3 server"
101                         (const :format "" pop)
102                         (checklist :tag "Options" :greedy t
103                                    (group :inline t
104                                           (const :format "" :value :server)
105                                           (string :tag "Server"))
106                                    (group :inline t
107                                           (const :format "" :value :port)
108                                           (choice :tag "Port"
109                                                   :value "pop3"
110                                                   (number :format "%v")
111                                                   (string :format "%v")))
112                                    (group :inline t
113                                           (const :format "" :value :user)
114                                           (string :tag "User"))
115                                    (group :inline t
116                                           (const :format "" :value :password)
117                                           (string :tag "Password"))
118                                    (group :inline t
119                                           (const :format "" :value :program)
120                                           (string :tag "Program"))
121                                    (group :inline t
122                                           (const :format "" :value :prescript)
123                                           (choice :tag "Prescript"
124                                                   :value nil
125                                                   (string :format "%v")
126                                                   (function :format "%v")))
127                                    (group :inline t
128                                           (const :format "" :value :postscript)
129                                           (choice :tag "Postscript"
130                                                   :value nil
131                                                   (string :format "%v")
132                                                   (function :format "%v")))
133                                    (group :inline t
134                                           (const :format "" :value :function)
135                                           (function :tag "Function"))
136                                    (group :inline t
137                                           (const :format ""
138                                                  :value :authentication)
139                                           (choice :tag "Authentication"
140                                                   :value apop
141                                                   (const password)
142                                                   (const apop)))
143                                    (group :inline t
144                                           (const :format "" :value :plugged)
145                                           (boolean :tag "Plugged"))))
146                   (cons :tag "Maildir (qmail, postfix...)"
147                         (const :format "" maildir)
148                         (checklist :tag "Options" :greedy t
149                                    (group :inline t
150                                           (const :format "" :value :path)
151                                           (directory :tag "Path"))
152                                    (group :inline t
153                                           (const :format "" :value :plugged)
154                                           (boolean :tag "Plugged"))))
155                   (cons :tag "IMAP server"
156                         (const :format "" imap)
157                         (checklist :tag "Options" :greedy t
158                                    (group :inline t
159                                           (const :format "" :value :server)
160                                           (string :tag "Server"))
161                                    (group :inline t
162                                           (const :format "" :value :port)
163                                           (choice :tag "Port"
164                                                   :value 143
165                                                   number string))
166                                    (group :inline t
167                                           (const :format "" :value :user)
168                                           (string :tag "User"))
169                                    (group :inline t
170                                           (const :format "" :value :password)
171                                           (string :tag "Password"))
172                                    (group :inline t
173                                           (const :format "" :value :stream)
174                                           (choice :tag "Stream"
175                                                   :value network
176                                                   ,@mail-source-imap-streams))
177                                    (group :inline t
178                                           (const :format "" :value :program)
179                                           (string :tag "Program"))
180                                    (group :inline t
181                                           (const :format ""
182                                                  :value :authenticator)
183                                           (choice :tag "Authenticator"
184                                                   :value login
185                                                   ,@mail-source-imap-authenticators))
186                                    (group :inline t
187                                           (const :format "" :value :mailbox)
188                                           (string :tag "Mailbox"
189                                                   :value "INBOX"))
190                                    (group :inline t
191                                           (const :format "" :value :predicate)
192                                           (string :tag "Predicate"
193                                                   :value "UNSEEN UNDELETED"))
194                                    (group :inline t
195                                           (const :format "" :value :fetchflag)
196                                           (string :tag "Fetchflag"
197                                                   :value  "\\Deleted"))
198                                    (group :inline t
199                                           (const :format ""
200                                                  :value :dontexpunge)
201                                           (boolean :tag "Dontexpunge"))
202                                    (group :inline t
203                                           (const :format "" :value :plugged)
204                                           (boolean :tag "Plugged"))))
205                   (cons :tag "Webmail server"
206                         (const :format "" webmail)
207                         (checklist :tag "Options" :greedy t
208                                    (group :inline t
209                                          (const :format "" :value :subtype)
210                                          ;; Should be generated from
211                                          ;; `webmail-type-definition', but we
212                                          ;; can't require webmail without W3.
213                                          (choice :tag "Subtype"
214                                                  :value hotmail
215                                                  (const hotmail)
216                                                  (const yahoo)
217                                                  (const netaddress)
218                                                  (const netscape)
219                                                  (const my-deja)))
220                                    (group :inline t
221                                           (const :format "" :value :user)
222                                           (string :tag "User"))
223                                    (group :inline t
224                                           (const :format "" :value :password)
225                                           (string :tag "Password"))
226                                    (group :inline t
227                                           (const :format ""
228                                                  :value :dontexpunge)
229                                           (boolean :tag "Dontexpunge"))
230                                    (group :inline t
231                                           (const :format "" :value :plugged)
232                                           (boolean :tag "Plugged")))))))
233
234 (defcustom mail-source-ignore-errors nil
235   "*Ignore errors when querying mail sources.
236 If nil, the user will be prompted when an error occurs.  If non-nil,
237 the error will be ignored.")
238
239 (defcustom mail-source-primary-source nil
240   "*Primary source for incoming mail.
241 If non-nil, this maildrop will be checked periodically for new mail."
242   :group 'mail-source
243   :type 'sexp)
244
245 (defcustom mail-source-flash t
246   "*If non-nil, flash periodically when mail is available."
247   :group 'mail-source
248   :type 'boolean)
249
250 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
251   "File where mail will be stored while processing it."
252   :group 'mail-source
253   :type 'file)
254
255 (defcustom mail-source-directory message-directory
256   "Directory where files (if any) will be stored."
257   :group 'mail-source
258   :type 'directory)
259
260 (defcustom mail-source-default-file-modes 384
261   "Set the mode bits of all new mail files to this integer."
262   :group 'mail-source
263   :type 'integer)
264
265 (defcustom mail-source-delete-incoming nil
266   "*If non-nil, delete incoming files after handling.
267 If t, delete immediately, if nil, never delete.  If a positive number, delete
268 files older than number of days."
269   ;; Note: The removing happens in `mail-source-callback', i.e. no old
270   ;; incoming files will be deleted, unless you receive new mail.
271   ;;
272   ;; You may also set this to `nil' and call `mail-source-delete-old-incoming'
273   ;; from a hook or interactively.
274   :group 'mail-source
275   :type '(choice (const :tag "immediately" t)
276                  (const :tag "never" nil)
277                  (integer :tag "days")))
278
279 (defcustom mail-source-delete-old-incoming-confirm t
280   "*If non-nil, ask for for confirmation before deleting old incoming files.
281 This variable only applies when `mail-source-delete-incoming' is a positive
282 number."
283   :group 'mail-source
284   :type 'boolean)
285
286 (defcustom mail-source-incoming-file-prefix "Incoming"
287   "Prefix for file name for storing incoming mail"
288   :group 'mail-source
289   :type 'string)
290
291 (defcustom mail-source-report-new-mail-interval 5
292   "Interval in minutes between checks for new mail."
293   :group 'mail-source
294   :type 'number)
295
296 (defcustom mail-source-idle-time-delay 5
297   "Number of idle seconds to wait before checking for new mail."
298   :group 'mail-source
299   :type 'number)
300
301 (defcustom mail-source-movemail-program nil
302   "If non-nil, name of program for fetching new mail."
303   :group 'mail-source
304   :type '(choice (const nil) string))
305
306 ;;; Internal variables.
307
308 (defvar mail-source-string ""
309   "A dynamically bound string that says what the current mail source is.")
310
311 (defvar mail-source-new-mail-available nil
312   "Flag indicating when new mail is available.")
313
314 (eval-and-compile
315   (defvar mail-source-common-keyword-map
316     '((:plugged))
317     "Mapping from keywords to default values.
318 Common keywords should be listed here.")
319
320   (defvar mail-source-keyword-map
321     '((file
322        (:prescript)
323        (:prescript-delay)
324        (:postscript)
325        (:path (or (getenv "MAIL")
326                   (expand-file-name (user-login-name) rmail-spool-directory))))
327       (directory
328        (:prescript)
329        (:prescript-delay)
330        (:postscript)
331        (:path)
332        (:suffix ".spool")
333        (:predicate identity))
334       (pop
335        (:prescript)
336        (:prescript-delay)
337        (:postscript)
338        (:server (getenv "MAILHOST"))
339        (:port 110)
340        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
341        (:program)
342        (:function)
343        (:password)
344        (:authentication password))
345       (maildir
346        (:path (or (getenv "MAILDIR") "~/Maildir/"))
347        (:subdirs ("new" "cur"))
348        (:function))
349       (imap
350        (:server (getenv "MAILHOST"))
351        (:port)
352        (:stream)
353        (:program)
354        (:authentication)
355        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
356        (:password)
357        (:mailbox "INBOX")
358        (:predicate "UNSEEN UNDELETED")
359        (:fetchflag "\\Deleted")
360        (:dontexpunge))
361       (webmail
362        (:subtype hotmail)
363        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
364        (:password)
365        (:dontexpunge)
366        (:authentication password)))
367     "Mapping from keywords to default values.
368 All keywords that can be used must be listed here."))
369
370 (defvar mail-source-fetcher-alist
371   '((file mail-source-fetch-file)
372     (directory mail-source-fetch-directory)
373     (pop mail-source-fetch-pop)
374     (maildir mail-source-fetch-maildir)
375     (imap mail-source-fetch-imap)
376     (webmail mail-source-fetch-webmail))
377   "A mapping from source type to fetcher function.")
378
379 (defvar mail-source-password-cache nil)
380
381 (defvar mail-source-plugged t)
382
383 ;;; Functions
384
385 (eval-and-compile
386   (defun mail-source-strip-keyword (keyword)
387     "Strip the leading colon off the KEYWORD."
388     (intern (substring (symbol-name keyword) 1))))
389
390 (eval-and-compile
391   (defun mail-source-bind-1 (type)
392     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
393            default bind)
394       (while (setq default (pop defaults))
395         (push (list (mail-source-strip-keyword (car default))
396                     nil)
397               bind))
398       bind)))
399
400 (defmacro mail-source-bind (type-source &rest body)
401   "Return a `let' form that binds all variables in source TYPE.
402 TYPE-SOURCE is a list where the first element is the TYPE, and
403 the second variable is the SOURCE.
404 At run time, the mail source specifier SOURCE will be inspected,
405 and the variables will be set according to it.  Variables not
406 specified will be given default values.
407
408 After this is done, BODY will be executed in the scope
409 of the `let' form.
410
411 The variables bound and their default values are described by
412 the `mail-source-keyword-map' variable."
413   `(let ,(mail-source-bind-1 (car type-source))
414      (mail-source-set-1 ,(cadr type-source))
415      ,@body))
416
417 (put 'mail-source-bind 'lisp-indent-function 1)
418 (put 'mail-source-bind 'edebug-form-spec '(sexp body))
419
420 (defun mail-source-set-1 (source)
421   (let* ((type (pop source))
422          (defaults (cdr (assq type mail-source-keyword-map)))
423          default value keyword)
424     (while (setq default (pop defaults))
425       (set (mail-source-strip-keyword (setq keyword (car default)))
426            (if (setq value (plist-get source keyword))
427                (mail-source-value value)
428              (mail-source-value (cadr default)))))))
429
430 (eval-and-compile
431   (defun mail-source-bind-common-1 ()
432     (let* ((defaults mail-source-common-keyword-map)
433            default bind)
434       (while (setq default (pop defaults))
435         (push (list (mail-source-strip-keyword (car default))
436                     nil)
437               bind))
438       bind)))
439
440 (defun mail-source-set-common-1 (source)
441   (let* ((type (pop source))
442          (defaults mail-source-common-keyword-map)
443          (defaults-1 (cdr (assq type mail-source-keyword-map)))
444          default value keyword)
445     (while (setq default (pop defaults))
446       (set (mail-source-strip-keyword (setq keyword (car default)))
447            (if (setq value (plist-get source keyword))
448                (mail-source-value value)
449              (if (setq value (assq  keyword defaults-1))
450                  (mail-source-value (cadr value))
451                (mail-source-value (cadr default))))))))
452
453 (defmacro mail-source-bind-common (source &rest body)
454   "Return a `let' form that binds all common variables.
455 See `mail-source-bind'."
456   `(let ,(mail-source-bind-common-1)
457      (mail-source-set-common-1 source)
458      ,@body))
459
460 (put 'mail-source-bind-common 'lisp-indent-function 1)
461 (put 'mail-source-bind-common 'edebug-form-spec '(sexp body))
462
463 (defun mail-source-value (value)
464   "Return the value of VALUE."
465   (cond
466    ;; String
467    ((stringp value)
468     value)
469    ;; Function
470    ((and (listp value)
471          (functionp (car value)))
472     (eval value))
473    ;; Just return the value.
474    (t
475     value)))
476
477 (defun mail-source-fetch (source callback)
478   "Fetch mail from SOURCE and call CALLBACK zero or more times.
479 CALLBACK will be called with the name of the file where (some of)
480 the mail from SOURCE is put.
481 Return the number of files that were found."
482   (mail-source-bind-common source
483     (if (or mail-source-plugged plugged)
484         (save-excursion
485           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
486                 (found 0))
487             (unless function
488               (error "%S is an invalid mail source specification" source))
489             ;; If there's anything in the crash box, we do it first.
490             (when (file-exists-p mail-source-crash-box)
491               (message "Processing mail from %s..." mail-source-crash-box)
492               (setq found (mail-source-callback
493                            callback mail-source-crash-box)))
494             (+ found
495                (if (or debug-on-quit debug-on-error)
496                    (funcall function source callback)
497                  (condition-case err
498                      (funcall function source callback)
499                    (error
500                     (if (and (not mail-source-ignore-errors)
501                              (not
502                               (yes-or-no-p
503                                (format "Mail source %s error (%s).  Continue? "
504                                        (if (memq ':password source)
505                                            (let ((s (copy-sequence source)))
506                                              (setcar (cdr (memq ':password s)) 
507                                                      "********")
508                                              s)
509                                          source)
510                                        (cadr err)))))
511                       (error "Cannot get new mail"))
512                     0)))))))))
513
514 (eval-and-compile
515   (if (fboundp 'make-temp-file)
516       (defalias 'mail-source-make-complex-temp-name 'make-temp-file)
517     (defun mail-source-make-complex-temp-name (prefix)
518       (let ((newname (make-temp-name prefix))
519             (newprefix prefix))
520         (while (file-exists-p newname)
521           (setq newprefix (concat newprefix "x"))
522           (setq newname (make-temp-name newprefix)))
523         newname))))
524
525 (defun mail-source-delete-old-incoming (&optional age confirm)
526   "Remove incoming files older than AGE days.
527 If CONFIRM is non-nil, ask for confirmation before removing a file."
528   (interactive "P")
529   (let* ((high2days (/ 65536.0 60 60 24));; convert high bits to days
530          (low2days  (/ 1.0 65536.0))     ;; convert low bits to days
531          (diff (if (natnump age) age 30));; fallback, if no valid AGE given
532          currday files)
533     (setq files (directory-files
534                  mail-source-directory t
535                  (concat mail-source-incoming-file-prefix "*"))
536           currday (* (car (current-time)) high2days)
537           currday (+ currday (* low2days (nth 1 (current-time)))))
538     (while files
539       (let* ((ffile (car files))
540              (bfile (gnus-replace-in-string
541                      ffile "\\`.*/\\([^/]+\\)\\'" "\\1"))
542              (filetime (nth 5 (file-attributes ffile)))
543              (fileday (* (car filetime) high2days))
544              (fileday (+ fileday (* low2days (nth 1 filetime)))))
545         (setq files (cdr files))
546         (when (and (> (- currday fileday) diff)
547                    (gnus-message 8 "File `%s' is older than %s day(s)"
548                                  bfile diff)
549                    (or (not confirm)
550                        (y-or-n-p (concat "Remove file `" bfile "'? "))))
551           (delete-file ffile))))))
552
553 (defun mail-source-callback (callback info)
554   "Call CALLBACK on the mail file, and then remove the mail file.
555 Pass INFO on to CALLBACK."
556   (if (or (not (file-exists-p mail-source-crash-box))
557           (zerop (nth 7 (file-attributes mail-source-crash-box))))
558       (progn
559         (when (file-exists-p mail-source-crash-box)
560           (delete-file mail-source-crash-box))
561         0)
562     (prog1
563         (funcall callback mail-source-crash-box info)
564       (when (file-exists-p mail-source-crash-box)
565         ;; Delete or move the incoming mail out of the way.
566         (if (eq mail-source-delete-incoming t)
567             (delete-file mail-source-crash-box)
568           (let ((incoming
569                  (mail-source-make-complex-temp-name
570                   (expand-file-name
571                    mail-source-incoming-file-prefix
572                    mail-source-directory))))
573             (unless (file-exists-p (file-name-directory incoming))
574               (make-directory (file-name-directory incoming) t))
575             (rename-file mail-source-crash-box incoming t)
576             ;; remove old incoming files?
577             (when (natnump mail-source-delete-incoming)
578               (mail-source-delete-old-incoming
579                mail-source-delete-incoming
580                mail-source-delete-old-incoming-confirm))))))))
581
582 (defun mail-source-movemail (from to)
583   "Move FROM to TO using movemail."
584   (if (not (file-writable-p to))
585       (error "Can't write to crash box %s.  Not moving mail" to)
586     (let ((to (file-truename (expand-file-name to)))
587           errors result)
588       (setq to (file-truename to)
589             from (file-truename from))
590       ;; Set TO if have not already done so, and rename or copy
591       ;; the file FROM to TO if and as appropriate.
592       (cond
593        ((file-exists-p to)
594         ;; The crash box exists already.
595         t)
596        ((not (file-exists-p from))
597         ;; There is no inbox.
598         (setq to nil))
599        ((zerop (nth 7 (file-attributes from)))
600         ;; Empty file.
601         (setq to nil))
602        (t
603         ;; If getting from mail spool directory, use movemail to move
604         ;; rather than just renaming, so as to interlock with the
605         ;; mailer.
606         (unwind-protect
607             (save-excursion
608               (setq errors (generate-new-buffer " *mail source loss*"))
609               (let ((default-directory "/"))
610                 (setq result
611                       (apply
612                        'call-process
613                        (append
614                         (list
615                          (or mail-source-movemail-program
616                              (expand-file-name "movemail" exec-directory))
617                          nil errors nil from to)))))
618               (when (file-exists-p to)
619                 (set-file-modes to mail-source-default-file-modes))
620               (if (and (or (not (buffer-modified-p errors))
621                            (zerop (buffer-size errors)))
622                        (zerop result))
623                   ;; No output => movemail won.
624                   t
625                 (set-buffer errors)
626                 ;; There may be a warning about older revisions.  We
627                 ;; ignore that.
628                 (goto-char (point-min))
629                 (if (search-forward "older revision" nil t)
630                     t
631                   ;; Probably a real error.
632                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
633                   (goto-char (point-max))
634                   (skip-chars-backward " \t")
635                   (delete-region (point) (point-max))
636                   (goto-char (point-min))
637                   (when (looking-at "movemail: ")
638                     (delete-region (point-min) (match-end 0)))
639                   ;; Result may be a signal description string.
640                   (unless (yes-or-no-p
641                            (format "movemail: %s (%s return).  Continue? "
642                                    (buffer-string) result))
643                     (error "%s" (buffer-string)))
644                   (setq to nil)))))))
645       (when (and errors
646                  (buffer-name errors))
647         (kill-buffer errors))
648       ;; Return whether we moved successfully or not.
649       to)))
650
651 (defun mail-source-movemail-and-remove (from to)
652   "Move FROM to TO using movemail, then remove FROM if empty."
653   (or (not (mail-source-movemail from to))
654       (not (zerop (nth 7 (file-attributes from))))
655       (delete-file from)))
656
657 (defvar mail-source-read-passwd nil)
658 (defun mail-source-read-passwd (prompt &rest args)
659   "Read a password using PROMPT.
660 If ARGS, PROMPT is used as an argument to `format'."
661   (let ((prompt
662          (if args
663              (apply 'format prompt args)
664            prompt)))
665     (unless mail-source-read-passwd
666       (if (or (fboundp 'read-passwd) (load "passwd" t))
667           (setq mail-source-read-passwd 'read-passwd)
668         (unless (fboundp 'ange-ftp-read-passwd)
669           (autoload 'ange-ftp-read-passwd "ange-ftp"))
670         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
671     (funcall mail-source-read-passwd prompt)))
672
673 (defun mail-source-fetch-with-program (program)
674   (zerop (call-process shell-file-name nil nil nil
675                        shell-command-switch program)))
676
677 (defun mail-source-run-script (script spec &optional delay)
678   (when script
679     (if (functionp script)
680         (funcall script)
681       (mail-source-call-script
682        (format-spec script spec))))
683   (when delay
684     (sleep-for delay)))
685
686 (defun mail-source-call-script (script)
687   (let ((background nil))
688     (when (string-match "& *$" script)
689       (setq script (substring script 0 (match-beginning 0))
690             background 0))
691     (call-process shell-file-name nil background nil
692                   shell-command-switch script)))
693
694 ;;;
695 ;;; Different fetchers
696 ;;;
697
698 (defun mail-source-fetch-file (source callback)
699   "Fetcher for single-file sources."
700   (mail-source-bind (file source)
701     (mail-source-run-script
702      prescript (format-spec-make ?t mail-source-crash-box)
703      prescript-delay)
704     (let ((mail-source-string (format "file:%s" path)))
705       (if (mail-source-movemail path mail-source-crash-box)
706           (prog1
707               (mail-source-callback callback path)
708             (mail-source-run-script
709              postscript (format-spec-make ?t mail-source-crash-box)))
710         0))))
711
712 (defun mail-source-fetch-directory (source callback)
713   "Fetcher for directory sources."
714   (mail-source-bind (directory source)
715     (mail-source-run-script
716      prescript (format-spec-make ?t path)
717      prescript-delay)
718     (let ((found 0)
719           (mail-source-string (format "directory:%s" path)))
720       (dolist (file (directory-files
721                      path t (concat (regexp-quote suffix) "$")))
722         (when (and (file-regular-p file)
723                    (funcall predicate file)
724                    (mail-source-movemail file mail-source-crash-box))
725           (incf found (mail-source-callback callback file))))
726       (mail-source-run-script
727        postscript (format-spec-make ?t path))
728       found)))
729
730 (defun mail-source-fetch-pop (source callback)
731   "Fetcher for single-file sources."
732   (mail-source-bind (pop source)
733     (mail-source-run-script
734      prescript
735      (format-spec-make ?p password ?t mail-source-crash-box
736                        ?s server ?P port ?u user)
737      prescript-delay)
738     (let ((from (format "%s:%s:%s" server user port))
739           (mail-source-string (format "pop:%s@%s" user server))
740           result)
741       (when (eq authentication 'password)
742         (setq password
743               (or password
744                   (cdr (assoc from mail-source-password-cache))
745                   (mail-source-read-passwd
746                    (format "Password for %s at %s: " user server)))))
747       (when server
748         (setenv "MAILHOST" server))
749       (setq result
750             (cond
751              (program
752               (mail-source-fetch-with-program
753                (format-spec
754                 program
755                 (format-spec-make ?p password ?t mail-source-crash-box
756                                   ?s server ?P port ?u user))))
757              (function
758               (funcall function mail-source-crash-box))
759              ;; The default is to use pop3.el.
760              (t
761               (let ((pop3-password password)
762                     (pop3-maildrop user)
763                     (pop3-mailhost server)
764                     (pop3-port port)
765                     (pop3-authentication-scheme
766                      (if (eq authentication 'apop) 'apop 'pass)))
767                 (if (or debug-on-quit debug-on-error)
768                     (save-excursion (pop3-movemail mail-source-crash-box))
769                   (condition-case err
770                       (save-excursion (pop3-movemail mail-source-crash-box))
771                     (error
772                      ;; We nix out the password in case the error
773                      ;; was because of a wrong password being given.
774                      (setq mail-source-password-cache
775                            (delq (assoc from mail-source-password-cache)
776                                  mail-source-password-cache))
777                      (signal (car err) (cdr err)))))))))
778       (if result
779           (progn
780             (when (eq authentication 'password)
781               (unless (assoc from mail-source-password-cache)
782                 (push (cons from password) mail-source-password-cache)))
783             (prog1
784                 (mail-source-callback callback server)
785               ;; Update display-time's mail flag, if relevant.
786               (if (equal source mail-source-primary-source)
787                   (setq mail-source-new-mail-available nil))
788               (mail-source-run-script
789                postscript
790                (format-spec-make ?p password ?t mail-source-crash-box
791                                  ?s server ?P port ?u user))))
792         ;; We nix out the password in case the error
793         ;; was because of a wrong password being given.
794         (setq mail-source-password-cache
795               (delq (assoc from mail-source-password-cache)
796                     mail-source-password-cache))
797         0))))
798
799 (defun mail-source-check-pop (source)
800   "Check whether there is new mail."
801   (mail-source-bind (pop source)
802     (let ((from (format "%s:%s:%s" server user port))
803           (mail-source-string (format "pop:%s@%s" user server))
804           result)
805       (when (eq authentication 'password)
806         (setq password
807               (or password
808                   (cdr (assoc from mail-source-password-cache))
809                   (mail-source-read-passwd
810                    (format "Password for %s at %s: " user server))))
811         (unless (assoc from mail-source-password-cache)
812           (push (cons from password) mail-source-password-cache)))
813       (when server
814         (setenv "MAILHOST" server))
815       (setq result
816             (cond
817              ;; No easy way to check whether mail is waiting for these.
818              (program)
819              (function)
820              ;; The default is to use pop3.el.
821              (t
822               (let ((pop3-password password)
823                     (pop3-maildrop user)
824                     (pop3-mailhost server)
825                     (pop3-port port)
826                     (pop3-authentication-scheme
827                      (if (eq authentication 'apop) 'apop 'pass)))
828                 (if (or debug-on-quit debug-on-error)
829                     (save-excursion (pop3-get-message-count))
830                   (condition-case err
831                       (save-excursion (pop3-get-message-count))
832                     (error
833                      ;; We nix out the password in case the error
834                      ;; was because of a wrong password being given.
835                      (setq mail-source-password-cache
836                            (delq (assoc from mail-source-password-cache)
837                                  mail-source-password-cache))
838                      (signal (car err) (cdr err)))))))))
839       (if result
840           ;; Inform display-time that we have new mail.
841           (setq mail-source-new-mail-available (> result 0))
842         ;; We nix out the password in case the error
843         ;; was because of a wrong password being given.
844         (setq mail-source-password-cache
845               (delq (assoc from mail-source-password-cache)
846                     mail-source-password-cache)))
847       result)))
848
849 (defun mail-source-touch-pop ()
850   "Open and close a POP connection shortly.
851 POP server should be defined in `mail-source-primary-source' (which is
852 preferred) or `mail-sources'.  You may use it for the POP-before-SMTP
853 authentication.  To do that, you need to set the option
854 `message-send-mail-function' to `message-smtpmail-send-it' and put the
855 following line in .gnus file:
856
857 \(add-hook 'message-send-mail-hook 'mail-source-touch-pop)
858 "
859   (let ((sources (if mail-source-primary-source
860                      (list mail-source-primary-source)
861                    mail-sources)))
862     (while sources
863       (if (eq 'pop (car (car sources)))
864           (mail-source-check-pop (car sources)))
865       (setq sources (cdr sources)))))
866
867 (defun mail-source-new-mail-p ()
868   "Handler for `display-time' to indicate when new mail is available."
869   ;; Flash (ie. ring the visible bell) if mail is available.
870   (if (and mail-source-flash mail-source-new-mail-available)
871       (let ((visible-bell t))
872         (ding)))
873   ;; Only report flag setting; flag is updated on a different schedule.
874   mail-source-new-mail-available)
875
876
877 (defvar mail-source-report-new-mail nil)
878 (defvar mail-source-report-new-mail-timer nil)
879 (defvar mail-source-report-new-mail-idle-timer nil)
880
881 (eval-when-compile
882   (if (featurep 'xemacs)
883       (require 'itimer)
884     (require 'timer)))
885
886 (defun mail-source-start-idle-timer ()
887   ;; Start our idle timer if necessary, so we delay the check until the
888   ;; user isn't typing.
889   (unless mail-source-report-new-mail-idle-timer
890     (setq mail-source-report-new-mail-idle-timer
891           (run-with-idle-timer
892            mail-source-idle-time-delay
893            nil
894            (lambda ()
895              (unwind-protect
896                  (mail-source-check-pop mail-source-primary-source)
897                (setq mail-source-report-new-mail-idle-timer nil)))))
898     ;; Since idle timers created when Emacs is already in the idle
899     ;; state don't get activated until Emacs _next_ becomes idle, we
900     ;; need to force our timer to be considered active now.  We do
901     ;; this by being naughty and poking the timer internals directly
902     ;; (element 0 of the vector is nil if the timer is active).
903     (aset mail-source-report-new-mail-idle-timer 0 nil)))
904
905 (defun mail-source-report-new-mail (arg)
906   "Toggle whether to report when new mail is available.
907 This only works when `display-time' is enabled."
908   (interactive "P")
909   (if (not mail-source-primary-source)
910       (error "Need to set `mail-source-primary-source' to check for new mail"))
911   (let ((on (if (null arg)
912                 (not mail-source-report-new-mail)
913               (> (prefix-numeric-value arg) 0))))
914     (setq mail-source-report-new-mail on)
915     (and mail-source-report-new-mail-timer
916          (nnheader-cancel-timer mail-source-report-new-mail-timer))
917     (and mail-source-report-new-mail-idle-timer
918          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
919     (setq mail-source-report-new-mail-timer nil)
920     (setq mail-source-report-new-mail-idle-timer nil)
921     (if on
922         (progn
923           (require 'time)
924           ;; display-time-mail-function is an Emacs 21 feature.
925           (setq display-time-mail-function #'mail-source-new-mail-p)
926           ;; Set up the main timer.
927           (setq mail-source-report-new-mail-timer
928                 (nnheader-run-at-time
929                  (* 60 mail-source-report-new-mail-interval)
930                  (* 60 mail-source-report-new-mail-interval)
931                  #'mail-source-start-idle-timer))
932           ;; When you get new mail, clear "Mail" from the mode line.
933           (add-hook 'nnmail-post-get-new-mail-hook
934                     'display-time-event-handler)
935           (message "Mail check enabled"))
936       (setq display-time-mail-function nil)
937       (remove-hook 'nnmail-post-get-new-mail-hook
938                    'display-time-event-handler)
939       (message "Mail check disabled"))))
940
941 (defun mail-source-fetch-maildir (source callback)
942   "Fetcher for maildir sources."
943   (mail-source-bind (maildir source)
944     (let ((found 0)
945           mail-source-string)
946       (unless (string-match "/$" path)
947         (setq path (concat path "/")))
948       (dolist (subdir subdirs)
949         (when (file-directory-p (concat path subdir))
950           (setq mail-source-string (format "maildir:%s%s" path subdir))
951           (dolist (file (directory-files (concat path subdir) t))
952             (when (and (not (file-directory-p file))
953                        (not (if function
954                                 (funcall function file mail-source-crash-box)
955                               (let ((coding-system-for-write
956                                      mm-text-coding-system)
957                                     (coding-system-for-read
958                                      mm-text-coding-system))
959                                 (with-temp-file mail-source-crash-box
960                                   (insert-file-contents file)
961                                   (goto-char (point-min))
962 ;;;                               ;; Unix mail format
963 ;;;                               (unless (looking-at "\n*From ")
964 ;;;                                 (insert "From maildir "
965 ;;;                                         (current-time-string) "\n"))
966 ;;;                               (while (re-search-forward "^From " nil t)
967 ;;;                                 (replace-match ">From "))
968 ;;;                               (goto-char (point-max))
969 ;;;                               (insert "\n\n")
970                                   ;; MMDF mail format
971                                   (insert "\001\001\001\001\n"))
972                                 (delete-file file)))))
973               (incf found (mail-source-callback callback file))))))
974       found)))
975
976 (eval-and-compile
977   (autoload 'imap-open "imap")
978   (autoload 'imap-authenticate "imap")
979   (autoload 'imap-mailbox-select "imap")
980   (autoload 'imap-mailbox-unselect "imap")
981   (autoload 'imap-mailbox-close "imap")
982   (autoload 'imap-search "imap")
983   (autoload 'imap-fetch "imap")
984   (autoload 'imap-close "imap")
985   (autoload 'imap-error-text "imap")
986   (autoload 'imap-message-flags-add "imap")
987   (autoload 'imap-list-to-message-set "imap")
988   (autoload 'imap-range-to-message-set "imap")
989   (autoload 'nnheader-ms-strip-cr "nnheader"))
990
991 (defvar mail-source-imap-file-coding-system 'binary
992   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
993
994 (defun mail-source-fetch-imap (source callback)
995   "Fetcher for imap sources."
996   (mail-source-bind (imap source)
997     (let ((from (format "%s:%s:%s" server user port))
998           (found 0)
999           (buf (get-buffer-create (generate-new-buffer-name " *imap source*")))
1000           (mail-source-string (format "imap:%s:%s" server mailbox))
1001           (imap-shell-program (or (list program) imap-shell-program))
1002           remove)
1003       (if (and (imap-open server port stream authentication buf)
1004                (imap-authenticate
1005                 user (or (cdr (assoc from mail-source-password-cache))
1006                          password) buf)
1007                (imap-mailbox-select mailbox nil buf))
1008           (let ((coding-system-for-write mail-source-imap-file-coding-system)
1009                 str)
1010             (with-temp-file mail-source-crash-box
1011               ;; Avoid converting 8-bit chars from inserted strings to
1012               ;; multibyte.
1013               (mm-disable-multibyte)
1014               ;; remember password
1015               (with-current-buffer buf
1016                 (when (or imap-password
1017                           (assoc from mail-source-password-cache))
1018                   (push (cons from imap-password) mail-source-password-cache)))
1019               ;; if predicate is nil, use all uids
1020               (dolist (uid (imap-search (or predicate "1:*") buf))
1021                 (when (setq str
1022                             (if (imap-capability 'IMAP4rev1 buf)
1023                                 (caddar (imap-fetch uid "BODY.PEEK[]"
1024                                                     'BODYDETAIL nil buf))
1025                               (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf)))
1026                   (push uid remove)
1027                   (insert "From imap " (current-time-string) "\n")
1028                   (save-excursion
1029                     (insert str "\n\n"))
1030                   (while (re-search-forward "^From " nil t)
1031                     (replace-match ">From "))
1032                   (goto-char (point-max))))
1033               (nnheader-ms-strip-cr))
1034             (incf found (mail-source-callback callback server))
1035             (when (and remove fetchflag)
1036               (imap-message-flags-add
1037                (imap-range-to-message-set (gnus-compress-sequence remove))
1038                fetchflag nil buf))
1039             (if dontexpunge
1040                 (imap-mailbox-unselect buf)
1041               (imap-mailbox-close nil buf))
1042             (imap-close buf))
1043         (imap-close buf)
1044         ;; We nix out the password in case the error
1045         ;; was because of a wrong password being given.
1046         (setq mail-source-password-cache
1047               (delq (assoc from mail-source-password-cache)
1048                     mail-source-password-cache))
1049         (error (imap-error-text buf)))
1050       (kill-buffer buf)
1051       found)))
1052
1053 (eval-and-compile
1054   (autoload 'webmail-fetch "webmail"))
1055
1056 (defun mail-source-fetch-webmail (source callback)
1057   "Fetch for webmail source."
1058   (mail-source-bind (webmail source)
1059     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
1060           (webmail-newmail-only dontexpunge)
1061           (webmail-move-to-trash-can (not dontexpunge)))
1062       (when (eq authentication 'password)
1063         (setq password
1064               (or password
1065                   (cdr (assoc (format "webmail:%s:%s" subtype user)
1066                               mail-source-password-cache))
1067                   (mail-source-read-passwd
1068                    (format "Password for %s at %s: " user subtype))))
1069         (when (and password
1070                    (not (assoc (format "webmail:%s:%s" subtype user)
1071                                mail-source-password-cache)))
1072           (push (cons (format "webmail:%s:%s" subtype user) password)
1073                 mail-source-password-cache)))
1074       (webmail-fetch mail-source-crash-box subtype user password)
1075       (mail-source-callback callback (symbol-name subtype)))))
1076
1077 (provide 'mail-source)
1078
1079 ;;; mail-source.el ends here