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