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