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