2001-09-14 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 1.0")
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                     t ;; for OGnus to see if ignoring uidvalidity
401                     ;; changes has any bad effects.
402                     (yes-or-no-p
403                      (format
404                       "nnimap: Group %s is not uidvalid.  Continue? " group)))
405                 imap-current-mailbox
406               (imap-mailbox-unselect)
407               (error "nnimap: Group %s is not uid-valid" group))
408           (nnheader-report 'nnimap (imap-error-text)))))))
409
410 (defun nnimap-replace-whitespace (string)
411   "Return STRING with all whitespace replaced with space."
412   (when string
413     (while (string-match "[\r\n\t]+" string)
414       (setq string (replace-match " " t t string)))
415     string))
416
417 ;; Required backend functions
418
419 (defun nnimap-retrieve-headers-progress ()
420   "Hook to insert NOV line for current article into `nntp-server-buffer'."
421   (and (numberp nnmail-large-newsgroup)
422        (zerop (% (incf nnimap-counter) nnimap-progress-how-often))
423        (> nnimap-length nnmail-large-newsgroup)
424        (nnheader-message 6 "nnimap: Retrieving headers... %c"
425                          (nth (/ (% nnimap-counter
426                                     (* (length nnimap-progress-chars)
427                                        nnimap-progress-how-often))
428                                  nnimap-progress-how-often)
429                               nnimap-progress-chars)))
430   (with-current-buffer nntp-server-buffer
431     (let (headers lines chars uid mbx)
432       (with-current-buffer nnimap-server-buffer
433         (setq uid imap-current-message
434               mbx imap-current-mailbox
435               headers (nnimap-demule
436                        (if (imap-capability 'IMAP4rev1)
437                       ;; xxx don't just use car? alist doesn't contain
438                            ;; anything else now, but it might...
439                            (nth 2 (car (imap-message-get uid 'BODYDETAIL)))
440                          (imap-message-get uid 'RFC822.HEADER)))
441               lines (imap-body-lines (imap-message-body imap-current-message))
442               chars (imap-message-get imap-current-message 'RFC822.SIZE)))
443       (nnheader-insert-nov
444        (with-temp-buffer
445          (buffer-disable-undo)
446          (insert headers)
447          (nnheader-ms-strip-cr)
448          (nnheader-fold-continuation-lines)
449          (subst-char-in-region (point-min) (point-max) ?\t ? )
450          (let ((head (nnheader-parse-head 'naked)))
451            (mail-header-set-number head uid)
452            (mail-header-set-chars head chars)
453            (mail-header-set-lines head lines)
454            (mail-header-set-xref
455             head (format "%s %s:%d" (system-name) mbx uid))
456            head))))))
457
458 (defun nnimap-retrieve-which-headers (articles fetch-old)
459   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
460   (with-current-buffer nnimap-server-buffer
461     (if (numberp (car-safe articles))
462         (imap-search
463          (concat "UID "
464                  (imap-range-to-message-set
465                   (gnus-compress-sequence
466                    (append (gnus-uncompress-sequence
467                             (and fetch-old
468                                  (cons (if (numberp fetch-old)
469                                            (max 1 (- (car articles) fetch-old))
470                                          1)
471                                        (1- (car articles)))))
472                            articles)))))
473       (mapcar (lambda (msgid)
474                 (imap-search
475                  (format "HEADER Message-Id \"%s\"" msgid)))
476               articles))))
477
478 (defun nnimap-group-overview-filename (group server)
479   "Make pathname for GROUP on SERVER."
480   (let* ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
481          (uidvalidity (gnus-group-get-parameter
482                        (gnus-group-prefixed-name
483                         group (gnus-server-to-method
484                                (format "nnimap:%s" server)))
485                        'uidvalidity))
486          (name (nnheader-translate-file-chars
487                 (concat nnimap-nov-file-name
488                         (if (equal server "")
489                             "unnamed"
490                           server) "." group nnimap-nov-file-name-suffix) t))
491          (nameuid (nnheader-translate-file-chars
492                    (concat nnimap-nov-file-name
493                            (if (equal server "")
494                                "unnamed"
495                              server) "." group "." uidvalidity
496                            nnimap-nov-file-name-suffix) t))
497          (oldfile (if (or nnmail-use-long-file-names
498                           (file-exists-p (expand-file-name name dir)))
499                       (expand-file-name name dir)
500                     (expand-file-name
501                      (mm-encode-coding-string
502                       (nnheader-replace-chars-in-string name ?. ?/)
503                       nnmail-pathname-coding-system)
504                      dir)))
505          (newfile (if (or nnmail-use-long-file-names
506                           (file-exists-p (expand-file-name nameuid dir)))
507                       (expand-file-name nameuid dir)
508                     (expand-file-name
509                      (mm-encode-coding-string
510                       (nnheader-replace-chars-in-string nameuid ?. ?/)
511                       nnmail-pathname-coding-system)
512                      dir))))
513     (when (and (file-exists-p oldfile) (not (file-exists-p newfile)))
514       (message "nnimap: Upgrading novcache filename...")
515       (sit-for 1)
516       (gnus-make-directory (file-name-directory newfile))
517       (unless (ignore-errors (rename-file oldfile newfile) t)
518         (if (ignore-errors (copy-file oldfile newfile) t)
519             (delete-file oldfile)
520           (error "Can't rename `%s' to `%s'" oldfile newfile))))
521     newfile))
522
523 (defun nnimap-retrieve-headers-from-file (group server)
524   (with-current-buffer nntp-server-buffer
525     (let ((nov (nnimap-group-overview-filename group server)))
526       (when (file-exists-p nov)
527         (mm-insert-file-contents nov)
528         (set-buffer-modified-p nil)
529         (let ((min (ignore-errors (goto-char (point-min))
530                                   (read (current-buffer))))
531               (max (ignore-errors (goto-char (point-max))
532                                   (forward-line -1)
533                                   (read (current-buffer)))))
534           (if (and (numberp min) (numberp max))
535               (cons min max)
536             ;; junk, remove it, it's saved later
537             (erase-buffer)
538             nil))))))
539
540 (defun nnimap-retrieve-headers-from-server (articles group server)
541   (with-current-buffer nnimap-server-buffer
542     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
543           (nnimap-length (gnus-range-length articles))
544           (nnimap-counter 0))
545       (imap-fetch (imap-range-to-message-set articles)
546                   (concat "(UID RFC822.SIZE BODY "
547                           (let ((headers
548                                  (append '(Subject From Date Message-Id
549                                                    References In-Reply-To Xref)
550                                          (copy-sequence
551                                           nnmail-extra-headers))))
552                             (if (imap-capability 'IMAP4rev1)
553                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
554                               (format "RFC822.HEADER.LINES %s)" headers)))))
555       (and (numberp nnmail-large-newsgroup)
556            (> nnimap-length nnmail-large-newsgroup)
557            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
558
559 (defun nnimap-dont-use-nov-p (group server)
560   (or gnus-nov-is-evil nnimap-nov-is-evil
561       (unless (and (gnus-make-directory
562                     (file-name-directory
563                      (nnimap-group-overview-filename group server)))
564                    (file-writable-p
565                     (nnimap-group-overview-filename group server)))
566         (message "nnimap: Nov cache not writable, %s"
567                  (nnimap-group-overview-filename group server)))))
568
569 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
570   (when (nnimap-possibly-change-group group server)
571     (with-current-buffer nntp-server-buffer
572       (erase-buffer)
573       (if (nnimap-dont-use-nov-p group server)
574           (nnimap-retrieve-headers-from-server
575            (gnus-compress-sequence articles) group server)
576         (let (uids cached low high)
577           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
578                       low (car uids)
579                       high (car (last uids)))
580             (if (setq cached (nnimap-retrieve-headers-from-file group server))
581                 (progn
582                   ;; fetch articles with uids before cache block
583                   (when (< low (car cached))
584                     (goto-char (point-min))
585                     (nnimap-retrieve-headers-from-server
586                      (cons low (1- (car cached))) group server))
587                   ;; fetch articles with uids after cache block
588                   (when (> high (cdr cached))
589                     (goto-char (point-max))
590                     (nnimap-retrieve-headers-from-server
591                      (cons (1+ (cdr cached)) high) group server))
592                   (when nnimap-prune-cache
593               ;; remove nov's for articles which has expired on server
594                     (goto-char (point-min))
595                     (dolist (uid (gnus-set-difference articles uids))
596                       (when (re-search-forward (format "^%d\t" uid) nil t)
597                         (gnus-delete-line)))))
598               ;; nothing cached, fetch whole range from server
599               (nnimap-retrieve-headers-from-server
600                (cons low high) group server))
601             (when (buffer-modified-p)
602               (nnmail-write-region
603                1 (point-max) (nnimap-group-overview-filename group server)
604                nil 'nomesg))
605             (nnheader-nov-delete-outside-range low high))))
606       'nov)))
607
608 (defun nnimap-open-connection (server)
609   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
610                       nnimap-authenticator nnimap-server-buffer))
611       (nnheader-report 'nnimap "Can't open connection to server %s" server)
612     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
613                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
614       (imap-close nnimap-server-buffer)
615       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
616     (let* ((list (gnus-parse-netrc nnimap-authinfo-file))
617            (port (if nnimap-server-port
618                      (int-to-string nnimap-server-port)
619                    "imap"))
620            (alist (gnus-netrc-machine list (or nnimap-server-address
621                                                nnimap-address server)
622                                       port "imap"))
623            (user (gnus-netrc-get alist "login"))
624            (passwd (gnus-netrc-get alist "password")))
625       (if (imap-authenticate user passwd nnimap-server-buffer)
626           (prog1
627               (push (list server nnimap-server-buffer)
628                     nnimap-server-buffer-alist)
629             (nnimap-possibly-change-server server))
630         (imap-close nnimap-server-buffer)
631         (kill-buffer nnimap-server-buffer)
632         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
633
634 (deffoo nnimap-open-server (server &optional defs)
635   (nnheader-init-server-buffer)
636   (if (nnimap-server-opened server)
637       t
638     (unless (assq 'nnimap-server-buffer defs)
639       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
640     ;; translate `nnimap-server-address' to `nnimap-address' in defs
641     ;; for people that configured nnimap with a very old version
642     (unless (assq 'nnimap-address defs)
643       (if (assq 'nnimap-server-address defs)
644           (push (list 'nnimap-address
645                       (cadr (assq 'nnimap-server-address defs))) defs)
646         (push (list 'nnimap-address server) defs)))
647     (nnoo-change-server 'nnimap server defs)
648     (or nnimap-server-buffer
649         (setq nnimap-server-buffer (cadr (assq 'nnimap-server-buffer defs))))
650     (with-current-buffer (get-buffer-create nnimap-server-buffer)
651       (nnoo-change-server 'nnimap server defs))
652     (or (and nnimap-server-buffer
653              (imap-opened nnimap-server-buffer))
654         (nnimap-open-connection server))))
655
656 (deffoo nnimap-server-opened (&optional server)
657   "Whether SERVER is opened.
658 If SERVER is the current virtual server, and the connection to the
659 physical server is alive, this function return a non-nil value.  If
660 SERVER is nil, it is treated as the current server."
661   ;; clean up autologouts??
662   (and (or server nnimap-current-server)
663        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
664        (imap-opened (nnimap-get-server-buffer server))))
665
666 (deffoo nnimap-close-server (&optional server)
667   "Close connection to server and free all resources connected to it.
668 Return nil if the server couldn't be closed for some reason."
669   (let ((server (or server nnimap-current-server)))
670     (when (or (nnimap-server-opened server)
671               (imap-opened (nnimap-get-server-buffer server)))
672       (imap-close (nnimap-get-server-buffer server))
673       (kill-buffer (nnimap-get-server-buffer server))
674       (setq nnimap-server-buffer nil
675             nnimap-current-server nil
676             nnimap-server-buffer-alist
677             (delq server nnimap-server-buffer-alist)))
678     (nnoo-close-server 'nnimap server)))
679
680 (deffoo nnimap-request-close ()
681   "Close connection to all servers and free all resources that the backend have reserved.
682 All buffers that have been created by that
683 backend should be killed.  (Not the nntp-server-buffer, though.) This
684 function is generally only called when Gnus is shutting down."
685   (mapcar (lambda (server) (nnimap-close-server (car server)))
686           nnimap-server-buffer-alist)
687   (setq nnimap-server-buffer-alist nil))
688
689 (deffoo nnimap-status-message (&optional server)
690   "This function returns the last error message from server."
691   (when (nnimap-possibly-change-server server)
692     (nnoo-status-message 'nnimap server)))
693
694 (defun nnimap-demule (string)
695   (funcall (if (and (fboundp 'string-as-multibyte)
696                     (subrp (symbol-function 'string-as-multibyte)))
697                'string-as-multibyte
698              'identity)
699            (or string "")))
700
701 (defun nnimap-callback ()
702   (remove-hook 'imap-fetch-data-hook 'nnimap-callback)
703   (with-current-buffer nnimap-callback-buffer
704     (insert
705      (with-current-buffer nnimap-server-buffer
706        (nnimap-demule
707         (if (imap-capability 'IMAP4rev1)
708             ;; xxx don't just use car? alist doesn't contain
709             ;; anything else now, but it might...
710             (nth 2 (car (imap-message-get (imap-current-message) 'BODYDETAIL)))
711           (imap-message-get (imap-current-message) 'RFC822)))))
712     (nnheader-ms-strip-cr)
713     (funcall nnimap-callback-callback-function t)))
714
715 (defun nnimap-request-article-part (article part prop &optional
716                                             group server to-buffer detail)
717   (when (nnimap-possibly-change-group group server)
718     (let ((article (if (stringp article)
719                        (car-safe (imap-search
720                                   (format "HEADER Message-Id \"%s\"" article)
721                                   nnimap-server-buffer))
722                      article)))
723       (when article
724         (gnus-message 10 "nnimap: Fetching (part of) article %d..." article)
725         (if (not nnheader-callback-function)
726             (with-current-buffer (or to-buffer nntp-server-buffer)
727               (erase-buffer)
728               (let ((data (imap-fetch article part prop nil
729                                       nnimap-server-buffer)))
730                 (insert (nnimap-demule (if detail
731                                            (nth 2 (car data))
732                                          data))))
733               (nnheader-ms-strip-cr)
734               (gnus-message 10 "nnimap: Fetching (part of) article %d...done"
735                             article)
736               (if (bobp)
737                   (nnheader-report 'nnimap "No such article: %s"
738                                    (imap-error-text nnimap-server-buffer))
739                 (cons group article)))
740           (add-hook 'imap-fetch-data-hook 'nnimap-callback)
741           (setq nnimap-callback-callback-function nnheader-callback-function
742                 nnimap-callback-buffer nntp-server-buffer)
743           (imap-fetch-asynch article part nil nnimap-server-buffer)
744           (cons group article))))))
745
746 (deffoo nnimap-asynchronous-p ()
747   t)
748
749 (deffoo nnimap-request-article (article &optional group server to-buffer)
750   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
751       (nnimap-request-article-part
752        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
753     (nnimap-request-article-part
754      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
755
756 (deffoo nnimap-request-head (article &optional group server to-buffer)
757   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
758       (nnimap-request-article-part
759        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
760     (nnimap-request-article-part
761      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
762
763 (deffoo nnimap-request-body (article &optional group server to-buffer)
764   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
765       (nnimap-request-article-part
766        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
767     (nnimap-request-article-part
768      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
769
770 (deffoo nnimap-request-group (group &optional server fast)
771   (nnimap-request-update-info-internal
772    group
773    (gnus-get-info (gnus-group-prefixed-name
774                    group (gnus-server-to-method (format "nnimap:%s" server))))
775    server)
776   (when (nnimap-possibly-change-group group server)
777     (nnimap-before-find-minmax-bugworkaround)
778     (let (info)
779       (cond (fast group)
780             ((null (setq info (nnimap-find-minmax-uid group t)))
781              (nnheader-report 'nnimap "Could not get active info for %s"
782                               group))
783             (t
784              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
785                               (max 1 (or (nth 1 info) 1))
786                               (or (nth 2 info) 0) group)
787              (nnheader-report 'nnimap "Group %s selected" group)
788              t)))))
789
790 (defun nnimap-close-group (group &optional server)
791   (with-current-buffer nnimap-server-buffer
792     (when (and (imap-opened)
793                (nnimap-possibly-change-group group server))
794       (case nnimap-expunge-on-close
795         ('always (imap-mailbox-expunge)
796                  (imap-mailbox-close))
797         ('ask (if (and (imap-search "DELETED")
798                        (gnus-y-or-n-p (format
799                                        "Expunge articles in group `%s'? "
800                                        imap-current-mailbox)))
801                   (progn (imap-mailbox-expunge)
802                          (imap-mailbox-close))
803                 (imap-mailbox-unselect)))
804         (t (imap-mailbox-unselect)))
805       (not imap-current-mailbox))))
806
807 (defun nnimap-pattern-to-list-arguments (pattern)
808   (mapcar (lambda (p)
809             (cons (car-safe p) (or (cdr-safe p) p)))
810           (if (and (listp pattern)
811                    (listp (cdr pattern)))
812               pattern
813             (list pattern))))
814
815 (deffoo nnimap-request-list (&optional server)
816   (when (nnimap-possibly-change-server server)
817     (with-current-buffer nntp-server-buffer
818       (erase-buffer))
819     (gnus-message 5 "nnimap: Generating active list%s..."
820                   (if (> (length server) 0) (concat " for " server) ""))
821     (nnimap-before-find-minmax-bugworkaround)
822     (with-current-buffer nnimap-server-buffer
823       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
824         (dolist (mbx (funcall nnimap-request-list-method
825                               (cdr pattern) (car pattern)))
826           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
827               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
828                 (when info
829                   (with-current-buffer nntp-server-buffer
830                     (insert (format "\"%s\" %d %d y\n"
831                                     mbx (or (nth 2 info) 0)
832                                     (max 1 (or (nth 1 info) 1)))))))))))
833     (gnus-message 5 "nnimap: Generating active list%s...done"
834                   (if (> (length server) 0) (concat " for " server) ""))
835     t))
836
837 (deffoo nnimap-request-post (&optional server)
838   (let ((success t))
839     (dolist (mbx (message-unquote-tokens
840                   (message-tokenize-header
841                    (message-fetch-field "Newsgroups") ", ")) success)
842       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
843         (or (gnus-active to-newsgroup)
844             (gnus-activate-group to-newsgroup)
845             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
846                                        to-newsgroup))
847                 (or (and (gnus-request-create-group
848                           to-newsgroup gnus-command-method)
849                          (gnus-activate-group to-newsgroup nil nil
850                                               gnus-command-method))
851                     (error "Couldn't create group %s" to-newsgroup)))
852             (error "No such group: %s" to-newsgroup))
853         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
854           (setq success nil))))))
855
856 ;; Optional backend functions
857
858 (deffoo nnimap-retrieve-groups (groups &optional server)
859   (when (nnimap-possibly-change-server server)
860     (gnus-message 5 "nnimap: Checking mailboxes...")
861     (with-current-buffer nntp-server-buffer
862       (erase-buffer)
863       (nnimap-before-find-minmax-bugworkaround)
864       (dolist (group groups)
865         (gnus-message 7 "nnimap: Checking mailbox %s" group)
866         (or (member "\\NoSelect"
867                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
868             (let ((info (nnimap-find-minmax-uid group 'examine)))
869               (when (> (or (imap-mailbox-get 'recent group 
870                                              nnimap-server-buffer) 0)
871                        0)
872                 (push (list (cons group 0)) nnmail-split-history))
873               (insert (format "\"%s\" %d %d y\n" group
874                               (or (nth 2 info) 0)
875                               (max 1 (or (nth 1 info) 1))))))))
876     (gnus-message 5 "nnimap: Checking mailboxes...done")
877     'active))
878
879 (deffoo nnimap-request-update-info-internal (group info &optional server)
880   (when (nnimap-possibly-change-group group server)
881     (when info ;; xxx what does this mean? should we create a info?
882       (with-current-buffer nnimap-server-buffer
883         (gnus-message 5 "nnimap: Updating info for %s..."
884                       (gnus-info-group info))
885
886         (when (nnimap-mark-permanent-p 'read)
887           (let (seen unseen)
888             ;; read info could contain articles marked unread by other
889             ;; imap clients!  we correct this
890             (setq seen (gnus-uncompress-range (gnus-info-read info))
891                   unseen (imap-search "UNSEEN UNDELETED")
892                   seen (gnus-set-difference seen unseen)
893                   ;; seen might lack articles marked as read by other
894                   ;; imap clients! we correct this
895                   seen (append seen (imap-search "SEEN"))
896                   ;; remove dupes
897                   seen (sort seen '<)
898                   seen (gnus-compress-sequence seen t)
899           ;; we can't return '(1) since this isn't a "list of ranges",
900          ;; and we can't return '((1)) since g-list-of-unread-articles
901                   ;; is buggy so we return '((1 . 1)).
902                   seen (if (and (integerp (car seen))
903                                 (null (cdr seen)))
904                            (list (cons (car seen) (car seen)))
905                          seen))
906             (gnus-info-set-read info seen)))
907
908         (mapcar (lambda (pred)
909                   (when (or (eq (cdr pred) 'recent)
910                             (and (nnimap-mark-permanent-p (cdr pred))
911                                  (member (nnimap-mark-to-flag (cdr pred))
912                                          (imap-mailbox-get 'flags))))
913                     (gnus-info-set-marks
914                      info
915                      (gnus-update-alist-soft
916                       (cdr pred)
917                       (gnus-compress-sequence
918                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
919                       (gnus-info-marks info))
920                      t)))
921                 gnus-article-mark-lists)
922
923         (when nnimap-importantize-dormant
924       ;; nnimap mark dormant article as ticked too (for other clients)
925           ;; so we remove that mark for gnus since we support dormant
926           (gnus-info-set-marks
927            info
928            (gnus-update-alist-soft
929             'tick
930             (gnus-remove-from-range
931              (cdr-safe (assoc 'tick (gnus-info-marks info)))
932              (cdr-safe (assoc 'dormant (gnus-info-marks info))))
933             (gnus-info-marks info))
934            t))
935
936         (gnus-message 5 "nnimap: Updating info for %s...done"
937                       (gnus-info-group info))
938
939         info))))
940
941 (deffoo nnimap-request-type (group &optional article)
942   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
943       'news
944     'mail))
945
946 (deffoo nnimap-request-set-mark (group actions &optional server)
947   (when (nnimap-possibly-change-group group server)
948     (with-current-buffer nnimap-server-buffer
949       (let (action)
950         (gnus-message 7 "nnimap: Setting marks in %s..." group)
951         (while (setq action (pop actions))
952           (let ((range (nth 0 action))
953                 (what  (nth 1 action))
954                 (cmdmarks (nth 2 action))
955                 marks)
956             ;; bookmark can't be stored (not list/range
957             (setq cmdmarks (delq 'bookmark cmdmarks))
958             ;; killed can't be stored (not list/range
959             (setq cmdmarks (delq 'killed cmdmarks))
960             ;; unsent are for nndraft groups only
961             (setq cmdmarks (delq 'unsent cmdmarks))
962             ;; cache flags are pointless on the server
963             (setq cmdmarks (delq 'cache cmdmarks))
964             ;; seen flags are local to each gnus
965             (setq cmdmarks (delq 'seen cmdmarks))
966             ;; recent marks can't be set
967             (setq cmdmarks (delq 'recent cmdmarks))
968             (when nnimap-importantize-dormant
969               ;; flag dormant articles as ticked
970               (if (memq 'dormant cmdmarks)
971                   (setq cmdmarks (cons 'tick cmdmarks))))
972             ;; remove stuff we are forbidden to store
973             (mapcar (lambda (mark)
974                       (if (imap-message-flag-permanent-p
975                            (nnimap-mark-to-flag mark))
976                           (setq marks (cons mark marks))))
977                     cmdmarks)
978             (when (and range marks)
979               (cond ((eq what 'del)
980                      (imap-message-flags-del
981                       (imap-range-to-message-set range)
982                       (nnimap-mark-to-flag marks nil t)))
983                     ((eq what 'add)
984                      (imap-message-flags-add
985                       (imap-range-to-message-set range)
986                       (nnimap-mark-to-flag marks nil t)))
987                     ((eq what 'set)
988                      (imap-message-flags-set
989                       (imap-range-to-message-set range)
990                       (nnimap-mark-to-flag marks nil t)))))))
991         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
992   nil)
993
994 (defun nnimap-split-fancy ()
995   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
996   (let ((nnmail-split-fancy nnimap-split-fancy))
997     (nnmail-split-fancy)))
998
999 (defun nnimap-split-to-groups (rules)
1000   ;; tries to match all rules in nnimap-split-rule against content of
1001   ;; nntp-server-buffer, returns a list of groups that matched.
1002   (with-current-buffer nntp-server-buffer
1003     ;; Fold continuation lines.
1004     (goto-char (point-min))
1005     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1006       (replace-match " " t t))
1007     (if (functionp rules)
1008         (funcall rules)
1009       (let (to-groups regrepp)
1010         (catch 'split-done
1011           (dolist (rule rules to-groups)
1012             (let ((group (car rule))
1013                   (regexp (cadr rule)))
1014               (goto-char (point-min))
1015               (when (and (if (stringp regexp)
1016                              (progn
1017                                (setq regrepp (string-match "\\\\[0-9&]" group))
1018                                (re-search-forward regexp nil t))
1019                            (funcall regexp group))
1020                  ;; Don't enter the article into the same group twice.
1021                          (not (assoc group to-groups)))
1022                 (push (if regrepp
1023                           (nnmail-expand-newtext group)
1024                         group)
1025                       to-groups)
1026                 (or nnimap-split-crosspost
1027                     (throw 'split-done to-groups))))))))))
1028
1029 (defun nnimap-assoc-match (key alist)
1030   (let (element)
1031     (while (and alist (not element))
1032       (if (string-match (car (car alist)) key)
1033           (setq element (car alist)))
1034       (setq alist (cdr alist)))
1035     element))
1036
1037 (defun nnimap-split-find-rule (server inbox)
1038   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
1039            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
1040       ;; extended format
1041       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match
1042                                             server nnimap-split-rule))))
1043     nnimap-split-rule))
1044
1045 (defun nnimap-split-find-inbox (server)
1046   (if (listp nnimap-split-inbox)
1047       nnimap-split-inbox
1048     (list nnimap-split-inbox)))
1049
1050 (defun nnimap-split-articles (&optional group server)
1051   (when (nnimap-possibly-change-server server)
1052     (with-current-buffer nnimap-server-buffer
1053       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
1054         ;; iterate over inboxes
1055         (while (and (setq inbox (pop inboxes))
1056                     (nnimap-possibly-change-group inbox)) ;; SELECT
1057           ;; find split rule for this server / inbox
1058           (when (setq rule (nnimap-split-find-rule server inbox))
1059             ;; iterate over articles
1060             (dolist (article (imap-search nnimap-split-predicate))
1061               (when (nnimap-request-head article)
1062                 ;; copy article to right group(s)
1063                 (setq removeorig nil)
1064                 (dolist (to-group (nnimap-split-to-groups rule))
1065                   (cond ((eq to-group 'junk)
1066                          (message "IMAP split removed %s:%s:%d" server inbox
1067                                   article)
1068                          (setq removeorig t))
1069                         ((imap-message-copy (number-to-string article)
1070                                             to-group nil 'nocopyuid)
1071                          (message "IMAP split moved %s:%s:%d to %s" server
1072                                   inbox article to-group)
1073                          (setq removeorig t)
1074                         ;; Add the group-art list to the history list.
1075                          (push (list (cons to-group 0)) nnmail-split-history))
1076                         (t
1077                          (message "IMAP split failed to move %s:%s:%d to %s"
1078                                   server inbox article to-group))))
1079              ;; remove article if it was successfully copied somewhere
1080                 (and removeorig
1081                      (imap-message-flags-add (format "%d" article)
1082                                              "\\Seen \\Deleted")))))
1083           (when (imap-mailbox-select inbox) ;; just in case
1084        ;; todo: UID EXPUNGE (if available) to remove splitted articles
1085             (imap-mailbox-expunge)
1086             (imap-mailbox-close)))
1087         t))))
1088
1089 (deffoo nnimap-request-scan (&optional group server)
1090   (nnimap-split-articles group server))
1091
1092 (deffoo nnimap-request-newgroups (date &optional server)
1093   (when (nnimap-possibly-change-server server)
1094     (with-current-buffer nntp-server-buffer
1095       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
1096                     (if (> (length server) 0) " on " "") server)
1097       (erase-buffer)
1098       (nnimap-before-find-minmax-bugworkaround)
1099       (dolist (pattern (nnimap-pattern-to-list-arguments
1100                         nnimap-list-pattern))
1101         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil
1102                                         nnimap-server-buffer))
1103           (or (catch 'found
1104                 (dolist (mailbox (imap-mailbox-get 'list-flags mbx
1105                                                    nnimap-server-buffer))
1106                   (if (string= (downcase mailbox) "\\noselect")
1107                       (throw 'found t)))
1108                 nil)
1109               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
1110                 (when info
1111                   (insert (format "\"%s\" %d %d y\n"
1112                                   mbx (or (nth 2 info) 0)
1113                                   (max 1 (or (nth 1 info) 1)))))))))
1114       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1115                     (if (> (length server) 0) " on " "") server))
1116     t))
1117
1118 (deffoo nnimap-request-create-group (group &optional server args)
1119   (when (nnimap-possibly-change-server server)
1120     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1121         (imap-mailbox-create group nnimap-server-buffer))))
1122
1123 (defun nnimap-time-substract (time1 time2)
1124   "Return TIME for TIME1 - TIME2."
1125   (let* ((ms (- (car time1) (car time2)))
1126          (ls (- (nth 1 time1) (nth 1 time2))))
1127     (if (< ls 0)
1128         (list (- ms 1) (+ (expt 2 16) ls))
1129       (list ms ls))))
1130
1131 (defun nnimap-date-days-ago (daysago)
1132   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1133   (let* ((time (nnimap-time-substract (current-time) (days-to-time daysago)))
1134          (date (format-time-string
1135                 (format "%%d-%s-%%Y"
1136                         (capitalize (car (rassoc (nth 4 (decode-time time))
1137                                                  parse-time-months))))
1138                 time)))
1139     (if (eq ?0 (string-to-char date))
1140         (substring date 1)
1141       date)))
1142
1143 (defun nnimap-request-expire-articles-progress ()
1144   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1145                 imap-current-message))
1146
1147
1148 (defun nnimap-expiry-target (arts group server)
1149   (unless (eq nnmail-expiry-target 'delete)
1150     (with-current-buffer nntp-server-buffer
1151       (dolist (art (gnus-uncompress-sequence arts))
1152         (nnimap-request-article art group server)
1153         ;; hints for optimization in `nnimap-request-accept-article'
1154         (let ((nnimap-current-move-article art)
1155               (nnimap-current-move-group group)
1156               (nnimap-current-move-server server))
1157           (nnmail-expiry-target-group nnmail-expiry-target group))))))
1158
1159 ;; Notice that we don't actually delete anything, we just mark them deleted.
1160 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1161   (let ((artseq (gnus-compress-sequence articles)))
1162     (when (and artseq (nnimap-possibly-change-group group server))
1163       (with-current-buffer nnimap-server-buffer
1164         (if force
1165             (progn
1166               (nnimap-expiry-target artseq group server)
1167               (when (imap-message-flags-add (imap-range-to-message-set artseq)
1168                                             "\\Deleted")
1169                 (setq articles nil)))
1170           (let ((days (or (and nnmail-expiry-wait-function
1171                                (funcall nnmail-expiry-wait-function group))
1172                           nnmail-expiry-wait)))
1173             (cond ((eq days 'immediate)
1174                    (nnimap-expiry-target artseq group server)
1175                    (when (imap-message-flags-add
1176                           (imap-range-to-message-set artseq) "\\Deleted")
1177                      (setq articles nil)))
1178                   ((numberp days)
1179                    (let ((oldarts (imap-search
1180                                    (format nnimap-expunge-search-string
1181                                            (imap-range-to-message-set artseq)
1182                                            (nnimap-date-days-ago days))))
1183                          (imap-fetch-data-hook
1184                           '(nnimap-request-expire-articles-progress)))
1185                      (nnimap-expiry-target oldarts group server)
1186                      (and oldarts
1187                           (imap-message-flags-add
1188                            (imap-range-to-message-set
1189                             (gnus-compress-sequence oldarts))
1190                            "\\Deleted")
1191                           (setq articles (gnus-set-difference
1192                                           articles oldarts)))))))))))
1193   ;; return articles not deleted
1194   articles)
1195
1196 (deffoo nnimap-request-move-article (article group server
1197                                              accept-form &optional last)
1198   (when (nnimap-possibly-change-server server)
1199     (save-excursion
1200       (let ((buf (get-buffer-create " *nnimap move*"))
1201             (nnimap-current-move-article article)
1202             (nnimap-current-move-group group)
1203             (nnimap-current-move-server nnimap-current-server)
1204             result)
1205         (and (nnimap-request-article article group server)
1206              (save-excursion
1207                (set-buffer buf)
1208                (buffer-disable-undo (current-buffer))
1209                (insert-buffer-substring nntp-server-buffer)
1210                (setq result (eval accept-form))
1211                (kill-buffer buf)
1212                result)
1213              (nnimap-request-expire-articles (list article) group server t))
1214         result))))
1215
1216 (deffoo nnimap-request-accept-article (group &optional server last)
1217   (when (nnimap-possibly-change-server server)
1218     (let (uid)
1219       (if (setq uid
1220                 (if (string= nnimap-current-server nnimap-current-move-server)
1221                   ;; moving article within same server, speed it up...
1222                     (and (nnimap-possibly-change-group
1223                           nnimap-current-move-group)
1224                          (imap-message-copy (number-to-string
1225                                              nnimap-current-move-article)
1226                                             group 'dontcreate nil
1227                                             nnimap-server-buffer))
1228                   (with-current-buffer (current-buffer)
1229                     (goto-char (point-min))
1230                   ;; remove any 'From blabla' lines, some IMAP servers
1231                     ;; reject the entire message otherwise.
1232                     (when (looking-at "^From[^:]")
1233                       (kill-region (point) (progn (forward-line) (point))))
1234                     ;; turn into rfc822 format (\r\n eol's)
1235                     (while (search-forward "\n" nil t)
1236                       (replace-match "\r\n")))
1237                   ;; this 'or' is for Cyrus server bug
1238                   (or (null (imap-current-mailbox nnimap-server-buffer))
1239                       (imap-mailbox-unselect nnimap-server-buffer))
1240                   (imap-message-append group (current-buffer) nil nil
1241                                        nnimap-server-buffer)))
1242           (cons group (nth 1 uid))
1243         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1244
1245 (deffoo nnimap-request-delete-group (group force &optional server)
1246   (when (nnimap-possibly-change-server server)
1247     (with-current-buffer nnimap-server-buffer
1248       (if force
1249           (or (null (imap-mailbox-status group 'uidvalidity))
1250               (imap-mailbox-delete group))
1251         ;; UNSUBSCRIBE?
1252         t))))
1253
1254 (deffoo nnimap-request-rename-group (group new-name &optional server)
1255   (when (nnimap-possibly-change-server server)
1256     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1257
1258 (defun nnimap-expunge (mailbox server)
1259   (when (nnimap-possibly-change-group mailbox server)
1260     (imap-mailbox-expunge nnimap-server-buffer)))
1261
1262 (defun nnimap-acl-get (mailbox server)
1263   (when (nnimap-possibly-change-server server)
1264     (and (imap-capability 'ACL nnimap-server-buffer)
1265          (imap-mailbox-acl-get mailbox nnimap-server-buffer))))
1266
1267 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1268   (when (nnimap-possibly-change-server (cadr method))
1269     (unless (imap-capability 'ACL nnimap-server-buffer)
1270       (error "Your server does not support ACL editing"))
1271     (with-current-buffer nnimap-server-buffer
1272       ;; delete all removed identifiers
1273       (mapcar (lambda (old-acl)
1274                 (unless (assoc (car old-acl) new-acls)
1275                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1276                       (error "Can't delete ACL for %s" (car old-acl)))))
1277               old-acls)
1278       ;; set all changed acl's
1279       (mapcar (lambda (new-acl)
1280                 (let ((new-rights (cdr new-acl))
1281                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1282                   (unless (and old-rights new-rights
1283                                (string= old-rights new-rights))
1284                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1285                         (error "Can't set ACL for %s to %s" (car new-acl)
1286                                new-rights)))))
1287               new-acls)
1288       t)))
1289
1290 \f
1291 ;;; Internal functions
1292
1293 ;;
1294 ;; This is confusing.
1295 ;;
1296 ;; mark      => read, tick, draft, reply etc
1297 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1298 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1299 ;;
1300 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1301 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1302 ;;
1303
1304 (defconst nnimap-mark-to-predicate-alist
1305   (mapcar
1306    (lambda (pair)                       ; cdr is the mark
1307      (or (assoc (cdr pair)
1308                 '((read . "SEEN")
1309                   (tick . "FLAGGED")
1310                   (draft . "DRAFT")
1311                   (recent . "RECENT")
1312                   (reply . "ANSWERED")))
1313          (cons (cdr pair)
1314                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1315    (cons '(read . read) gnus-article-mark-lists)))
1316
1317 (defun nnimap-mark-to-predicate (pred)
1318   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1319 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1320 to be used within a IMAP SEARCH query."
1321   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1322
1323 (defconst nnimap-mark-to-flag-alist
1324   (mapcar
1325    (lambda (pair)
1326      (or (assoc (cdr pair)
1327                 '((read . "\\Seen")
1328                   (tick . "\\Flagged")
1329                   (draft . "\\Draft")
1330                   (recent . "\\Recent")
1331                   (reply . "\\Answered")))
1332          (cons (cdr pair)
1333                (format "gnus-%s" (symbol-name (cdr pair))))))
1334    (cons '(read . read) gnus-article-mark-lists)))
1335
1336 (defun nnimap-mark-to-flag-1 (preds)
1337   (if (and (not (null preds)) (listp preds))
1338       (cons (nnimap-mark-to-flag (car preds))
1339             (nnimap-mark-to-flag (cdr preds)))
1340     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1341
1342 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1343   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1344 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1345 be used in a STORE FLAGS command."
1346   (let ((result (nnimap-mark-to-flag-1 preds)))
1347     (setq result (if (and (or make-string always-list)
1348                           (not (listp result)))
1349                      (list result)
1350                    result))
1351     (if make-string
1352         (mapconcat (lambda (flag)
1353                      (if (listp flag)
1354                          (mapconcat 'identity flag " ")
1355                        flag))
1356                    result " ")
1357       result)))
1358
1359 (defun nnimap-mark-permanent-p (mark &optional group)
1360   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1361   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1362
1363 (when nnimap-debug
1364   (require 'trace)
1365   (buffer-disable-undo (get-buffer-create nnimap-debug))
1366   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1367           '(
1368             nnimap-possibly-change-server
1369             nnimap-verify-uidvalidity
1370             nnimap-find-minmax-uid
1371             nnimap-before-find-minmax-bugworkaround
1372             nnimap-possibly-change-group
1373             ;;nnimap-replace-whitespace
1374             nnimap-retrieve-headers-progress
1375             nnimap-retrieve-which-headers
1376             nnimap-group-overview-filename
1377             nnimap-retrieve-headers-from-file
1378             nnimap-retrieve-headers-from-server
1379             nnimap-retrieve-headers
1380             nnimap-open-connection
1381             nnimap-open-server
1382             nnimap-server-opened
1383             nnimap-close-server
1384             nnimap-request-close
1385             nnimap-status-message
1386             ;;nnimap-demule
1387             nnimap-request-article-part
1388             nnimap-request-article
1389             nnimap-request-head
1390             nnimap-request-body
1391             nnimap-request-group
1392             nnimap-close-group
1393             nnimap-pattern-to-list-arguments
1394             nnimap-request-list
1395             nnimap-request-post
1396             nnimap-retrieve-groups
1397             nnimap-request-update-info-internal
1398             nnimap-request-type
1399             nnimap-request-set-mark
1400             nnimap-split-to-groups
1401             nnimap-split-find-rule
1402             nnimap-split-find-inbox
1403             nnimap-split-articles
1404             nnimap-request-scan
1405             nnimap-request-newgroups
1406             nnimap-request-create-group
1407             nnimap-time-substract
1408             nnimap-date-days-ago
1409             nnimap-request-expire-articles-progress
1410             nnimap-request-expire-articles
1411             nnimap-request-move-article
1412             nnimap-request-accept-article
1413             nnimap-request-delete-group
1414             nnimap-request-rename-group
1415             gnus-group-nnimap-expunge
1416             gnus-group-nnimap-edit-acl
1417             gnus-group-nnimap-edit-acl-done
1418             nnimap-group-mode-hook
1419             nnimap-mark-to-predicate
1420             nnimap-mark-to-flag-1
1421             nnimap-mark-to-flag
1422             nnimap-mark-permanent-p
1423             )))
1424
1425 (provide 'nnimap)
1426
1427 ;;; nnimap.el ends here