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