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