* nndoc.el (nndoc-oe-dbx-type-p): Use `string-as-multibyte' instead of
[elisp/gnus.git-] / lisp / mail-source.el
1 ;;; mail-source.el --- functions for fetching mail
2 ;; Copyright (C) 1999, 2000, 2001 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 ;;; Internal variables.
268
269 (defvar mail-source-string ""
270   "A dynamically bound string that says what the current mail source is.")
271
272 (defvar mail-source-new-mail-available nil
273   "Flag indicating when new mail is available.")
274
275 (eval-and-compile
276   (defvar mail-source-common-keyword-map
277     '((:plugged))
278     "Mapping from keywords to default values.
279 Common keywords should be listed here.")
280
281   (defvar mail-source-keyword-map
282     '((file
283        (:prescript)
284        (:prescript-delay)
285        (:postscript)
286        (:path (or (getenv "MAIL")
287                   (expand-file-name (user-login-name) rmail-spool-directory))))
288       (directory
289        (:path)
290        (:suffix ".spool")
291        (:predicate identity))
292       (pop
293        (:prescript)
294        (:prescript-delay)
295        (:postscript)
296        (:server (getenv "MAILHOST"))
297        (:port 110)
298        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
299        (:program)
300        (:function)
301        (:password)
302        (:connection)
303        (:authentication password)
304        (:leave))
305       (maildir
306        (:path (or (getenv "MAILDIR") "~/Maildir/"))
307        (:subdirs ("new" "cur"))
308        (:function))
309       (imap
310        (:server (getenv "MAILHOST"))
311        (:port)
312        (:stream)
313        (:program)
314        (:authentication)
315        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
316        (:password)
317        (:mailbox "INBOX")
318        (:predicate "UNSEEN UNDELETED")
319        (:fetchflag "\\Deleted")
320        (:dontexpunge))
321       (webmail
322        (:subtype hotmail)
323        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
324        (:password)
325        (:dontexpunge)
326        (:authentication password)))
327     "Mapping from keywords to default values.
328 All keywords that can be used must be listed here."))
329
330 (defvar mail-source-fetcher-alist
331   '((file mail-source-fetch-file)
332     (directory mail-source-fetch-directory)
333     (pop mail-source-fetch-pop)
334     (maildir mail-source-fetch-maildir)
335     (imap mail-source-fetch-imap)
336     (webmail mail-source-fetch-webmail))
337   "A mapping from source type to fetcher function.")
338
339 (defvar mail-source-password-cache nil)
340
341 (defvar mail-source-plugged t)
342
343 ;;; Functions
344
345 (eval-and-compile
346   (defun mail-source-strip-keyword (keyword)
347     "Strip the leading colon off the KEYWORD."
348     (intern (substring (symbol-name keyword) 1))))
349
350 (eval-and-compile
351   (defun mail-source-bind-1 (type)
352     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
353            default bind)
354       (while (setq default (pop defaults))
355         (push (list (mail-source-strip-keyword (car default))
356                     nil)
357               bind))
358       bind)))
359
360 (defmacro mail-source-bind (type-source &rest body)
361   "Return a `let' form that binds all variables in source TYPE.
362 TYPE-SOURCE is a list where the first element is the TYPE, and
363 the second variable is the SOURCE.
364 At run time, the mail source specifier SOURCE will be inspected,
365 and the variables will be set according to it.  Variables not
366 specified will be given default values.
367
368 After this is done, BODY will be executed in the scope
369 of the `let' form.
370
371 The variables bound and their default values are described by
372 the `mail-source-keyword-map' variable."
373   `(let ,(mail-source-bind-1 (car type-source))
374      (mail-source-set-1 ,(cadr type-source))
375      ,@body))
376
377 (put 'mail-source-bind 'lisp-indent-function 1)
378 (put 'mail-source-bind 'edebug-form-spec '(form body))
379
380 (defun mail-source-set-1 (source)
381   (let* ((type (pop source))
382          (defaults (cdr (assq type mail-source-keyword-map)))
383          default value keyword)
384     (while (setq default (pop defaults))
385       (set (mail-source-strip-keyword (setq keyword (car default)))
386            (if (setq value (plist-get source keyword))
387                (mail-source-value value)
388              (mail-source-value (cadr default)))))))
389
390 (eval-and-compile
391   (defun mail-source-bind-common-1 ()
392     (let* ((defaults mail-source-common-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 (defun mail-source-set-common-1 (source)
401   (let* ((type (pop source))
402          (defaults mail-source-common-keyword-map)
403          (defaults-1 (cdr (assq type mail-source-keyword-map)))
404          default value keyword)
405     (while (setq default (pop defaults))
406       (set (mail-source-strip-keyword (setq keyword (car default)))
407            (if (setq value (plist-get source keyword))
408                (mail-source-value value)
409              (if (setq value (assq  keyword defaults-1))
410                  (mail-source-value (cadr value))
411                (mail-source-value (cadr default))))))))
412
413 (defmacro mail-source-bind-common (source &rest body)
414   "Return a `let' form that binds all common variables.
415 See `mail-source-bind'."
416   `(let ,(mail-source-bind-common-1)
417      (mail-source-set-common-1 source)
418      ,@body))
419
420 (put 'mail-source-bind-common 'lisp-indent-function 1)
421 (put 'mail-source-bind-common 'edebug-form-spec '(form body))
422
423 (defun mail-source-value (value)
424   "Return the value of VALUE."
425   (cond
426    ;; String
427    ((stringp value)
428     value)
429    ;; Function
430    ((and (listp value)
431          (functionp (car value)))
432     (eval value))
433    ;; Just return the value.
434    (t
435     value)))
436
437 (defun mail-source-fetch (source callback)
438   "Fetch mail from SOURCE and call CALLBACK zero or more times.
439 CALLBACK will be called with the name of the file where (some of)
440 the mail from SOURCE is put.
441 Return the number of files that were found."
442   (mail-source-bind-common source
443     (if (or mail-source-plugged plugged)
444         (save-excursion
445           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
446                 (found 0))
447             (unless function
448               (error "%S is an invalid mail source specification" source))
449             ;; If there's anything in the crash box, we do it first.
450             (when (file-exists-p mail-source-crash-box)
451               (message "Processing mail from %s..." mail-source-crash-box)
452               (setq found (mail-source-callback
453                            callback mail-source-crash-box)))
454             (+ found
455                (condition-case err
456                    (funcall function source callback)
457                  (error
458                   (unless (yes-or-no-p
459                            (format "Mail source error (%s).  Continue? " err))
460                     (error "Cannot get new mail"))
461                   0))))))))
462
463 (defun mail-source-make-complex-temp-name (prefix)
464   (let ((newname (make-temp-name prefix))
465         (newprefix prefix))
466     (while (file-exists-p newname)
467       (setq newprefix (concat newprefix "x"))
468       (setq newname (make-temp-name newprefix)))
469     newname))
470
471 (defun mail-source-callback (callback info)
472   "Call CALLBACK on the mail file, and then remove the mail file.
473 Pass INFO on to CALLBACK."
474   (if (or (not (file-exists-p mail-source-crash-box))
475           (zerop (nth 7 (file-attributes mail-source-crash-box))))
476       (progn
477         (when (file-exists-p mail-source-crash-box)
478           (delete-file mail-source-crash-box))
479         0)
480     (prog1
481         (funcall callback mail-source-crash-box info)
482       (when (file-exists-p mail-source-crash-box)
483         ;; Delete or move the incoming mail out of the way.
484         (if mail-source-delete-incoming
485             (delete-file mail-source-crash-box)
486           (let ((incoming
487                  (mail-source-make-complex-temp-name
488                   (expand-file-name
489                    mail-source-incoming-file-prefix
490                    mail-source-directory))))
491             (unless (file-exists-p (file-name-directory incoming))
492               (make-directory (file-name-directory incoming) t))
493             (rename-file mail-source-crash-box incoming t)))))))
494
495 (defun mail-source-movemail (from to)
496   "Move FROM to TO using movemail."
497   (if (not (file-writable-p to))
498       (error "Can't write to crash box %s.  Not moving mail" to)
499     (let ((to (file-truename (expand-file-name to)))
500           errors result)
501       (setq to (file-truename to)
502             from (file-truename from))
503       ;; Set TO if have not already done so, and rename or copy
504       ;; the file FROM to TO if and as appropriate.
505       (cond
506        ((file-exists-p to)
507         ;; The crash box exists already.
508         t)
509        ((not (file-exists-p from))
510         ;; There is no inbox.
511         (setq to nil))
512        ((zerop (nth 7 (file-attributes from)))
513         ;; Empty file.
514         (setq to nil))
515        (t
516         ;; If getting from mail spool directory, use movemail to move
517         ;; rather than just renaming, so as to interlock with the
518         ;; mailer.
519         (unwind-protect
520             (save-excursion
521               (setq errors (generate-new-buffer " *mail source loss*"))
522               (let ((default-directory "/"))
523                 (setq result
524                       (apply
525                        'call-process
526                        (append
527                         (list
528                          (expand-file-name "movemail" exec-directory)
529                          nil errors nil from to)))))
530               (when (file-exists-p to)
531                 (set-file-modes to mail-source-default-file-modes))
532               (if (and (or (not (buffer-modified-p errors))
533                            (zerop (buffer-size errors)))
534                        (zerop result))
535                   ;; No output => movemail won.
536                   t
537                 (set-buffer errors)
538                 ;; There may be a warning about older revisions.  We
539                 ;; ignore that.
540                 (goto-char (point-min))
541                 (if (search-forward "older revision" nil t)
542                     t
543                   ;; Probably a real error.
544                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
545                   (goto-char (point-max))
546                   (skip-chars-backward " \t")
547                   (delete-region (point) (point-max))
548                   (goto-char (point-min))
549                   (when (looking-at "movemail: ")
550                     (delete-region (point-min) (match-end 0)))
551                   ;; Result may be a signal description string.
552                   (unless (yes-or-no-p
553                            (format "movemail: %s (%s return).  Continue? "
554                                    (buffer-string) result))
555                     (error "%s" (buffer-string)))
556                   (setq to nil)))))))
557       (when (and errors
558                  (buffer-name errors))
559         (kill-buffer errors))
560       ;; Return whether we moved successfully or not.
561       to)))
562
563 (defun mail-source-movemail-and-remove (from to)
564   "Move FROM to TO using movemail, then remove FROM if empty."
565   (or (not (mail-source-movemail from to))
566       (not (zerop (nth 7 (file-attributes from))))
567       (delete-file from)))
568
569 (defvar mail-source-read-passwd nil)
570 (defun mail-source-read-passwd (prompt &rest args)
571   "Read a password using PROMPT.
572 If ARGS, PROMPT is used as an argument to `format'."
573   (let ((prompt
574          (if args
575              (apply 'format prompt args)
576            prompt)))
577     (unless mail-source-read-passwd
578       (if (or (fboundp 'read-passwd) (load "passwd" t))
579           (setq mail-source-read-passwd 'read-passwd)
580         (unless (fboundp 'ange-ftp-read-passwd)
581           (autoload 'ange-ftp-read-passwd "ange-ftp"))
582         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
583     (funcall mail-source-read-passwd prompt)))
584
585 (defun mail-source-fetch-with-program (program)
586   (zerop (call-process shell-file-name nil nil nil
587                        shell-command-switch program)))
588
589 (defun mail-source-run-script (script spec &optional delay)
590   (when script
591     (if (and (symbolp script) (fboundp script))
592         (funcall script)
593       (mail-source-call-script
594        (format-spec script spec))))
595   (when delay
596     (sleep-for delay)))
597
598 (defun mail-source-call-script (script)
599   (let ((background nil))
600     (when (string-match "& *$" script)
601       (setq script (substring script 0 (match-beginning 0))
602             background 0))
603     (call-process shell-file-name nil background nil
604                   shell-command-switch script)))
605
606 ;;;
607 ;;; Different fetchers
608 ;;;
609
610 (defun mail-source-fetch-file (source callback)
611   "Fetcher for single-file sources."
612   (mail-source-bind (file source)
613     (mail-source-run-script
614      prescript (format-spec-make ?t mail-source-crash-box)
615      prescript-delay)
616     (let ((mail-source-string (format "file:%s" path)))
617       (if (mail-source-movemail path mail-source-crash-box)
618           (prog1
619               (mail-source-callback callback path)
620             (mail-source-run-script
621              postscript (format-spec-make ?t mail-source-crash-box)))
622         0))))
623
624 (defun mail-source-fetch-directory (source callback)
625   "Fetcher for directory sources."
626   (mail-source-bind (directory source)
627     (let ((found 0)
628           (mail-source-string (format "directory:%s" path)))
629       (dolist (file (directory-files
630                      path t (concat (regexp-quote suffix) "$")))
631         (when (and (file-regular-p file)
632                    (funcall predicate file)
633                    (mail-source-movemail file mail-source-crash-box))
634           (incf found (mail-source-callback callback file))))
635       found)))
636
637 (defun mail-source-fetch-pop (source callback)
638   "Fetcher for single-file sources."
639   (mail-source-bind (pop source)
640     (mail-source-run-script
641      prescript
642      (format-spec-make ?p password ?t mail-source-crash-box
643                        ?s server ?P port ?u user)
644      prescript-delay)
645     (let ((from (format "%s:%s:%s" server user port))
646           (mail-source-string (format "pop:%s@%s" user server))
647           result)
648       (when (eq authentication 'password)
649         (setq password
650               (or password
651                   (cdr (assoc from mail-source-password-cache))
652                   (mail-source-read-passwd
653                    (format "Password for %s at %s: " user server)))))
654       (when server
655         (setenv "MAILHOST" server))
656       (setq result
657             (cond
658              (program
659               (mail-source-fetch-with-program
660                (format-spec
661                 program
662                 (format-spec-make ?p password ?t mail-source-crash-box
663                                   ?s server ?P port ?u user))))
664              (function
665               (funcall function mail-source-crash-box))
666              ;; The default is to use pop3.el.
667              (t
668               (let ((pop3-password password)
669                     (pop3-maildrop user)
670                     (pop3-mailhost server)
671                     (pop3-port port)
672                     (pop3-authentication-scheme
673                      (if (eq authentication 'apop) 'apop 'pass))
674                     (pop3-connection-type connection)
675                     (pop3-leave-mail-on-server
676                      (or leave
677                          (and (boundp 'pop3-leave-mail-on-server)
678                               pop3-leave-mail-on-server))))
679                 (condition-case err
680                     (save-excursion (pop3-movemail mail-source-crash-box))
681                   (error
682                    ;; We nix out the password in case the error
683                    ;; was because of a wrong password being given.
684                    (setq mail-source-password-cache
685                          (delq (assoc from mail-source-password-cache)
686                                mail-source-password-cache))
687                    (signal (car err) (cdr err))))))))
688       (if result
689           (progn
690             (when (eq authentication 'password)
691               (unless (assoc from mail-source-password-cache)
692                 (push (cons from password) mail-source-password-cache)))
693             (prog1
694                 (mail-source-callback callback server)
695               ;; Update display-time's mail flag, if relevant.
696               (if (equal source mail-source-primary-source)
697                   (setq mail-source-new-mail-available nil))
698               (mail-source-run-script
699                postscript
700                (format-spec-make ?p password ?t mail-source-crash-box
701                                  ?s server ?P port ?u user))))
702         ;; We nix out the password in case the error
703         ;; was because of a wrong password being given.
704         (setq mail-source-password-cache
705               (delq (assoc from mail-source-password-cache)
706                     mail-source-password-cache))
707         0))))
708
709 (defun mail-source-check-pop (source)
710   "Check whether there is new mail."
711   (mail-source-bind (pop source)
712     (let ((from (format "%s:%s:%s" server user port))
713           (mail-source-string (format "pop:%s@%s" user server))
714           result)
715       (when (eq authentication 'password)
716         (setq password
717               (or password
718                   (cdr (assoc from mail-source-password-cache))
719                   (mail-source-read-passwd
720                    (format "Password for %s at %s: " user server))))
721         (unless (assoc from mail-source-password-cache)
722           (push (cons from password) mail-source-password-cache)))
723       (when server
724         (setenv "MAILHOST" server))
725       (setq result
726             (cond
727              ;; No easy way to check whether mail is waiting for these.
728              (program)
729              (function)
730              ;; The default is to use pop3.el.
731              (t
732               (let ((pop3-password password)
733                     (pop3-maildrop user)
734                     (pop3-mailhost server)
735                     (pop3-port port)
736                     (pop3-authentication-scheme
737                      (if (eq authentication 'apop) 'apop 'pass)))
738                 (condition-case err
739                     (save-excursion (pop3-get-message-count))
740                   (error
741                    ;; We nix out the password in case the error
742                    ;; was because of a wrong password being given.
743                    (setq mail-source-password-cache
744                          (delq (assoc from mail-source-password-cache)
745                                mail-source-password-cache))
746                    (signal (car err) (cdr err))))))))
747       (if result
748           ;; Inform display-time that we have new mail.
749           (setq mail-source-new-mail-available (> result 0))
750         ;; We nix out the password in case the error
751         ;; was because of a wrong password being given.
752         (setq mail-source-password-cache
753               (delq (assoc from mail-source-password-cache)
754                     mail-source-password-cache)))
755       result)))
756
757 (defun mail-source-new-mail-p ()
758   "Handler for `display-time' to indicate when new mail is available."
759   ;; Flash (ie. ring the visible bell) if mail is available.
760   (if (and mail-source-flash mail-source-new-mail-available)
761       (let ((visible-bell t))
762         (ding)))
763   ;; Only report flag setting; flag is updated on a different schedule.
764   mail-source-new-mail-available)
765
766
767 (defvar mail-source-report-new-mail nil)
768 (defvar mail-source-report-new-mail-timer nil)
769 (defvar mail-source-report-new-mail-idle-timer nil)
770
771 (eval-when-compile
772   (if (featurep 'xemacs)
773       (require 'itimer)
774     (require 'timer)))
775
776 (defun mail-source-start-idle-timer ()
777   ;; Start our idle timer if necessary, so we delay the check until the
778   ;; user isn't typing.
779   (unless mail-source-report-new-mail-idle-timer
780     (setq mail-source-report-new-mail-idle-timer
781           (run-with-idle-timer
782            mail-source-idle-time-delay
783            nil
784            (lambda ()
785              (unwind-protect
786                  (mail-source-check-pop mail-source-primary-source)
787                (setq mail-source-report-new-mail-idle-timer nil)))))
788     ;; Since idle timers created when Emacs is already in the idle
789     ;; state don't get activated until Emacs _next_ becomes idle, we
790     ;; need to force our timer to be considered active now.  We do
791     ;; this by being naughty and poking the timer internals directly
792     ;; (element 0 of the vector is nil if the timer is active).
793     (aset mail-source-report-new-mail-idle-timer 0 nil)))
794
795 (defun mail-source-report-new-mail (arg)
796   "Toggle whether to report when new mail is available.
797 This only works when `display-time' is enabled."
798   (interactive "P")
799   (if (not mail-source-primary-source)
800       (error "Need to set `mail-source-primary-source' to check for new mail"))
801   (let ((on (if (null arg)
802                 (not mail-source-report-new-mail)
803               (> (prefix-numeric-value arg) 0))))
804     (setq mail-source-report-new-mail on)
805     (and mail-source-report-new-mail-timer
806          (nnheader-cancel-timer mail-source-report-new-mail-timer))
807     (and mail-source-report-new-mail-idle-timer
808          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
809     (setq mail-source-report-new-mail-timer nil)
810     (setq mail-source-report-new-mail-idle-timer nil)
811     (if on
812         (progn
813           (require 'time)
814           ;; display-time-mail-function is an Emacs 21 feature.
815           (setq display-time-mail-function #'mail-source-new-mail-p)
816           ;; Set up the main timer.
817           (setq mail-source-report-new-mail-timer
818                 (nnheader-run-at-time
819                  (* 60 mail-source-report-new-mail-interval)
820                  (* 60 mail-source-report-new-mail-interval)
821                  #'mail-source-start-idle-timer))
822           ;; When you get new mail, clear "Mail" from the mode line.
823           (add-hook 'nnmail-post-get-new-mail-hook
824                     'display-time-event-handler)
825           (message "Mail check enabled"))
826       (setq display-time-mail-function nil)
827       (remove-hook 'nnmail-post-get-new-mail-hook
828                    'display-time-event-handler)
829       (message "Mail check disabled"))))
830
831 (defun mail-source-fetch-maildir (source callback)
832   "Fetcher for maildir sources."
833   (mail-source-bind (maildir source)
834     (let ((found 0)
835           mail-source-string)
836       (unless (string-match "/$" path)
837         (setq path (concat path "/")))
838       (dolist (subdir subdirs)
839         (when (file-directory-p (concat path subdir))
840           (setq mail-source-string (format "maildir:%s%s" path subdir))
841           (dolist (file (directory-files (concat path subdir) t))
842             (when (and (not (file-directory-p file))
843                        (not (if function
844                                 (funcall function file mail-source-crash-box)
845                               (let ((coding-system-for-write
846                                      nnheader-text-coding-system)
847                                     (coding-system-for-read
848                                      nnheader-text-coding-system)
849                                     (output-coding-system
850                                      nnheader-text-coding-system)
851                                     (input-coding-system
852                                      nnheader-text-coding-system))
853                                 (with-temp-file mail-source-crash-box
854                                   (insert-file-contents file)
855                                   (goto-char (point-min))
856 ;;;                               ;; Unix mail format
857 ;;;                               (unless (looking-at "\n*From ")
858 ;;;                                 (insert "From maildir "
859 ;;;                                         (current-time-string) "\n"))
860 ;;;                               (while (re-search-forward "^From " nil t)
861 ;;;                                 (replace-match ">From "))
862 ;;;                               (goto-char (point-max))
863 ;;;                               (insert "\n\n")
864                                   ;; MMDF mail format
865                                   (insert "\001\001\001\001\n"))
866                                 (delete-file file)))))
867               (incf found (mail-source-callback callback file))))))
868       found)))
869
870 (eval-and-compile
871   (autoload 'imap-open "imap")
872   (autoload 'imap-authenticate "imap")
873   (autoload 'imap-mailbox-select "imap")
874   (autoload 'imap-mailbox-unselect "imap")
875   (autoload 'imap-mailbox-close "imap")
876   (autoload 'imap-search "imap")
877   (autoload 'imap-fetch "imap")
878   (autoload 'imap-close "imap")
879   (autoload 'imap-error-text "imap")
880   (autoload 'imap-message-flags-add "imap")
881   (autoload 'imap-list-to-message-set "imap")
882   (autoload 'imap-range-to-message-set "imap"))
883
884 (defvar mail-source-imap-file-coding-system 'binary
885   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
886
887 (defun mail-source-fetch-imap (source callback)
888   "Fetcher for imap sources."
889   (mail-source-bind (imap source)
890     (let ((from (format "%s:%s:%s" server user port))
891           (found 0)
892           (buf (get-buffer-create
893                 (format " *imap source %s:%s:%s *" server user mailbox)))
894           (mail-source-string (format "imap:%s:%s" server mailbox))
895           (imap-shell-program (or (list program) imap-shell-program))
896           remove)
897       (if (and (imap-open server port stream authentication buf)
898                (imap-authenticate
899                 user (or (cdr (assoc from mail-source-password-cache))
900                          password) buf)
901                (imap-mailbox-select mailbox nil buf))
902           (let ((coding-system-for-write mail-source-imap-file-coding-system)
903                 (output-coding-system mail-source-imap-file-coding-system)
904                 str)
905             (with-temp-file mail-source-crash-box
906               ;; Avoid converting 8-bit chars from inserted strings to
907               ;; multibyte.
908               (set-buffer-multibyte nil)
909               ;; remember password
910               (with-current-buffer buf
911                 (when (or imap-password
912                           (assoc from mail-source-password-cache))
913                   (push (cons from imap-password) mail-source-password-cache)))
914               ;; if predicate is nil, use all uids
915               (dolist (uid (imap-search (or predicate "1:*") buf))
916                 (when (setq str (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf))
917                   (push uid remove)
918                   (insert "From imap " (current-time-string) "\n")
919                   (save-excursion
920                     (insert str "\n\n"))
921                   (while (re-search-forward "^From " nil t)
922                     (replace-match ">From "))
923                   (goto-char (point-max))))
924               (nnheader-ms-strip-cr))
925             (incf found (mail-source-callback callback server))
926             (when (and remove fetchflag)
927               (imap-message-flags-add
928                (imap-range-to-message-set (gnus-compress-sequence remove))
929                fetchflag nil buf))
930             (if dontexpunge
931                 (imap-mailbox-unselect buf)
932               (imap-mailbox-close buf))
933             (imap-close buf))
934         (imap-close buf)
935         ;; We nix out the password in case the error
936         ;; was because of a wrong password being given.
937         (setq mail-source-password-cache
938               (delq (assoc from mail-source-password-cache)
939                     mail-source-password-cache))
940         (error (imap-error-text buf)))
941       (kill-buffer buf)
942       found)))
943
944 (eval-and-compile
945   (autoload 'webmail-fetch "webmail"))
946
947 (defun mail-source-fetch-webmail (source callback)
948   "Fetch for webmail source."
949   (mail-source-bind (webmail source)
950     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
951           (webmail-newmail-only dontexpunge)
952           (webmail-move-to-trash-can (not dontexpunge)))
953       (when (eq authentication 'password)
954         (setq password
955               (or password
956                   (cdr (assoc (format "webmail:%s:%s" subtype user)
957                               mail-source-password-cache))
958                   (mail-source-read-passwd
959                    (format "Password for %s at %s: " user subtype))))
960         (when (and password
961                    (not (assoc (format "webmail:%s:%s" subtype user)
962                                mail-source-password-cache)))
963           (push (cons (format "webmail:%s:%s" subtype user) password)
964                 mail-source-password-cache)))
965       (webmail-fetch mail-source-crash-box subtype user password)
966       (mail-source-callback callback (symbol-name subtype)))))
967
968 (provide 'mail-source)
969
970 ;;; mail-source.el ends here