2001-07-04 Simon Josefsson <jas@extundo.com>
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- imap backend for Gnus
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Simon Josefsson <jas@pdc.kth.se>
5 ;;         Jim Radford <radford@robby.caltech.edu>
6 ;; Keywords: mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Todo, major things:
28 ;;
29 ;;   o Fix Gnus to view correct number of unread/total articles in group buffer
30 ;;   o Fix Gnus to handle leading '.' in group names (fixed?)
31 ;;   o Finish disconnected mode (moving articles between mailboxes unplugged)
32 ;;   o Sieve
33 ;;   o MIME (partial article fetches)
34 ;;   o Split to other backends, different split rules for different
35 ;;     servers/inboxes
36 ;;
37 ;; Todo, minor things:
38 ;;
39 ;;   o Don't require half of Gnus -- backends should be standalone
40 ;;   o Verify that we don't use IMAP4rev1 specific things (RFC2060 App B)
41 ;;   o Dont uid fetch 1,* in nnimap-retrive-groups (slow)
42 ;;   o Split up big fetches (1,* header especially) in smaller chunks
43 ;;   o What do I do with gnus-newsgroup-*?
44 ;;   o Tell Gnus about new groups (how can we tell?)
45 ;;   o Respooling (fix Gnus?) (unnecessery?)
46 ;;   o Add support for the following: (if applicable)
47 ;;       request-list-newsgroups, request-regenerate
48 ;;       list-active-group,
49 ;;       request-associate-buffer, request-restore-buffer,
50 ;;   o Do The Right Thing when UIDVALIDITY changes (what's the right thing?)
51 ;;   o Support RFC2221 (Login referrals)
52 ;;   o IMAP2BIS compatibility? (RFC2061)
53 ;;   o ACAP stuff (perhaps a different project, would be nice to ACAPify
54 ;;     .newsrc.eld)
55 ;;   o What about Gnus's article editing, can we support it?  NO!
56 ;;   o Use \Draft to support the draft group??
57 ;;   o Duplicate suppression
58
59 ;;; Code:
60
61 (eval-and-compile
62   (require 'cl)
63   (require 'imap))
64
65 (require 'nnoo)
66 (require 'nnmail)
67 (require 'nnheader)
68 (require 'mm-util)
69 (require 'gnus)
70 (require 'gnus-range)
71 (require 'gnus-start)
72 (require 'gnus-int)
73
74 (nnoo-declare nnimap)
75
76 (defconst nnimap-version "nnimap 0.131")
77
78 (defvoo nnimap-address nil
79   "Address of physical IMAP server.  If nil, use the virtual server's name.")
80
81 (defvoo nnimap-server-port nil
82   "Port number on physical IMAP server.
83 If nil, defaults to 993 for SSL connections and 143 otherwise.")
84
85 ;; Splitting variables
86
87 (defvar nnimap-split-crosspost t
88   "If non-nil, do crossposting if several split methods match the mail.
89 If nil, the first match found will be used.")
90
91 (defvar nnimap-split-inbox nil
92   "*Name of mailbox to split mail from.
93
94 Mail is read from this mailbox and split according to rules in
95 `nnimap-split-rule'.
96
97 This can be a string or a list of strings.")
98
99 (defvar nnimap-split-rule nil
100   "*Mail will be split according to theese rules.
101
102 Mail is read from mailbox(es) specified in `nnimap-split-inbox'.
103
104 If you'd like, for instance, one mail group for mail from the
105 \"gnus-imap\" mailing list, one group for junk mail and leave
106 everything else in the incoming mailbox, you could do something like
107 this:
108
109 (setq nnimap-split-rule '((\"INBOX.gnus-imap\"   \"From:.*gnus-imap\")
110                           (\"INBOX.junk\"        \"Subject:.*buy\")))
111
112 As you can see, `nnimap-split-rule' is a list of lists, where the first
113 element in each \"rule\" is the name of the IMAP mailbox, and the
114 second is a regexp that nnimap will try to match on the header to find
115 a fit.
116
117 The second element can also be a function.  In that case, it will be
118 called narrowed to the headers with the first element of the rule as
119 the argument.  It should return a non-nil value if it thinks that the
120 mail belongs in that group.
121
122 This variable can also have a function as its value, the function will
123 be called with the headers narrowed and should return a group where it
124 thinks the article should be splitted to.  See `nnimap-split-fancy'.
125
126 To allow for different split rules on different virtual servers, and
127 even different split rules in different inboxes on the same server,
128 the syntax of this variable have been extended along the lines of:
129
130 (setq nnimap-split-rule
131       '((\"my1server\"    (\".*\"    ((\"ding\"    \"ding@gnus.org\")
132                                   (\"junk\"    \"From:.*Simon\")))
133         (\"my2server\"    (\"INBOX\" nnimap-split-fancy))
134         (\"my[34]server\" (\".*\"    ((\"private\" \"To:.*Simon\")
135                                   (\"junk\"    my-junk-func)))))
136
137 The virtual server name is in fact a regexp, so that the same rules
138 may apply to several servers.  In the example, the servers
139 \"my3server\" and \"my4server\" both use the same rules.  Similarly,
140 the inbox string is also a regexp.  The actual splitting rules are as
141 before, either a function, or a list with group/regexp or
142 group/function elements.")
143
144 (defvar nnimap-split-predicate "UNSEEN UNDELETED"
145   "The predicate used to find articles to split.
146 If you use another IMAP client to peek on articles but always would
147 like nnimap to split them once it's started, you could change this to
148 \"UNDELETED\". Other available predicates are available in
149 RFC2060 section 6.4.4.")
150
151 (defvar nnimap-split-fancy nil
152   "Like `nnmail-split-fancy', which see.")
153
154 ;; Authorization / Privacy variables
155
156 (defvoo nnimap-auth-method nil
157   "Obsolete.")
158
159 (defvoo nnimap-stream nil
160   "How nnimap will connect to the server.
161
162 The default, nil, will try to use the \"best\" method the server can
163 handle.
164
165 Change this if
166
167 1) you want to connect with SSL.  The SSL integration with IMAP is
168    brain-dead so you'll have to tell it specifically.
169
170 2) your server is more capable than your environment -- i.e. your
171    server accept Kerberos login's but you haven't installed the
172    `imtest' program or your machine isn't configured for Kerberos.
173
174 Possible choices: kerberos4, ssl, network")
175
176 (defvoo nnimap-authenticator nil
177   "How nnimap authenticate itself to the server.
178
179 The default, nil, will try to use the \"best\" method the server can
180 handle.
181
182 There is only one reason for fiddling with this variable, and that is
183 if your server is more capable than your environment -- i.e. you
184 connect to a server that accept Kerberos login's but you haven't
185 installed the `imtest' program or your machine isn't configured for
186 Kerberos.
187
188 Possible choices: kerberos4, cram-md5, login, anonymous.")
189
190 (defvoo nnimap-directory (nnheader-concat gnus-directory "overview/")
191   "Directory to keep NOV cache files for nnimap groups.
192 See also `nnimap-nov-file-name'.")
193
194 (defvoo nnimap-nov-file-name "nnimap."
195   "NOV cache base filename.
196 The group name and `nnimap-nov-file-name-suffix' will be appended.  A
197 typical complete file name would be
198 ~/News/overview/nnimap.pdc.INBOX.ding.nov, or
199 ~/News/overview/nnimap/pdc/INBOX/ding/nov if
200 `nnmail-use-long-file-names' is nil")
201
202 (defvoo nnimap-nov-file-name-suffix ".novcache"
203   "Suffix for NOV cache base filename.")
204
205 (defvoo nnimap-nov-is-evil nil
206   "If non-nil, nnimap will never generate or use a local nov database for this backend.
207 Using nov databases will speed up header fetching considerably.
208 Unlike other backends, you do not need to take special care if you
209 flip this variable.")
210
211 (defvoo nnimap-expunge-on-close 'always ; 'ask, 'never
212   "Whether to expunge a group when it is closed.
213 When a IMAP group with articles marked for deletion is closed, this
214 variable determine if nnimap should actually remove the articles or
215 not.
216
217 If always, nnimap always perform a expunge when closing the group.
218 If never, nnimap never expunges articles marked for deletion.
219 If ask, nnimap will ask you if you wish to expunge marked articles.
220
221 When setting this variable to `never', you can only expunge articles
222 by using `G x' (gnus-group-nnimap-expunge) from the Group buffer.")
223
224 (defvoo nnimap-list-pattern "*"
225   "A string LIMIT or list of strings with mailbox wildcards used to limit available groups.
226 See below for available wildcards.
227
228 The LIMIT string can be a cons cell (REFERENCE . LIMIT), where
229 REFERENCE will be passed as the first parameter to LIST/LSUB.  The
230 semantics of this are server specific, on the University of Washington
231 server you can specify a directory.
232
233 Example:
234  '(\"INBOX\" \"mail/*\" (\"~friend/mail/\" . \"list/*\"))
235
236 There are two wildcards * and %. * matches everything, % matches
237 everything in the current hierarchy.")
238
239 (defvoo nnimap-news-groups nil
240   "IMAP support a news-like mode, also known as bulletin board mode,
241 where replies is sent via IMAP instead of SMTP.
242
243 This variable should contain a regexp matching groups where you wish
244 replies to be stored to the mailbox directly.
245
246 Example:
247   '(\"^[^I][^N][^B][^O][^X].*$\")
248
249 This will match all groups not beginning with \"INBOX\".
250
251 Note that there is nothing technically different between mail-like and
252 news-like mailboxes.  If you wish to have a group with todo items or
253 similar which you wouldn't want to set up a mailing list for, you can
254 use this to make replies go directly to the group.")
255
256 (defvoo nnimap-expunge-search-string "UID %s NOT SINCE %s"
257   "*IMAP search command to use for articles that are to be expired.
258 The first %s is replaced by a UID set of articles to search on,
259 and the second %s is replaced by a date criterium.
260
261 One useful (and perhaps the only useful) value to change this to would
262 be `UID %s NOT SENTSINCE %s' to make nnimap use the Date: header
263 instead of the internal date of messages.  See section 6.4.4 of RFC
264 2060 for more information on valid strings.")
265
266 (defvoo nnimap-importantize-dormant t
267   "*If non-nil, mark \"dormant\" articles as \"ticked\" for other IMAP clients.
268 Note that within Gnus, dormant articles will still (only) be
269 marked as ticked.  This is to make \"dormant\" articles stand out,
270 just like \"ticked\" articles, in other IMAP clients.")
271
272 (defvoo nnimap-server-address nil
273   "Obsolete.  Use `nnimap-address'.")
274
275 (defcustom nnimap-authinfo-file "~/.authinfo"
276   "Authorization information for IMAP servers.  In .netrc format."
277   :type
278   '(choice file
279            (repeat :tag "Entries"
280                    :menu-tag "Inline"
281                    (list :format "%v"
282                          :value ("" ("login" . "") ("password" . ""))
283                          (string :tag "Host")
284                          (checklist :inline t
285                                     (cons :format "%v"
286                                           (const :format "" "login")
287                                           (string :format "Login: %v"))
288                                     (cons :format "%v"
289                                           (const :format "" "password")
290                                           (string :format "Password: %v")))))))
291
292 (defcustom nnimap-prune-cache t
293   "If non-nil, nnimap check whether articles still exist on server before using data stored in NOV cache."
294   :type 'boolean)
295
296 (defvar nnimap-request-list-method 'imap-mailbox-list
297   "Method to use to request a list of all folders from the server.
298 If this is 'imap-mailbox-lsub, then use a server-side subscription list to
299 restrict visible folders.")
300
301 ;; Internal variables:
302
303 (defvar nnimap-debug nil
304   "Name of buffer to record debugging info.
305 For example: (setq nnimap-debug \"*nnimap-debug*\")")
306 (defvar nnimap-current-move-server nil)
307 (defvar nnimap-current-move-group nil)
308 (defvar nnimap-current-move-article nil)
309 (defvar nnimap-length)
310 (defvar nnimap-progress-chars '(?| ?/ ?- ?\\))
311 (defvar nnimap-progress-how-often 20)
312 (defvar nnimap-counter)
313 (defvar nnimap-callback-callback-function nil
314   "Gnus callback the nnimap asynchronous callback should call.")
315 (defvar nnimap-callback-buffer nil
316   "Which buffer the asynchronous article prefetch callback should work in.")
317 (defvar nnimap-server-buffer-alist nil) ;; Map server name to buffers.
318 (defvar nnimap-current-server nil)      ;; Current server
319 (defvar nnimap-server-buffer nil)       ;; Current servers' buffer
320
321 \f
322
323 (nnoo-define-basics nnimap)
324
325 ;; Utility functions:
326
327 (defsubst nnimap-get-server-buffer (server)
328   "Return buffer for SERVER, if nil use current server."
329   (cadr (assoc (or server nnimap-current-server) nnimap-server-buffer-alist)))
330
331 (defun nnimap-possibly-change-server (server)
332   "Return buffer for SERVER, changing the current server as a side-effect.
333 If SERVER is nil, uses the current server."
334   (setq nnimap-current-server (or server nnimap-current-server)
335         nnimap-server-buffer (nnimap-get-server-buffer nnimap-current-server)))
336
337 (defun nnimap-verify-uidvalidity (group server)
338   "Verify stored uidvalidity match current one in GROUP on SERVER."
339   (let* ((gnusgroup (gnus-group-prefixed-name
340                      group (gnus-server-to-method
341                             (format "nnimap:%s" server))))
342          (new-uidvalidity (imap-mailbox-get 'uidvalidity))
343          (old-uidvalidity (gnus-group-get-parameter gnusgroup 'uidvalidity))
344          (dir (file-name-as-directory (expand-file-name nnimap-directory)))
345          (nameuid (nnheader-translate-file-chars
346                    (concat nnimap-nov-file-name
347                            (if (equal server "")
348                                "unnamed"
349                              server) "." group "." old-uidvalidity
350                              nnimap-nov-file-name-suffix) t))
351          (file (if (or nnmail-use-long-file-names
352                        (file-exists-p (expand-file-name nameuid dir)))
353                    (expand-file-name nameuid dir)
354                  (expand-file-name
355                   (mm-encode-coding-string
356                    (nnheader-replace-chars-in-string nameuid ?. ?/)
357                    nnmail-pathname-coding-system)
358                   dir))))
359     (if old-uidvalidity
360         (if (not (equal old-uidvalidity new-uidvalidity))
361             ;; uidvalidity clash
362             (gnus-delete-file file)
363           (gnus-group-set-parameter gnusgroup 'uidvalidity new-uidvalidity)
364           t)
365       (gnus-group-add-parameter gnusgroup (cons 'uidvalidity new-uidvalidity))
366       t)))
367
368 (defun nnimap-before-find-minmax-bugworkaround ()
369   "Function called before iterating through mailboxes with
370 `nnimap-find-minmax-uid'."
371   ;; XXX this is for UoW imapd problem, it doesn't notice new mail in
372   ;; currently selected mailbox without a re-select/examine.
373   (or (null (imap-current-mailbox nnimap-server-buffer))
374       (imap-mailbox-unselect nnimap-server-buffer)))
375
376 (defun nnimap-find-minmax-uid (group &optional examine)
377   "Find lowest and highest active article nummber in GROUP.
378 If EXAMINE is non-nil the group is selected read-only."
379   (with-current-buffer nnimap-server-buffer
380     (when (imap-mailbox-select group examine)
381       (let (minuid maxuid)
382         (when (> (imap-mailbox-get 'exists) 0)
383           (imap-fetch "1,*" "UID" nil 'nouidfetch)
384           (imap-message-map (lambda (uid Uid)
385                               (setq minuid (if minuid (min minuid uid) uid)
386                                     maxuid (if maxuid (max maxuid uid) uid)))
387                             'UID))
388         (list (imap-mailbox-get 'exists) minuid maxuid)))))
389   
390 (defun nnimap-possibly-change-group (group &optional server)
391   "Make GROUP the current group, and SERVER the current server."
392   (when (nnimap-possibly-change-server server)
393     (with-current-buffer nnimap-server-buffer
394       (if (or (null group) (imap-current-mailbox-p group))
395           imap-current-mailbox
396         (if (imap-mailbox-select group)
397             (if (or (nnimap-verify-uidvalidity
398                      group (or server nnimap-current-server))
399                     (zerop (imap-mailbox-get 'exists group))
400                     (yes-or-no-p
401                      (format
402                       "nnimap: Group %s is not uidvalid.  Continue? " group)))
403                 imap-current-mailbox
404               (imap-mailbox-unselect)
405               (error "nnimap: Group %s is not uid-valid." group))
406           (nnheader-report 'nnimap (imap-error-text)))))))
407
408 (defun nnimap-replace-whitespace (string)
409   "Return STRING with all whitespace replaced with space."
410   (when string
411     (while (string-match "[\r\n\t]+" string)
412       (setq string (replace-match " " t t string)))
413     string))
414
415 ;; Required backend functions
416
417 (defun nnimap-retrieve-headers-progress ()
418   "Hook to insert NOV line for current article into `nntp-server-buffer'."
419   (and (numberp nnmail-large-newsgroup)
420        (zerop (% (incf nnimap-counter) nnimap-progress-how-often))
421        (> nnimap-length nnmail-large-newsgroup)
422        (nnheader-message 6 "nnimap: Retrieving headers... %c"
423                          (nth (/ (% nnimap-counter
424                                     (* (length nnimap-progress-chars)
425                                        nnimap-progress-how-often))
426                                  nnimap-progress-how-often)
427                               nnimap-progress-chars)))
428   (with-current-buffer nntp-server-buffer
429     (let (headers lines chars uid mbx)
430       (with-current-buffer nnimap-server-buffer
431         (setq uid imap-current-message
432               mbx imap-current-mailbox
433               headers (nnimap-demule
434                        (if (imap-capability 'IMAP4rev1)
435                            ;; xxx don't just use car? alist doesn't contain
436                            ;; anything else now, but it might...
437                            (nth 2 (car (imap-message-get uid 'BODYDETAIL)))
438                          (imap-message-get uid 'RFC822.HEADER)))
439               lines (imap-body-lines (imap-message-body imap-current-message))
440               chars (imap-message-get imap-current-message 'RFC822.SIZE)))
441       (nnheader-insert-nov
442        (with-temp-buffer
443          (buffer-disable-undo)
444          (insert headers)
445          (nnheader-ms-strip-cr)
446          (nnheader-fold-continuation-lines)
447          (subst-char-in-region (point-min) (point-max) ?\t ? )
448          (let ((head (nnheader-parse-head 'naked)))
449            (mail-header-set-number head uid)
450            (mail-header-set-chars head chars)
451            (mail-header-set-lines head lines)
452            (mail-header-set-xref
453             head (format "%s %s:%d" (system-name) mbx uid))
454            head))))))
455
456 (defun nnimap-retrieve-which-headers (articles fetch-old)
457   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
458   (with-current-buffer nnimap-server-buffer
459     (if (numberp (car-safe articles))
460         (imap-search
461          (concat "UID "
462                  (imap-range-to-message-set
463                   (gnus-compress-sequence
464                    (append (gnus-uncompress-sequence
465                             (and fetch-old
466                                  (cons (if (numberp fetch-old)
467                                            (max 1 (- (car articles) fetch-old))
468                                          1)
469                                        (1- (car articles)))))
470                            articles)))))
471       (mapcar (lambda (msgid)
472                 (imap-search
473                  (format "HEADER Message-Id \"%s\"" msgid)))
474               articles))))
475
476 (defun nnimap-group-overview-filename (group server)
477   "Make pathname for GROUP on SERVER."
478   (let* ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
479          (uidvalidity (gnus-group-get-parameter
480                        (gnus-group-prefixed-name
481                         group (gnus-server-to-method
482                                (format "nnimap:%s" server)))
483                        'uidvalidity))
484          (name (nnheader-translate-file-chars
485                 (concat nnimap-nov-file-name
486                         (if (equal server "")
487                             "unnamed"
488                           server) "." group nnimap-nov-file-name-suffix) t))
489          (nameuid (nnheader-translate-file-chars
490                    (concat nnimap-nov-file-name
491                            (if (equal server "")
492                                "unnamed"
493                              server) "." group "." uidvalidity
494                              nnimap-nov-file-name-suffix) t))
495          (oldfile (if (or nnmail-use-long-file-names
496                           (file-exists-p (expand-file-name name dir)))
497                       (expand-file-name name dir)
498                     (expand-file-name
499                      (mm-encode-coding-string
500                       (nnheader-replace-chars-in-string name ?. ?/)
501                       nnmail-pathname-coding-system)
502                      dir)))
503          (newfile (if (or nnmail-use-long-file-names
504                           (file-exists-p (expand-file-name nameuid dir)))
505                       (expand-file-name nameuid dir)
506                     (expand-file-name
507                      (mm-encode-coding-string
508                       (nnheader-replace-chars-in-string nameuid ?. ?/)
509                       nnmail-pathname-coding-system)
510                      dir))))
511     (when (and (file-exists-p oldfile) (not (file-exists-p newfile)))
512       (message "nnimap: Upgrading novcache filename...")
513       (sit-for 1)
514       (gnus-make-directory (file-name-directory newfile))
515       (unless (ignore-errors (rename-file oldfile newfile) t)
516         (if (ignore-errors (copy-file oldfile newfile) t)
517             (delete-file oldfile)
518           (error "Can't rename `%s' to `%s'" oldfile newfile))))
519     newfile))
520
521 (defun nnimap-retrieve-headers-from-file (group server)
522   (with-current-buffer nntp-server-buffer
523     (let ((nov (nnimap-group-overview-filename group server)))
524       (when (file-exists-p nov)
525         (mm-insert-file-contents nov)
526         (set-buffer-modified-p nil)
527         (let ((min (ignore-errors (goto-char (point-min))
528                                   (read (current-buffer))))
529               (max (ignore-errors (goto-char (point-max))
530                                   (forward-line -1)
531                                   (read (current-buffer)))))
532           (if (and (numberp min) (numberp max))
533               (cons min max)
534             ;; junk, remove it, it's saved later
535             (erase-buffer)
536             nil))))))
537
538 (defun nnimap-retrieve-headers-from-server (articles group server)
539   (with-current-buffer nnimap-server-buffer
540     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
541           (nnimap-length (gnus-range-length articles))
542           (nnimap-counter 0))
543       (imap-fetch (imap-range-to-message-set articles)
544                   (concat "(UID RFC822.SIZE BODY "
545                           (let ((headers
546                                  (append '(Subject From Date Message-Id
547                                                    References In-Reply-To Xref)
548                                          (copy-sequence
549                                           nnmail-extra-headers))))
550                             (if (imap-capability 'IMAP4rev1)
551                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
552                               (format "RFC822.HEADER.LINES %s)" headers)))))
553       (and (numberp nnmail-large-newsgroup)
554            (> nnimap-length nnmail-large-newsgroup)
555            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
556
557 (defun nnimap-dont-use-nov-p (group server)
558   (or gnus-nov-is-evil nnimap-nov-is-evil
559       (unless (and (gnus-make-directory
560                     (file-name-directory
561                      (nnimap-group-overview-filename group server)))
562                    (file-writable-p
563                     (nnimap-group-overview-filename group server)))
564         (message "nnimap: Nov cache not writable, %s"
565                  (nnimap-group-overview-filename group server)))))
566
567 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
568   (when (nnimap-possibly-change-group group server)
569     (with-current-buffer nntp-server-buffer
570       (erase-buffer)
571       (if (nnimap-dont-use-nov-p group server)
572           (nnimap-retrieve-headers-from-server
573            (gnus-compress-sequence articles) group server)
574         (let (uids cached low high)
575           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
576                       low (car uids)
577                       high (car (last uids)))
578             (if (setq cached (nnimap-retrieve-headers-from-file group server))
579                 (progn
580                   ;; fetch articles with uids before cache block
581                   (when (< low (car cached))
582                     (goto-char (point-min))
583                     (nnimap-retrieve-headers-from-server
584                      (cons low (1- (car cached))) group server))
585                   ;; fetch articles with uids after cache block
586                   (when (> high (cdr cached))
587                     (goto-char (point-max))
588                     (nnimap-retrieve-headers-from-server
589                      (cons (1+ (cdr cached)) high) group server))
590                   (when nnimap-prune-cache
591                     ;; remove nov's for articles which has expired on server
592                     (goto-char (point-min))
593                     (dolist (uid (gnus-set-difference articles uids))
594                       (when (re-search-forward (format "^%d\t" uid) nil t)
595                         (gnus-delete-line)))))
596               ;; nothing cached, fetch whole range from server
597               (nnimap-retrieve-headers-from-server
598                (cons low high) group server))
599             (when (buffer-modified-p)
600               (nnmail-write-region
601                1 (point-max) (nnimap-group-overview-filename group server)
602                nil 'nomesg))
603             (nnheader-nov-delete-outside-range low high))))
604       'nov)))
605
606 (defun nnimap-open-connection (server)
607   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
608                       nnimap-authenticator nnimap-server-buffer))
609       (nnheader-report 'nnimap "Can't open connection to server %s" server)
610     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
611                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
612       (imap-close nnimap-server-buffer)
613       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
614     (let* ((list (gnus-parse-netrc nnimap-authinfo-file))
615            (port (if nnimap-server-port
616                      (int-to-string nnimap-server-port)
617                    "imap"))
618            (alist (gnus-netrc-machine list (or nnimap-server-address 
619                                                nnimap-address server)
620                                       port "imap"))
621            (user (gnus-netrc-get alist "login"))
622            (passwd (gnus-netrc-get alist "password")))
623       (if (imap-authenticate user passwd nnimap-server-buffer)
624           (prog1
625               (push (list server nnimap-server-buffer)
626                     nnimap-server-buffer-alist)
627             (nnimap-possibly-change-server server))
628         (imap-close nnimap-server-buffer)
629         (kill-buffer nnimap-server-buffer)
630         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
631
632 (deffoo nnimap-open-server (server &optional defs)
633   (nnheader-init-server-buffer)
634   (if (nnimap-server-opened server)
635       t
636     (unless (assq 'nnimap-server-buffer defs)
637       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
638     ;; translate `nnimap-server-address' to `nnimap-address' in defs
639     ;; for people that configured nnimap with a very old version
640     (unless (assq 'nnimap-address defs)
641       (if (assq 'nnimap-server-address defs)
642           (push (list 'nnimap-address
643                       (cadr (assq 'nnimap-server-address defs))) defs)
644         (push (list 'nnimap-address server) defs)))
645     (nnoo-change-server 'nnimap server defs)
646     (with-current-buffer (get-buffer-create nnimap-server-buffer)
647       (nnoo-change-server 'nnimap server defs))
648     (or (and nnimap-server-buffer
649              (imap-opened nnimap-server-buffer))
650         (nnimap-open-connection server))))
651
652 (deffoo nnimap-server-opened (&optional server)
653   "Whether SERVER is opened.
654 If SERVER is the current virtual server, and the connection to the
655 physical server is alive, this function return a non-nil value.  If
656 SERVER is nil, it is treated as the current server."
657   ;; clean up autologouts??
658   (and (or server nnimap-current-server)
659        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
660        (imap-opened (nnimap-get-server-buffer server))))
661
662 (deffoo nnimap-close-server (&optional server)
663   "Close connection to server and free all resources connected to it.
664 Return nil if the server couldn't be closed for some reason."
665   (let ((server (or server nnimap-current-server)))
666     (when (or (nnimap-server-opened server)
667               (imap-opened (nnimap-get-server-buffer server)))
668       (imap-close (nnimap-get-server-buffer server))
669       (kill-buffer (nnimap-get-server-buffer server))
670       (setq nnimap-server-buffer nil
671             nnimap-current-server nil
672             nnimap-server-buffer-alist
673             (delq server nnimap-server-buffer-alist)))
674     (nnoo-close-server 'nnimap server)))
675
676 (deffoo nnimap-request-close ()
677   "Close connection to all servers and free all resources that the backend have reserved.
678 All buffers that have been created by that
679 backend should be killed.  (Not the nntp-server-buffer, though.) This
680 function is generally only called when Gnus is shutting down."
681   (mapcar (lambda (server) (nnimap-close-server (car server)))
682           nnimap-server-buffer-alist)
683   (setq nnimap-server-buffer-alist nil))
684
685 (deffoo nnimap-status-message (&optional server)
686   "This function returns the last error message from server."
687   (when (nnimap-possibly-change-server server)
688     (nnoo-status-message 'nnimap server)))
689
690 (defun nnimap-demule (string)
691   (funcall (if (and (fboundp 'string-as-multibyte)
692                     (subrp (symbol-function 'string-as-multibyte)))
693                'string-as-multibyte
694              'identity)
695            (or string "")))
696
697 (defun nnimap-callback ()
698   (remove-hook 'imap-fetch-data-hook 'nnimap-callback)
699   (with-current-buffer nnimap-callback-buffer
700     (insert
701      (with-current-buffer nnimap-server-buffer
702        (nnimap-demule
703         (if (imap-capability 'IMAP4rev1) 
704             ;; xxx don't just use car? alist doesn't contain
705             ;; anything else now, but it might...
706             (nth 2 (car (imap-message-get (imap-current-message) 'BODYDETAIL)))
707           (imap-message-get (imap-current-message) 'RFC822)))))
708     (nnheader-ms-strip-cr)
709     (funcall nnimap-callback-callback-function t)))
710
711 (defun nnimap-request-article-part (article part prop &optional
712                                             group server to-buffer detail)
713   (when (nnimap-possibly-change-group group server)
714     (let ((article (if (stringp article)
715                        (car-safe (imap-search
716                                   (format "HEADER Message-Id \"%s\"" article)
717                                   nnimap-server-buffer))
718                      article)))
719       (when article
720         (gnus-message 10 "nnimap: Fetching (part of) article %d..." article)
721         (if (not nnheader-callback-function)
722             (with-current-buffer (or to-buffer nntp-server-buffer)
723               (erase-buffer)
724               (let ((data (imap-fetch article part prop nil
725                                       nnimap-server-buffer)))
726                 (insert (nnimap-demule (if detail
727                                            (nth 2 (car data))
728                                          data))))
729               (nnheader-ms-strip-cr)
730               (gnus-message 10 "nnimap: Fetching (part of) article %d...done"
731                             article)
732               (if (bobp)
733                   (nnheader-report 'nnimap "No such article: %s"
734                                    (imap-error-text nnimap-server-buffer))
735                 (cons group article)))
736           (add-hook 'imap-fetch-data-hook 'nnimap-callback)
737           (setq nnimap-callback-callback-function nnheader-callback-function
738                 nnimap-callback-buffer nntp-server-buffer)
739           (imap-fetch-asynch article part nil nnimap-server-buffer)
740           (cons group article))))))
741
742 (deffoo nnimap-asynchronous-p ()
743   t)
744
745 (deffoo nnimap-request-article (article &optional group server to-buffer)
746   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
747       (nnimap-request-article-part
748        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
749     (nnimap-request-article-part
750      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
751
752 (deffoo nnimap-request-head (article &optional group server to-buffer)
753   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
754       (nnimap-request-article-part
755        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
756     (nnimap-request-article-part
757      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
758
759 (deffoo nnimap-request-body (article &optional group server to-buffer)
760   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
761       (nnimap-request-article-part
762        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
763     (nnimap-request-article-part
764      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
765
766 (deffoo nnimap-request-group (group &optional server fast)
767   (nnimap-request-update-info-internal
768    group
769    (gnus-get-info (gnus-group-prefixed-name
770                    group (gnus-server-to-method (format "nnimap:%s" server))))
771    server)
772   (when (nnimap-possibly-change-group group server)
773     (nnimap-before-find-minmax-bugworkaround)
774     (let (info)
775       (cond (fast group)
776             ((null (setq info (nnimap-find-minmax-uid group t)))
777              (nnheader-report 'nnimap "Could not get active info for %s"
778                               group))
779             (t
780              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
781                               (max 1 (or (nth 1 info) 1))
782                               (or (nth 2 info) 0) group)
783              (nnheader-report 'nnimap "Group %s selected" group)
784              t)))))
785
786 (defun nnimap-close-group (group &optional server)
787   (with-current-buffer nnimap-server-buffer
788     (when (and (imap-opened)
789                (nnimap-possibly-change-group group server))
790       (case nnimap-expunge-on-close
791         ('always (imap-mailbox-expunge)
792                  (imap-mailbox-close))
793         ('ask (if (and (imap-search "DELETED")
794                        (gnus-y-or-n-p (format
795                                        "Expunge articles in group `%s'? "
796                                        imap-current-mailbox)))
797                   (progn (imap-mailbox-expunge)
798                          (imap-mailbox-close))
799                 (imap-mailbox-unselect)))
800         (t (imap-mailbox-unselect)))
801       (not imap-current-mailbox))))
802
803 (defun nnimap-pattern-to-list-arguments (pattern)
804   (mapcar (lambda (p)
805             (cons (car-safe p) (or (cdr-safe p) p)))
806           (if (and (listp pattern)
807                    (listp (cdr pattern)))
808               pattern
809             (list pattern))))
810
811 (deffoo nnimap-request-list (&optional server)
812   (when (nnimap-possibly-change-server server)
813     (with-current-buffer nntp-server-buffer
814       (erase-buffer))
815     (gnus-message 5 "nnimap: Generating active list%s..."
816                   (if (> (length server) 0) (concat " for " server) ""))
817     (nnimap-before-find-minmax-bugworkaround)
818     (with-current-buffer nnimap-server-buffer
819       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
820         (dolist (mbx (funcall nnimap-request-list-method
821                               (cdr pattern) (car pattern)))
822           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
823               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
824                 (when info
825                   (with-current-buffer nntp-server-buffer
826                    (insert (format "\"%s\" %d %d y\n"
827                                    mbx (or (nth 2 info) 0)
828                                    (max 1 (or (nth 1 info) 1)))))))))))
829     (gnus-message 5 "nnimap: Generating active list%s...done"
830                   (if (> (length server) 0) (concat " for " server) ""))
831     t))
832
833 (deffoo nnimap-request-post (&optional server)
834   (let ((success t))
835     (dolist (mbx (message-unquote-tokens
836                   (message-tokenize-header
837                    (message-fetch-field "Newsgroups") ", ")) success)
838       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
839         (or (gnus-active to-newsgroup)
840             (gnus-activate-group to-newsgroup)
841             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
842                                        to-newsgroup))
843                 (or (and (gnus-request-create-group
844                           to-newsgroup gnus-command-method)
845                          (gnus-activate-group to-newsgroup nil nil
846                                               gnus-command-method))
847                     (error "Couldn't create group %s" to-newsgroup)))
848             (error "No such group: %s" to-newsgroup))
849         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
850           (setq success nil))))))
851
852 ;; Optional backend functions
853
854 (deffoo nnimap-retrieve-groups (groups &optional server)
855   (when (nnimap-possibly-change-server server)
856     (gnus-message 5 "nnimap: Checking mailboxes...")
857     (with-current-buffer nntp-server-buffer
858       (erase-buffer)
859       (nnimap-before-find-minmax-bugworkaround)
860       (dolist (group groups)
861         (gnus-message 7 "nnimap: Checking mailbox %s" group)
862         (or (member "\\NoSelect"
863                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
864             (let ((info (nnimap-find-minmax-uid group 'examine)))
865               (insert (format "\"%s\" %d %d y\n" group
866                               (or (nth 2 info) 0)
867                               (max 1 (or (nth 1 info) 1))))))))
868     (gnus-message 5 "nnimap: Checking mailboxes...done")
869     'active))
870
871 (deffoo nnimap-request-update-info-internal (group info &optional server)
872   (when (nnimap-possibly-change-group group server)
873     (when info;; xxx what does this mean? should we create a info?
874       (with-current-buffer nnimap-server-buffer
875         (gnus-message 5 "nnimap: Updating info for %s..."
876                       (gnus-info-group info))
877         
878         (when (nnimap-mark-permanent-p 'read)
879           (let (seen unseen)
880             ;; read info could contain articles marked unread by other
881             ;; imap clients!  we correct this
882             (setq seen (gnus-uncompress-range (gnus-info-read info))
883                   unseen (imap-search "UNSEEN UNDELETED")
884                   seen (gnus-set-difference seen unseen)
885                   ;; seen might lack articles marked as read by other
886                   ;; imap clients! we correct this
887                   seen (append seen (imap-search "SEEN"))
888                   ;; remove dupes
889                   seen (sort seen '<)
890                   seen (gnus-compress-sequence seen t)
891                   ;; we can't return '(1) since this isn't a "list of ranges",
892                   ;; and we can't return '((1)) since g-list-of-unread-articles
893                   ;; is buggy so we return '((1 . 1)).
894                   seen (if (and (integerp (car seen))
895                                 (null (cdr seen)))
896                            (list (cons (car seen) (car seen)))
897                          seen))
898             (gnus-info-set-read info seen)))
899
900         (mapcar (lambda (pred)
901                   (when (and (nnimap-mark-permanent-p (cdr pred))
902                              (member (nnimap-mark-to-flag (cdr pred))
903                                      (imap-mailbox-get 'flags)))
904                     (gnus-info-set-marks
905                      info
906                      (nnimap-update-alist-soft
907                       (cdr pred)
908                       (gnus-compress-sequence
909                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
910                       (gnus-info-marks info))
911                      t)))
912                 gnus-article-mark-lists)
913
914         (when nnimap-importantize-dormant
915           ;; nnimap mark dormant article as ticked too (for other clients)
916           ;; so we remove that mark for gnus since we support dormant
917           (gnus-info-set-marks
918            info 
919            (nnimap-update-alist-soft
920             'tick
921             (gnus-remove-from-range
922              (cdr-safe (assoc 'tick (gnus-info-marks info)))
923              (cdr-safe (assoc 'dormant (gnus-info-marks info))))
924             (gnus-info-marks info))
925            t))
926         
927         (gnus-message 5 "nnimap: Updating info for %s...done"
928                       (gnus-info-group info))
929
930         info))))
931
932 (deffoo nnimap-request-type (group &optional article)
933   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
934       'news
935     'mail))
936
937 (deffoo nnimap-request-set-mark (group actions &optional server)
938   (when (nnimap-possibly-change-group group server)
939     (with-current-buffer nnimap-server-buffer
940       (let (action)
941         (gnus-message 7 "nnimap: Setting marks in %s..." group)
942         (while (setq action (pop actions))
943           (let ((range (nth 0 action))
944                 (what  (nth 1 action))
945                 (cmdmarks (nth 2 action))
946                 marks)
947             ;; cache flags are pointless on the server
948             (setq cmdmarks (delq 'cache cmdmarks))
949             (when nnimap-importantize-dormant
950               ;; flag dormant articles as ticked
951               (if (memq 'dormant cmdmarks)
952                   (setq cmdmarks (cons 'tick cmdmarks))))
953             ;; remove stuff we are forbidden to store
954             (mapcar (lambda (mark)
955                       (if (imap-message-flag-permanent-p
956                            (nnimap-mark-to-flag mark))
957                           (setq marks (cons mark marks))))
958                     cmdmarks)
959             (when (and range marks)
960               (cond ((eq what 'del)
961                      (imap-message-flags-del
962                       (imap-range-to-message-set range)
963                       (nnimap-mark-to-flag marks nil t)))
964                     ((eq what 'add)
965                      (imap-message-flags-add
966                       (imap-range-to-message-set range)
967                       (nnimap-mark-to-flag marks nil t)))
968                     ((eq what 'set)
969                      (imap-message-flags-set
970                       (imap-range-to-message-set range)
971                       (nnimap-mark-to-flag marks nil t)))))))
972         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
973   nil)
974
975 (defun nnimap-split-fancy ()
976   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
977   (let ((nnmail-split-fancy nnimap-split-fancy))
978     (nnmail-split-fancy)))
979
980 (defun nnimap-split-to-groups (rules)
981   ;; tries to match all rules in nnimap-split-rule against content of
982   ;; nntp-server-buffer, returns a list of groups that matched.
983   (with-current-buffer nntp-server-buffer
984     ;; Fold continuation lines.
985     (goto-char (point-min))
986     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
987       (replace-match " " t t))
988     (if (functionp rules)
989         (funcall rules)
990       (let (to-groups regrepp)
991         (catch 'split-done
992           (dolist (rule rules to-groups)
993             (let ((group (car rule))
994                   (regexp (cadr rule)))
995               (goto-char (point-min))
996               (when (and (if (stringp regexp)
997                              (progn
998                                (setq regrepp (string-match "\\\\[0-9&]" group))
999                                (re-search-forward regexp nil t))
1000                            (funcall regexp group))
1001                          ;; Don't enter the article into the same group twice.
1002                          (not (assoc group to-groups)))
1003                 (push (if regrepp
1004                           (nnmail-expand-newtext group)
1005                         group)
1006                       to-groups)
1007                 (or nnimap-split-crosspost
1008                     (throw 'split-done to-groups))))))))))
1009   
1010 (defun nnimap-assoc-match (key alist)
1011   (let (element)
1012     (while (and alist (not element))
1013       (if (string-match (car (car alist)) key)
1014           (setq element (car alist)))
1015       (setq alist (cdr alist)))
1016     element))
1017
1018 (defun nnimap-split-find-rule (server inbox)
1019   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
1020            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
1021       ;; extended format
1022       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match 
1023                                             server nnimap-split-rule))))
1024     nnimap-split-rule))
1025
1026 (defun nnimap-split-find-inbox (server)
1027   (if (listp nnimap-split-inbox)
1028       nnimap-split-inbox
1029     (list nnimap-split-inbox)))
1030
1031 (defun nnimap-split-articles (&optional group server)
1032   (when (nnimap-possibly-change-server server)
1033     (with-current-buffer nnimap-server-buffer
1034       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
1035         ;; iterate over inboxes
1036         (while (and (setq inbox (pop inboxes))
1037                     (nnimap-possibly-change-group inbox));; SELECT
1038           ;; find split rule for this server / inbox
1039           (when (setq rule (nnimap-split-find-rule server inbox))
1040             ;; iterate over articles
1041             (dolist (article (imap-search nnimap-split-predicate))
1042               (when (nnimap-request-head article)
1043                 ;; copy article to right group(s)
1044                 (setq removeorig nil)
1045                 (dolist (to-group (nnimap-split-to-groups rule))
1046                   (cond ((eq to-group 'junk)
1047                          (message "IMAP split removed %s:%s:%d" server inbox
1048                                   article)
1049                          (setq removeorig t))
1050                         ((imap-message-copy (number-to-string article)
1051                                             to-group nil 'nocopyuid)
1052                          (message "IMAP split moved %s:%s:%d to %s" server
1053                                   inbox article to-group)
1054                          (setq removeorig t)
1055                          ;; Add the group-art list to the history list.
1056                          (push (list (cons to-group 0)) nnmail-split-history))
1057                         (t
1058                          (message "IMAP split failed to move %s:%s:%d to %s"
1059                                   server inbox article to-group))))
1060                 ;; remove article if it was successfully copied somewhere
1061                 (and removeorig
1062                      (imap-message-flags-add (format "%d" article)
1063                                              "\\Seen \\Deleted")))))
1064           (when (imap-mailbox-select inbox);; just in case
1065             ;; todo: UID EXPUNGE (if available) to remove splitted articles
1066             (imap-mailbox-expunge)
1067             (imap-mailbox-close)))
1068         t))))
1069
1070 (deffoo nnimap-request-scan (&optional group server)
1071   (nnimap-split-articles group server))
1072
1073 (deffoo nnimap-request-newgroups (date &optional server)
1074   (when (nnimap-possibly-change-server server)
1075     (with-current-buffer nntp-server-buffer
1076       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
1077                     (if (> (length server) 0) " on " "") server)
1078       (erase-buffer)
1079       (nnimap-before-find-minmax-bugworkaround)
1080       (dolist (pattern (nnimap-pattern-to-list-arguments
1081                         nnimap-list-pattern))
1082         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil 
1083                                         nnimap-server-buffer))
1084           (or (catch 'found
1085                 (dolist (mailbox (imap-mailbox-get 'list-flags mbx
1086                                                    nnimap-server-buffer))
1087                   (if (string= (downcase mailbox) "\\noselect")
1088                       (throw 'found t)))
1089                 nil)
1090               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
1091                 (when info
1092                  (insert (format "\"%s\" %d %d y\n"
1093                                  mbx (or (nth 2 info) 0)
1094                                  (max 1 (or (nth 1 info) 1)))))))))
1095       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1096                     (if (> (length server) 0) " on " "") server))
1097     t))
1098       
1099 (deffoo nnimap-request-create-group (group &optional server args)
1100   (when (nnimap-possibly-change-server server)
1101     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1102         (imap-mailbox-create group nnimap-server-buffer))))
1103
1104 (defun nnimap-time-substract (time1 time2)
1105   "Return TIME for TIME1 - TIME2."
1106   (let* ((ms (- (car time1) (car time2)))
1107          (ls (- (nth 1 time1) (nth 1 time2))))
1108     (if (< ls 0)
1109         (list (- ms 1) (+ (expt 2 16) ls))
1110       (list ms ls))))
1111
1112 (defun nnimap-date-days-ago (daysago)
1113   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1114   (let* ((time (nnimap-time-substract (current-time) (days-to-time daysago)))
1115          (date (format-time-string
1116                 (format "%%d-%s-%%Y"
1117                         (capitalize (car (rassoc (nth 4 (decode-time time))
1118                                                  parse-time-months))))
1119                 time)))
1120     (if (eq ?0 (string-to-char date))
1121         (substring date 1)
1122       date)))
1123
1124 (defun nnimap-request-expire-articles-progress ()
1125   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1126                 imap-current-message))
1127
1128
1129 (defun nnimap-expiry-target (arts group server)
1130   (unless (eq nnmail-expiry-target 'delete)
1131     (with-current-buffer nntp-server-buffer
1132       (dolist (art (gnus-uncompress-sequence arts))
1133         (nnimap-request-article art group server)
1134         ;; hints for optimization in `nnimap-request-accept-article'
1135         (let ((nnimap-current-move-article art)
1136               (nnimap-current-move-group group)
1137               (nnimap-current-move-server server))
1138           (nnmail-expiry-target-group nnmail-expiry-target group))))))
1139
1140 ;; Notice that we don't actually delete anything, we just mark them deleted.
1141 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1142   (let ((artseq (gnus-compress-sequence articles)))
1143     (when (and artseq (nnimap-possibly-change-group group server))
1144       (with-current-buffer nnimap-server-buffer
1145         (if force
1146             (progn
1147               (nnimap-expiry-target artseq group server)
1148               (when (imap-message-flags-add (imap-range-to-message-set artseq)
1149                                             "\\Deleted")
1150                 (setq articles nil)))
1151           (let ((days (or (and nnmail-expiry-wait-function
1152                                (funcall nnmail-expiry-wait-function group))
1153                           nnmail-expiry-wait)))
1154             (cond ((eq days 'immediate)
1155                    (nnimap-expiry-target artseq group server)
1156                    (when (imap-message-flags-add
1157                           (imap-range-to-message-set artseq) "\\Deleted")
1158                      (setq articles nil)))
1159                   ((numberp days)
1160                    (let ((oldarts (imap-search
1161                                    (format nnimap-expunge-search-string
1162                                            (imap-range-to-message-set artseq)
1163                                            (nnimap-date-days-ago days))))
1164                          (imap-fetch-data-hook
1165                           '(nnimap-request-expire-articles-progress)))
1166                      (nnimap-expiry-target oldarts group server)
1167                      (and oldarts
1168                           (imap-message-flags-add
1169                            (imap-range-to-message-set
1170                             (gnus-compress-sequence oldarts))
1171                            "\\Deleted")
1172                           (setq articles (gnus-set-difference
1173                                           articles oldarts)))))))))))
1174   ;; return articles not deleted
1175   articles)
1176
1177 (deffoo nnimap-request-move-article (article group server
1178                                              accept-form &optional last)
1179   (when (nnimap-possibly-change-server server)
1180     (save-excursion
1181       (let ((buf (get-buffer-create " *nnimap move*"))
1182             (nnimap-current-move-article article)
1183             (nnimap-current-move-group group)
1184             (nnimap-current-move-server nnimap-current-server)
1185             result)
1186         (and (nnimap-request-article article group server)
1187              (save-excursion
1188                (set-buffer buf)
1189                (buffer-disable-undo (current-buffer))
1190                (insert-buffer-substring nntp-server-buffer)
1191                (setq result (eval accept-form))
1192                (kill-buffer buf)
1193                result)
1194              (nnimap-request-expire-articles (list article) group server t))
1195         result))))
1196   
1197 (deffoo nnimap-request-accept-article (group &optional server last)
1198   (when (nnimap-possibly-change-server server)
1199     (let (uid)
1200       (if (setq uid
1201                 (if (string= nnimap-current-server nnimap-current-move-server)
1202                     ;; moving article within same server, speed it up...
1203                     (and (nnimap-possibly-change-group
1204                           nnimap-current-move-group)
1205                          (imap-message-copy (number-to-string
1206                                              nnimap-current-move-article)
1207                                             group 'dontcreate nil
1208                                             nnimap-server-buffer))
1209                   (with-current-buffer (current-buffer)
1210                     (goto-char (point-min))
1211                     ;; remove any 'From blabla' lines, some IMAP servers
1212                     ;; reject the entire message otherwise.
1213                     (when (looking-at "^From[^:]")
1214                       (kill-region (point) (progn (forward-line) (point))))
1215                     ;; turn into rfc822 format (\r\n eol's)
1216                     (while (search-forward "\n" nil t)
1217                       (replace-match "\r\n")))
1218                   ;; this 'or' is for Cyrus server bug
1219                   (or (null (imap-current-mailbox nnimap-server-buffer))
1220                       (imap-mailbox-unselect nnimap-server-buffer))
1221                   (imap-message-append group (current-buffer) nil nil
1222                                        nnimap-server-buffer)))
1223           (cons group (nth 1 uid))
1224         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1225
1226 (deffoo nnimap-request-delete-group (group force &optional server)
1227   (when (nnimap-possibly-change-server server)
1228     (with-current-buffer nnimap-server-buffer
1229       (if force
1230           (or (null (imap-mailbox-status group 'uidvalidity))
1231               (imap-mailbox-delete group))
1232         ;; UNSUBSCRIBE?
1233         t))))
1234
1235 (deffoo nnimap-request-rename-group (group new-name &optional server)
1236   (when (nnimap-possibly-change-server server)
1237     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1238
1239 (defun nnimap-expunge (mailbox server)
1240   (when (nnimap-possibly-change-group mailbox server)
1241     (imap-mailbox-expunge nnimap-server-buffer)))
1242
1243 (defun nnimap-acl-get (mailbox server)
1244   (when (nnimap-possibly-change-server server)
1245     (and (imap-capability 'ACL nnimap-server-buffer)
1246          (imap-mailbox-acl-get mailbox nnimap-server-buffer))))
1247
1248 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1249   (when (nnimap-possibly-change-server (cadr method))
1250     (unless (imap-capability 'ACL nnimap-server-buffer)
1251       (error "Your server does not support ACL editing"))
1252     (with-current-buffer nnimap-server-buffer
1253       ;; delete all removed identifiers
1254       (mapcar (lambda (old-acl)
1255                 (unless (assoc (car old-acl) new-acls)
1256                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1257                       (error "Can't delete ACL for %s" (car old-acl)))))
1258               old-acls)
1259       ;; set all changed acl's
1260       (mapcar (lambda (new-acl)
1261                 (let ((new-rights (cdr new-acl))
1262                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1263                   (unless (and old-rights new-rights
1264                                (string= old-rights new-rights))
1265                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1266                         (error "Can't set ACL for %s to %s" (car new-acl)
1267                                new-rights)))))
1268               new-acls)
1269       t)))
1270
1271 \f
1272 ;;; Internal functions
1273
1274 ;;
1275 ;; This is confusing.
1276 ;;
1277 ;; mark      => read, tick, draft, reply etc
1278 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1279 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1280 ;;
1281 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1282 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1283 ;;
1284
1285 (defconst nnimap-mark-to-predicate-alist
1286   (mapcar
1287    (lambda (pair)                       ; cdr is the mark
1288      (or (assoc (cdr pair)
1289                 '((read . "SEEN")
1290                   (tick . "FLAGGED")
1291                   (draft . "DRAFT")
1292                   (reply . "ANSWERED")))
1293          (cons (cdr pair)
1294                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1295    (cons '(read . read) gnus-article-mark-lists)))
1296
1297 (defun nnimap-mark-to-predicate (pred)
1298   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1299 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1300 to be used within a IMAP SEARCH query."
1301   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1302
1303 (defconst nnimap-mark-to-flag-alist
1304   (mapcar
1305    (lambda (pair)
1306      (or (assoc (cdr pair)
1307                 '((read . "\\Seen")
1308                   (tick . "\\Flagged")
1309                   (draft . "\\Draft")
1310                   (reply . "\\Answered")))
1311          (cons (cdr pair)
1312                (format "gnus-%s" (symbol-name (cdr pair))))))
1313    (cons '(read . read) gnus-article-mark-lists)))
1314
1315 (defun nnimap-mark-to-flag-1 (preds)
1316   (if (and (not (null preds)) (listp preds))
1317       (cons (nnimap-mark-to-flag (car preds))
1318             (nnimap-mark-to-flag (cdr preds)))
1319     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1320
1321 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1322   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1323 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1324 be used in a STORE FLAGS command."
1325   (let ((result (nnimap-mark-to-flag-1 preds)))
1326     (setq result (if (and (or make-string always-list)
1327                           (not (listp result)))
1328                      (list result)
1329                    result))
1330     (if make-string
1331         (mapconcat (lambda (flag)
1332                      (if (listp flag)
1333                          (mapconcat 'identity flag " ")
1334                        flag))
1335                    result " ")
1336       result)))
1337
1338 (defun nnimap-mark-permanent-p (mark &optional group)
1339   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1340   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1341
1342 (defun nnimap-remassoc (key alist)
1343   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1344 The modified LIST is returned.  If the first member
1345 of LIST has a car that is `equal' to KEY, there is no way to remove it
1346 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1347 sure of changing the value of `foo'."
1348   (when alist
1349     (if (equal key (caar alist))
1350         (cdr alist)
1351       (setcdr alist (nnimap-remassoc key (cdr alist)))
1352       alist)))
1353   
1354 (defun nnimap-update-alist-soft (key value alist)
1355   (if value
1356       (cons (cons key value) (nnimap-remassoc key alist))
1357     (nnimap-remassoc key alist)))
1358
1359 (when nnimap-debug
1360   (require 'trace)
1361   (buffer-disable-undo (get-buffer-create nnimap-debug))
1362   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1363         '(
1364           nnimap-possibly-change-server
1365           nnimap-verify-uidvalidity
1366           nnimap-find-minmax-uid
1367           nnimap-before-find-minmax-bugworkaround
1368           nnimap-possibly-change-group
1369           ;;nnimap-replace-whitespace
1370           nnimap-retrieve-headers-progress
1371           nnimap-retrieve-which-headers
1372           nnimap-group-overview-filename
1373           nnimap-retrieve-headers-from-file
1374           nnimap-retrieve-headers-from-server
1375           nnimap-retrieve-headers
1376           nnimap-open-connection
1377           nnimap-open-server
1378           nnimap-server-opened
1379           nnimap-close-server
1380           nnimap-request-close
1381           nnimap-status-message
1382           ;;nnimap-demule
1383           nnimap-request-article-part
1384           nnimap-request-article
1385           nnimap-request-head
1386           nnimap-request-body
1387           nnimap-request-group
1388           nnimap-close-group
1389           nnimap-pattern-to-list-arguments
1390           nnimap-request-list
1391           nnimap-request-post
1392           nnimap-retrieve-groups
1393           nnimap-request-update-info-internal
1394           nnimap-request-type
1395           nnimap-request-set-mark
1396           nnimap-split-to-groups
1397           nnimap-split-find-rule
1398           nnimap-split-find-inbox
1399           nnimap-split-articles
1400           nnimap-request-scan
1401           nnimap-request-newgroups
1402           nnimap-request-create-group
1403           nnimap-time-substract
1404           nnimap-date-days-ago
1405           nnimap-request-expire-articles-progress
1406           nnimap-request-expire-articles
1407           nnimap-request-move-article
1408           nnimap-request-accept-article
1409           nnimap-request-delete-group
1410           nnimap-request-rename-group
1411           gnus-group-nnimap-expunge
1412           gnus-group-nnimap-edit-acl
1413           gnus-group-nnimap-edit-acl-done
1414           nnimap-group-mode-hook
1415           nnimap-mark-to-predicate
1416           nnimap-mark-to-flag-1
1417           nnimap-mark-to-flag
1418           nnimap-mark-permanent-p
1419           nnimap-remassoc
1420           nnimap-update-alist-soft
1421           )))
1422
1423 (provide 'nnimap)
1424
1425 ;;; nnimap.el ends here