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