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