* nnimap.el (nnimap-retrieve-groups): Don't send STATUS when
[gnus] / 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 (deffoo nnimap-retrieve-groups (groups &optional server)
942   (when (nnimap-possibly-change-server server)
943     (gnus-message 5 "nnimap: Checking mailboxes...")
944     (with-current-buffer nntp-server-buffer
945       (erase-buffer)
946       (nnimap-before-find-minmax-bugworkaround)
947       (let (asyncgroups slowgroups)
948         (if (null nnimap-retrieve-groups-asynchronous)
949             (setq slowgroups groups)
950           (dolist (group groups)
951             (gnus-message 7 "nnimap: Checking mailbox %s" group)
952             (add-to-list (if (gnus-gethash-safe group nnimap-mailbox-info)
953                              'asyncgroups
954                            'slowgroups)
955                          (list group (imap-mailbox-status-asynch
956                                       group 'uidnext nnimap-server-buffer))))
957           (dolist (asyncgroup asyncgroups)
958             (let ((group (nth 0 asyncgroup))
959                   (tag   (nth 1 asyncgroup))
960                   new old)
961               (when (imap-ok-p (imap-wait-for-tag tag nnimap-server-buffer))
962                 (if (< (car (gnus-gethash group nnimap-mailbox-info))
963                        (imap-mailbox-get 'uidnext group nnimap-server-buffer))
964                     (push (list group) slowgroups)
965                   (insert (cdr (gnus-gethash group nnimap-mailbox-info))))))))
966         (dolist (group slowgroups)
967           (if nnimap-retrieve-groups-asynchronous
968               (setq group (car group)))
969           (gnus-message 7 "nnimap: Rechecking mailbox %s" group)
970           (imap-mailbox-put 'uidnext nil group nnimap-server-buffer)
971           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags group
972                                                      nnimap-server-buffer))
973               (let* ((info (nnimap-find-minmax-uid group 'examine))
974                      (str (format "\"%s\" %d %d y\n" group
975                                   (or (nth 2 info) 0)
976                                   (max 1 (or (nth 1 info) 1)))))
977                 (when (> (or (imap-mailbox-get 'recent group
978                                                nnimap-server-buffer) 0)
979                          0)
980                   (push (list (cons group 0)) nnmail-split-history))
981                 (insert str)
982                 (when nnimap-retrieve-groups-asynchronous
983                   (gnus-sethash
984                    group
985                    (cons (or (imap-mailbox-get
986                               'uidnext group nnimap-server-buffer)
987                              (imap-mailbox-status
988                               group 'uidnext nnimap-server-buffer))
989                          str)
990                    nnimap-mailbox-info)))))))
991     (gnus-message 5 "nnimap: Checking mailboxes...done")
992     'active))
993
994 (deffoo nnimap-request-update-info-internal (group info &optional server)
995   (when (nnimap-possibly-change-group group server)
996     (when info ;; xxx what does this mean? should we create a info?
997       (with-current-buffer nnimap-server-buffer
998         (gnus-message 5 "nnimap: Updating info for %s..."
999                       (gnus-info-group info))
1000
1001         (when (nnimap-mark-permanent-p 'read)
1002           (let (seen unseen)
1003             ;; read info could contain articles marked unread by other
1004             ;; imap clients!  we correct this
1005             (setq seen (gnus-uncompress-range (gnus-info-read info))
1006                   unseen (imap-search "UNSEEN UNDELETED")
1007                   seen (gnus-set-difference seen unseen)
1008                   ;; seen might lack articles marked as read by other
1009                   ;; imap clients! we correct this
1010                   seen (append seen (imap-search "SEEN"))
1011                   ;; remove dupes
1012                   seen (sort seen '<)
1013                   seen (gnus-compress-sequence seen t)
1014                   ;; we can't return '(1) since this isn't a "list of ranges",
1015                   ;; and we can't return '((1)) since g-list-of-unread-articles
1016                   ;; is buggy so we return '((1 . 1)).
1017                   seen (if (and (integerp (car seen))
1018                                 (null (cdr seen)))
1019                            (list (cons (car seen) (car seen)))
1020                          seen))
1021             (gnus-info-set-read info seen)))
1022
1023         (mapcar (lambda (pred)
1024                   (when (or (eq (cdr pred) 'recent)
1025                             (and (nnimap-mark-permanent-p (cdr pred))
1026                                  (member (nnimap-mark-to-flag (cdr pred))
1027                                          (imap-mailbox-get 'flags))))
1028                     (gnus-info-set-marks
1029                      info
1030                      (gnus-update-alist-soft
1031                       (cdr pred)
1032                       (gnus-compress-sequence
1033                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
1034                       (gnus-info-marks info))
1035                      t)))
1036                 gnus-article-mark-lists)
1037
1038         (when nnimap-importantize-dormant
1039           ;; nnimap mark dormant article as ticked too (for other clients)
1040           ;; so we remove that mark for gnus since we support dormant
1041           (gnus-info-set-marks
1042            info
1043            (gnus-update-alist-soft
1044             'tick
1045             (gnus-remove-from-range
1046              (cdr-safe (assoc 'tick (gnus-info-marks info)))
1047              (cdr-safe (assoc 'dormant (gnus-info-marks info))))
1048             (gnus-info-marks info))
1049            t))
1050
1051         (gnus-message 5 "nnimap: Updating info for %s...done"
1052                       (gnus-info-group info))
1053
1054         info))))
1055
1056 (deffoo nnimap-request-type (group &optional article)
1057   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
1058       'news
1059     'mail))
1060
1061 (deffoo nnimap-request-set-mark (group actions &optional server)
1062   (when (nnimap-possibly-change-group group server)
1063     (with-current-buffer nnimap-server-buffer
1064       (let (action)
1065         (gnus-message 7 "nnimap: Setting marks in %s..." group)
1066         (while (setq action (pop actions))
1067           (let ((range (nth 0 action))
1068                 (what  (nth 1 action))
1069                 (cmdmarks (nth 2 action))
1070                 marks)
1071             ;; bookmark can't be stored (not list/range
1072             (setq cmdmarks (delq 'bookmark cmdmarks))
1073             ;; killed can't be stored (not list/range
1074             (setq cmdmarks (delq 'killed cmdmarks))
1075             ;; unsent are for nndraft groups only
1076             (setq cmdmarks (delq 'unsent cmdmarks))
1077             ;; cache flags are pointless on the server
1078             (setq cmdmarks (delq 'cache cmdmarks))
1079             ;; seen flags are local to each gnus
1080             (setq cmdmarks (delq 'seen cmdmarks))
1081             ;; recent marks can't be set
1082             (setq cmdmarks (delq 'recent cmdmarks))
1083             (when nnimap-importantize-dormant
1084               ;; flag dormant articles as ticked
1085               (if (memq 'dormant cmdmarks)
1086                   (setq cmdmarks (cons 'tick cmdmarks))))
1087             ;; remove stuff we are forbidden to store
1088             (mapcar (lambda (mark)
1089                       (if (imap-message-flag-permanent-p
1090                            (nnimap-mark-to-flag mark))
1091                           (setq marks (cons mark marks))))
1092                     cmdmarks)
1093             (when (and range marks)
1094               (cond ((eq what 'del)
1095                      (imap-message-flags-del
1096                       (imap-range-to-message-set range)
1097                       (nnimap-mark-to-flag marks nil t)))
1098                     ((eq what 'add)
1099                      (imap-message-flags-add
1100                       (imap-range-to-message-set range)
1101                       (nnimap-mark-to-flag marks nil t)))
1102                     ((eq what 'set)
1103                      (imap-message-flags-set
1104                       (imap-range-to-message-set range)
1105                       (nnimap-mark-to-flag marks nil t)))))))
1106         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
1107   nil)
1108
1109 (defun nnimap-split-fancy ()
1110   "Like the function `nnmail-split-fancy', but uses `nnimap-split-fancy'."
1111   (let ((nnmail-split-fancy nnimap-split-fancy))
1112     (nnmail-split-fancy)))
1113
1114 (defun nnimap-split-to-groups (rules)
1115   ;; tries to match all rules in nnimap-split-rule against content of
1116   ;; nntp-server-buffer, returns a list of groups that matched.
1117   (with-current-buffer nntp-server-buffer
1118     ;; Fold continuation lines.
1119     (goto-char (point-min))
1120     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1121       (replace-match " " t t))
1122     (if (functionp rules)
1123         (funcall rules)
1124       (let (to-groups regrepp)
1125         (catch 'split-done
1126           (dolist (rule rules to-groups)
1127             (let ((group (car rule))
1128                   (regexp (cadr rule)))
1129               (goto-char (point-min))
1130               (when (and (if (stringp regexp)
1131                              (progn
1132                                (setq regrepp (string-match "\\\\[0-9&]" group))
1133                                (re-search-forward regexp nil t))
1134                            (funcall regexp group))
1135                          ;; Don't enter the article into the same group twice.
1136                          (not (assoc group to-groups)))
1137                 (push (if regrepp
1138                           (nnmail-expand-newtext group)
1139                         group)
1140                       to-groups)
1141                 (or nnimap-split-crosspost
1142                     (throw 'split-done to-groups))))))))))
1143
1144 (defun nnimap-assoc-match (key alist)
1145   (let (element)
1146     (while (and alist (not element))
1147       (if (string-match (car (car alist)) key)
1148           (setq element (car alist)))
1149       (setq alist (cdr alist)))
1150     element))
1151
1152 (defun nnimap-split-find-rule (server inbox)
1153   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
1154            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
1155       ;; extended format
1156       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match
1157                                             server nnimap-split-rule))))
1158     nnimap-split-rule))
1159
1160 (defun nnimap-split-find-inbox (server)
1161   (if (listp nnimap-split-inbox)
1162       nnimap-split-inbox
1163     (list nnimap-split-inbox)))
1164
1165 (defun nnimap-split-articles (&optional group server)
1166   (when (nnimap-possibly-change-server server)
1167     (with-current-buffer nnimap-server-buffer
1168       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
1169         ;; iterate over inboxes
1170         (while (and (setq inbox (pop inboxes))
1171                     (nnimap-possibly-change-group inbox)) ;; SELECT
1172           ;; find split rule for this server / inbox
1173           (when (setq rule (nnimap-split-find-rule server inbox))
1174             ;; iterate over articles
1175             (dolist (article (imap-search nnimap-split-predicate))
1176               (when (nnimap-request-head article)
1177                 ;; copy article to right group(s)
1178                 (setq removeorig nil)
1179                 (dolist (to-group (nnimap-split-to-groups rule))
1180                   (cond ((eq to-group 'junk)
1181                          (message "IMAP split removed %s:%s:%d" server inbox
1182                                   article)
1183                          (setq removeorig t))
1184                         ((imap-message-copy (number-to-string article)
1185                                             to-group nil 'nocopyuid)
1186                          (message "IMAP split moved %s:%s:%d to %s" server
1187                                   inbox article to-group)
1188                          (setq removeorig t)
1189                          (when nnmail-cache-accepted-message-ids
1190                            (with-current-buffer nntp-server-buffer
1191                              (nnmail-cache-insert (nnmail-fetch-field
1192                                                    "message-id") to-group)))
1193                          ;; Add the group-art list to the history list.
1194                          (push (list (cons to-group 0)) nnmail-split-history))
1195                         (t
1196                          (message "IMAP split failed to move %s:%s:%d to %s"
1197                                   server inbox article to-group))))
1198                 ;; remove article if it was successfully copied somewhere
1199                 (and removeorig
1200                      (imap-message-flags-add (format "%d" article)
1201                                              "\\Seen \\Deleted")))))
1202           (when (imap-mailbox-select inbox) ;; just in case
1203             ;; todo: UID EXPUNGE (if available) to remove splitted articles
1204             (imap-mailbox-expunge)
1205             (imap-mailbox-close)))
1206         (when nnmail-cache-accepted-message-ids
1207           (nnmail-cache-close))
1208         t))))
1209
1210 (deffoo nnimap-request-scan (&optional group server)
1211   (nnimap-split-articles group server))
1212
1213 (deffoo nnimap-request-newgroups (date &optional server)
1214   (when (nnimap-possibly-change-server server)
1215     (with-current-buffer nntp-server-buffer
1216       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
1217                     (if (> (length server) 0) " on " "") server)
1218       (erase-buffer)
1219       (nnimap-before-find-minmax-bugworkaround)
1220       (dolist (pattern (nnimap-pattern-to-list-arguments
1221                         nnimap-list-pattern))
1222         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil
1223                                         nnimap-server-buffer))
1224           (or (catch 'found
1225                 (dolist (mailbox (imap-mailbox-get 'list-flags mbx
1226                                                    nnimap-server-buffer))
1227                   (if (string= (downcase mailbox) "\\noselect")
1228                       (throw 'found t)))
1229                 nil)
1230               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
1231                 (when info
1232                   (insert (format "\"%s\" %d %d y\n"
1233                                   mbx (or (nth 2 info) 0)
1234                                   (max 1 (or (nth 1 info) 1)))))))))
1235       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1236                     (if (> (length server) 0) " on " "") server))
1237     t))
1238
1239 (deffoo nnimap-request-create-group (group &optional server args)
1240   (when (nnimap-possibly-change-server server)
1241     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1242         (imap-mailbox-create group nnimap-server-buffer))))
1243
1244 (defun nnimap-time-substract (time1 time2)
1245   "Return TIME for TIME1 - TIME2."
1246   (let* ((ms (- (car time1) (car time2)))
1247          (ls (- (nth 1 time1) (nth 1 time2))))
1248     (if (< ls 0)
1249         (list (- ms 1) (+ (expt 2 16) ls))
1250       (list ms ls))))
1251
1252 (defun nnimap-date-days-ago (daysago)
1253   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1254   (let* ((time (nnimap-time-substract (current-time) (days-to-time daysago)))
1255          (date (format-time-string
1256                 (format "%%d-%s-%%Y"
1257                         (capitalize (car (rassoc (nth 4 (decode-time time))
1258                                                  parse-time-months))))
1259                 time)))
1260     (if (eq ?0 (string-to-char date))
1261         (substring date 1)
1262       date)))
1263
1264 (defun nnimap-request-expire-articles-progress ()
1265   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1266                 imap-current-message))
1267
1268 (defun nnimap-expiry-target (arts group server)
1269   (unless (eq nnmail-expiry-target 'delete)
1270     (with-temp-buffer
1271       (dolist (art (gnus-uncompress-sequence arts))
1272         (nnimap-request-article art group server  (current-buffer))
1273         ;; hints for optimization in `nnimap-request-accept-article'
1274         (let ((nnimap-current-move-article art)
1275               (nnimap-current-move-group group)
1276               (nnimap-current-move-server server))
1277           (nnmail-expiry-target-group nnmail-expiry-target group))))
1278     ;; It is not clear if `nnmail-expiry-target' somehow cause the
1279     ;; current group to be changed or not, so we make sure here.
1280     (nnimap-possibly-change-group group server)))
1281
1282 ;; Notice that we don't actually delete anything, we just mark them deleted.
1283 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1284   (let ((artseq (gnus-compress-sequence articles)))
1285     (when (and artseq (nnimap-possibly-change-group group server))
1286       (with-current-buffer nnimap-server-buffer
1287         (if force
1288             (progn
1289               (nnimap-expiry-target artseq group server)
1290               (when (imap-message-flags-add (imap-range-to-message-set artseq)
1291                                             "\\Deleted")
1292                 (setq articles nil)))
1293           (let ((days (or (and nnmail-expiry-wait-function
1294                                (funcall nnmail-expiry-wait-function group))
1295                           nnmail-expiry-wait)))
1296             (cond ((eq days 'immediate)
1297                    (nnimap-expiry-target artseq group server)
1298                    (when (imap-message-flags-add
1299                           (imap-range-to-message-set artseq) "\\Deleted")
1300                      (setq articles nil)))
1301                   ((numberp days)
1302                    (let ((oldarts (imap-search
1303                                    (format nnimap-expunge-search-string
1304                                            (imap-range-to-message-set artseq)
1305                                            (nnimap-date-days-ago days))))
1306                          (imap-fetch-data-hook
1307                           '(nnimap-request-expire-articles-progress)))
1308                      (nnimap-expiry-target oldarts group server)
1309                      (and oldarts
1310                           (imap-message-flags-add
1311                            (imap-range-to-message-set
1312                             (gnus-compress-sequence oldarts))
1313                            "\\Deleted")
1314                           (setq articles (gnus-set-difference
1315                                           articles oldarts)))))))))))
1316   ;; return articles not deleted
1317   articles)
1318
1319 (deffoo nnimap-request-move-article (article group server
1320                                              accept-form &optional last)
1321   (when (nnimap-possibly-change-server server)
1322     (save-excursion
1323       (let ((buf (get-buffer-create " *nnimap move*"))
1324             (nnimap-current-move-article article)
1325             (nnimap-current-move-group group)
1326             (nnimap-current-move-server nnimap-current-server)
1327             result)
1328         (and (nnimap-request-article article group server)
1329              (save-excursion
1330                (set-buffer buf)
1331                (buffer-disable-undo (current-buffer))
1332                (insert-buffer-substring nntp-server-buffer)
1333                (setq result (eval accept-form))
1334                (kill-buffer buf)
1335                result)
1336              (imap-message-flags-add
1337               (imap-range-to-message-set (list article))
1338               "\\Deleted" 'silent nnimap-server-buffer))
1339         result))))
1340
1341 (deffoo nnimap-request-accept-article (group &optional server last)
1342   (when (nnimap-possibly-change-server server)
1343     (let (uid)
1344       (if (setq uid
1345                 (if (string= nnimap-current-server nnimap-current-move-server)
1346                     ;; moving article within same server, speed it up...
1347                     (and (nnimap-possibly-change-group
1348                           nnimap-current-move-group)
1349                          (imap-message-copy (number-to-string
1350                                              nnimap-current-move-article)
1351                                             group 'dontcreate nil
1352                                             nnimap-server-buffer))
1353                   (with-current-buffer (current-buffer)
1354                     (goto-char (point-min))
1355                     ;; remove any 'From blabla' lines, some IMAP servers
1356                     ;; reject the entire message otherwise.
1357                     (when (looking-at "^From[^:]")
1358                       (kill-region (point) (progn (forward-line) (point))))
1359                     ;; turn into rfc822 format (\r\n eol's)
1360                     (while (search-forward "\n" nil t)
1361                       (replace-match "\r\n"))
1362                     (when nnmail-cache-accepted-message-ids
1363                       (nnmail-cache-insert (nnmail-fetch-field "message-id"))))
1364                   (when (and last nnmail-cache-accepted-message-ids)
1365                     (nnmail-cache-close))
1366                   ;; this 'or' is for Cyrus server bug
1367                   (or (null (imap-current-mailbox nnimap-server-buffer))
1368                       (imap-mailbox-unselect nnimap-server-buffer))
1369                   (imap-message-append group (current-buffer) nil nil
1370                                        nnimap-server-buffer)))
1371           (cons group (nth 1 uid))
1372         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1373
1374 (deffoo nnimap-request-delete-group (group force &optional server)
1375   (when (nnimap-possibly-change-server server)
1376     (with-current-buffer nnimap-server-buffer
1377       (if force
1378           (or (null (imap-mailbox-status group 'uidvalidity))
1379               (imap-mailbox-delete group))
1380         ;; UNSUBSCRIBE?
1381         t))))
1382
1383 (deffoo nnimap-request-rename-group (group new-name &optional server)
1384   (when (nnimap-possibly-change-server server)
1385     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1386
1387 (defun nnimap-expunge (mailbox server)
1388   (when (nnimap-possibly-change-group mailbox server)
1389     (imap-mailbox-expunge nil nnimap-server-buffer)))
1390
1391 (defun nnimap-acl-get (mailbox server)
1392   (when (nnimap-possibly-change-server server)
1393     (and (imap-capability 'ACL nnimap-server-buffer)
1394          (imap-mailbox-acl-get mailbox nnimap-server-buffer))))
1395
1396 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1397   (when (nnimap-possibly-change-server (cadr method))
1398     (unless (imap-capability 'ACL nnimap-server-buffer)
1399       (error "Your server does not support ACL editing"))
1400     (with-current-buffer nnimap-server-buffer
1401       ;; delete all removed identifiers
1402       (mapcar (lambda (old-acl)
1403                 (unless (assoc (car old-acl) new-acls)
1404                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1405                       (error "Can't delete ACL for %s" (car old-acl)))))
1406               old-acls)
1407       ;; set all changed acl's
1408       (mapcar (lambda (new-acl)
1409                 (let ((new-rights (cdr new-acl))
1410                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1411                   (unless (and old-rights new-rights
1412                                (string= old-rights new-rights))
1413                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1414                         (error "Can't set ACL for %s to %s" (car new-acl)
1415                                new-rights)))))
1416               new-acls)
1417       t)))
1418
1419 \f
1420 ;;; Internal functions
1421
1422 ;;
1423 ;; This is confusing.
1424 ;;
1425 ;; mark      => read, tick, draft, reply etc
1426 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1427 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1428 ;;
1429 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1430 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1431 ;;
1432
1433 (defconst nnimap-mark-to-predicate-alist
1434   (mapcar
1435    (lambda (pair)                       ; cdr is the mark
1436      (or (assoc (cdr pair)
1437                 '((read . "SEEN")
1438                   (tick . "FLAGGED")
1439                   (draft . "DRAFT")
1440                   (recent . "RECENT")
1441                   (reply . "ANSWERED")))
1442          (cons (cdr pair)
1443                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1444    (cons '(read . read) gnus-article-mark-lists)))
1445
1446 (defun nnimap-mark-to-predicate (pred)
1447   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1448 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1449 to be used within a IMAP SEARCH query."
1450   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1451
1452 (defconst nnimap-mark-to-flag-alist
1453   (mapcar
1454    (lambda (pair)
1455      (or (assoc (cdr pair)
1456                 '((read . "\\Seen")
1457                   (tick . "\\Flagged")
1458                   (draft . "\\Draft")
1459                   (recent . "\\Recent")
1460                   (reply . "\\Answered")))
1461          (cons (cdr pair)
1462                (format "gnus-%s" (symbol-name (cdr pair))))))
1463    (cons '(read . read) gnus-article-mark-lists)))
1464
1465 (defun nnimap-mark-to-flag-1 (preds)
1466   (if (and (not (null preds)) (listp preds))
1467       (cons (nnimap-mark-to-flag (car preds))
1468             (nnimap-mark-to-flag (cdr preds)))
1469     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1470
1471 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1472   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1473 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1474 be used in a STORE FLAGS command."
1475   (let ((result (nnimap-mark-to-flag-1 preds)))
1476     (setq result (if (and (or make-string always-list)
1477                           (not (listp result)))
1478                      (list result)
1479                    result))
1480     (if make-string
1481         (mapconcat (lambda (flag)
1482                      (if (listp flag)
1483                          (mapconcat 'identity flag " ")
1484                        flag))
1485                    result " ")
1486       result)))
1487
1488 (defun nnimap-mark-permanent-p (mark &optional group)
1489   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1490   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1491
1492 (when nnimap-debug
1493   (require 'trace)
1494   (buffer-disable-undo (get-buffer-create nnimap-debug))
1495   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1496           '(
1497             nnimap-possibly-change-server
1498             nnimap-verify-uidvalidity
1499             nnimap-find-minmax-uid
1500             nnimap-before-find-minmax-bugworkaround
1501             nnimap-possibly-change-group
1502             ;;nnimap-replace-whitespace
1503             nnimap-retrieve-headers-progress
1504             nnimap-retrieve-which-headers
1505             nnimap-group-overview-filename
1506             nnimap-retrieve-headers-from-file
1507             nnimap-retrieve-headers-from-server
1508             nnimap-retrieve-headers
1509             nnimap-open-connection
1510             nnimap-open-server
1511             nnimap-server-opened
1512             nnimap-close-server
1513             nnimap-request-close
1514             nnimap-status-message
1515             ;;nnimap-demule
1516             nnimap-request-article-part
1517             nnimap-request-article
1518             nnimap-request-head
1519             nnimap-request-body
1520             nnimap-request-group
1521             nnimap-close-group
1522             nnimap-pattern-to-list-arguments
1523             nnimap-request-list
1524             nnimap-request-post
1525             nnimap-retrieve-groups
1526             nnimap-request-update-info-internal
1527             nnimap-request-type
1528             nnimap-request-set-mark
1529             nnimap-split-to-groups
1530             nnimap-split-find-rule
1531             nnimap-split-find-inbox
1532             nnimap-split-articles
1533             nnimap-request-scan
1534             nnimap-request-newgroups
1535             nnimap-request-create-group
1536             nnimap-time-substract
1537             nnimap-date-days-ago
1538             nnimap-request-expire-articles-progress
1539             nnimap-request-expire-articles
1540             nnimap-request-move-article
1541             nnimap-request-accept-article
1542             nnimap-request-delete-group
1543             nnimap-request-rename-group
1544             gnus-group-nnimap-expunge
1545             gnus-group-nnimap-edit-acl
1546             gnus-group-nnimap-edit-acl-done
1547             nnimap-group-mode-hook
1548             nnimap-mark-to-predicate
1549             nnimap-mark-to-flag-1
1550             nnimap-mark-to-flag
1551             nnimap-mark-permanent-p
1552             )))
1553
1554 (provide 'nnimap)
1555
1556 ;;; nnimap.el ends here