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