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