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