"Use instead" obsolescence messages should end with "."
[bpt/emacs.git] / lisp / gnus / nnimap.el
CommitLineData
20a673b2 1;;; nnimap.el --- IMAP interface for Gnus
e84b4b86 2
ba318903 3;; Copyright (C) 2010-2014 Free Software Foundation, Inc.
c113de23 4
20a673b2
KY
5;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6;; Simon Josefsson <simon@josefsson.org>
c113de23
GM
7
8;; This file is part of GNU Emacs.
9
5e809f55 10;; GNU Emacs is free software: you can redistribute it and/or modify
c113de23 11;; it under the terms of the GNU General Public License as published by
5e809f55
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
c113de23
GM
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
5e809f55 17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
c113de23
GM
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
5e809f55 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
c113de23
GM
22
23;;; Commentary:
24
20a673b2 25;; nnimap interfaces Gnus with IMAP servers.
c113de23
GM
26
27;;; Code:
28
f0b7f5a8
KY
29;; For Emacs <22.2 and XEmacs.
30(eval-and-compile
31 (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
32
aa8f8277 33(eval-and-compile
da91b5f2
CY
34 (require 'nnheader)
35 ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
36 ;; `make-network-stream'.
37 (unless (fboundp 'open-protocol-stream)
38 (require 'proto-stream)))
aa8f8277 39
20a673b2
KY
40(eval-when-compile
41 (require 'cl))
c113de23 42
f58208b1
LMI
43(require 'nnheader)
44(require 'gnus-util)
45(require 'gnus)
46(require 'nnoo)
20a673b2 47(require 'netrc)
14db1c41 48(require 'utf7)
6b958814 49(require 'tls)
0617bb00 50(require 'parse-time)
2b1e1ff4
GM
51(require 'nnmail)
52
b8e0f0cd
G
53(autoload 'auth-source-forget+ "auth-source")
54(autoload 'auth-source-search "auth-source")
635be05a 55
c113de23
GM
56(nnoo-declare nnimap)
57
c113de23 58(defvoo nnimap-address nil
20a673b2 59 "The address of the IMAP server.")
c113de23 60
5e68f861
TZ
61(defvoo nnimap-user nil
62 "Username to use for authentication to the IMAP server.")
63
c113de23 64(defvoo nnimap-server-port nil
20a673b2
KY
65 "The IMAP port used.
66If nnimap-stream is `ssl', this will default to `imaps'. If not,
67it will default to `imap'.")
68
ed797193 69(defvoo nnimap-stream 'undecided
e742e117
CY
70 "How nnimap talks to the IMAP server.
71The value should be either `undecided', `ssl' or `tls',
72`network', `starttls', `plain', or `shell'.
73
74If the value is `undecided', nnimap tries `ssl' first, then falls
75back on `network'.")
20a673b2
KY
76
77(defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
78 (if (listp imap-shell-program)
79 (car imap-shell-program)
80 imap-shell-program)
81 "ssh %s imapd"))
82
83(defvoo nnimap-inbox nil
8e22bee0 84 "The mail box where incoming mail arrives and should be split out of.
eaa610c3
KY
85This can be a string or a list of strings
86For example, \"INBOX\" or (\"INBOX\" \"SENT\").")
20a673b2 87
8ccbef23
G
88(defvoo nnimap-split-methods nil
89 "How mail is split.
8e22bee0 90Uses the same syntax as `nnmail-split-methods'.")
8ccbef23 91
6b958814 92(defvoo nnimap-split-fancy nil
8e22bee0 93 "Uses the same syntax as `nnmail-split-fancy'.")
6b958814 94
99e65b2d
G
95(defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
96 "Articles with the flags in the list will not be considered when splitting.")
97
e92e30dd 98(make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'."
6b958814 99 "Emacs 24.1")
229b59da 100
bdaa75c7
LMI
101(defvoo nnimap-authenticator nil
102 "How nnimap authenticate itself to the server.
45dd6480
LI
103Possible choices are nil (use default methods), `anonymous',
104`login', `plain' and `cram-md5'.")
bdaa75c7 105
b069e5a6
G
106(defvoo nnimap-expunge t
107 "If non-nil, expunge articles after deleting them.
108This is always done if the server supports UID EXPUNGE, but it's
109not done by default on servers that doesn't support that command.")
110
8ccbef23
G
111(defvoo nnimap-streaming t
112 "If non-nil, try to use streaming commands with IMAP servers.
113Switching this off will make nnimap slower, but it helps with
114some servers.")
0617bb00 115
20a673b2 116(defvoo nnimap-connection-alist nil)
286c4fc2
LMI
117
118(defvoo nnimap-current-infos nil)
119
9f2d52e7
G
120(defvoo nnimap-fetch-partial-articles nil
121 "If non-nil, Gnus will fetch partial articles.
89b163db 122If t, Gnus will fetch only the first part. If a string, it
9f2d52e7
G
123will fetch all parts that have types that match that string. A
124likely value would be \"text/\" to automatically fetch all
125textual parts.")
126
eaa610c3
KY
127(defgroup nnimap nil
128 "IMAP for Gnus."
129 :group 'gnus)
130
131(defcustom nnimap-request-articles-find-limit nil
132 "Limit the number of articles to look for after moving an article."
af1c6c84
GM
133 :type '(choice (const nil) integer)
134 :version "24.4"
eaa610c3
KY
135 :group 'nnimap)
136
20a673b2
KY
137(defvar nnimap-process nil)
138
139(defvar nnimap-status-string "")
23f87bed
MB
140
141(defvar nnimap-split-download-body-default nil
142 "Internal variable with default value for `nnimap-split-download-body'.")
143
61b1af82
G
144(defvar nnimap-keepalive-timer nil)
145(defvar nnimap-process-buffers nil)
146
20a673b2 147(defstruct nnimap
61b1af82 148 group process commands capabilities select-result newlinep server
b5235dd9 149 last-command-time greeting examined stream-type initial-resync)
c113de23 150
20a673b2
KY
151(defvar nnimap-object nil)
152
153(defvar nnimap-mark-alist
b069e5a6
G
154 '((read "\\Seen" %Seen)
155 (tick "\\Flagged" %Flagged)
156 (reply "\\Answered" %Answered)
20a673b2
KY
157 (expire "gnus-expire")
158 (dormant "gnus-dormant")
159 (score "gnus-score")
160 (save "gnus-save")
161 (download "gnus-download")
162 (forward "gnus-forward")))
163
549c9aed
G
164(defvar nnimap-quirks
165 '(("QRESYNC" "Zimbra" "QRESYNC ")))
166
d5e9a4e9
LI
167(defvar nnimap-inhibit-logging nil)
168
20a673b2
KY
169(defun nnimap-buffer ()
170 (nnimap-find-process-buffer nntp-server-buffer))
171
b5c575e6
G
172(defun nnimap-header-parameters ()
173 (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
174 (format
175 (if (nnimap-ver4-p)
176 "BODY.PEEK[HEADER.FIELDS %s]"
177 "RFC822.HEADER.LINES %s")
178 (append '(Subject From Date Message-Id
179 References In-Reply-To Xref)
180 nnmail-extra-headers))))
181
286c4fc2 182(deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
e21bac42
G
183 (when group
184 (setq group (nnimap-decode-gnus-group group)))
c113de23 185 (with-current-buffer nntp-server-buffer
20a673b2 186 (erase-buffer)
eaa610c3 187 (when (nnimap-change-group group server)
20a673b2 188 (with-current-buffer (nnimap-buffer)
20a673b2
KY
189 (erase-buffer)
190 (nnimap-wait-for-response
191 (nnimap-send-command
192 "UID FETCH %s %s"
193 (nnimap-article-ranges (gnus-compress-sequence articles))
b5c575e6 194 (nnimap-header-parameters))
20a673b2 195 t)
70041e9a
G
196 (nnimap-transform-headers)
197 (nnheader-remove-cr-followed-by-lf))
20a673b2
KY
198 (insert-buffer-substring
199 (nnimap-find-process-buffer (current-buffer))))
b1ae92ba 200 'headers))
20a673b2
KY
201
202(defun nnimap-transform-headers ()
203 (goto-char (point-min))
827235c3 204 (let (article lines size string)
20a673b2
KY
205 (block nil
206 (while (not (eobp))
827235c3 207 (while (not (looking-at "\\* [0-9]+ FETCH"))
20a673b2
KY
208 (delete-region (point) (progn (forward-line 1) (point)))
209 (when (eobp)
210 (return)))
827235c3 211 (goto-char (match-end 0))
733de8e2 212 ;; Unfold quoted {number} strings.
827235c3
LI
213 (while (re-search-forward
214 "[^]][ (]{\\([0-9]+\\)}\r?\n"
215 (save-excursion
20d6487e
LI
216 ;; Start of the header section.
217 (or (re-search-forward "] {[0-9]+}\r?\n" nil t)
218 ;; Start of the next FETCH.
ec80e689 219 (re-search-forward "\\* [0-9]+ FETCH" nil t)
827235c3
LI
220 (point-max)))
221 t)
733de8e2
LMI
222 (setq size (string-to-number (match-string 1)))
223 (delete-region (+ (match-beginning 0) 2) (point))
224 (setq string (buffer-substring (point) (+ (point) size)))
225 (delete-region (point) (+ (point) size))
1f0f21c5 226 (insert (format "%S" (mm-subst-char-in-string ?\n ?\s string))))
20a673b2 227 (beginning-of-line)
827235c3
LI
228 (setq article
229 (and (re-search-forward "UID \\([0-9]+\\)" (line-end-position)
230 t)
231 (match-string 1)))
232 (setq lines nil)
a46359d4
LMI
233 (setq size
234 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
235 (line-end-position)
236 t)
237 (match-string 1)))
238 (beginning-of-line)
20a673b2 239 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
b1ae92ba
G
240 (let ((structure (ignore-errors
241 (read (current-buffer)))))
20a673b2 242 (while (and (consp structure)
4d9db491 243 (not (atom (car structure))))
20a673b2 244 (setq structure (car structure)))
fb568e63 245 (setq lines (if (and
4d9db491 246 (stringp (car structure))
fb568e63
AC
247 (equal (upcase (nth 0 structure)) "MESSAGE")
248 (equal (upcase (nth 1 structure)) "RFC822"))
249 (nth 9 structure)
250 (nth 7 structure)))))
20a673b2
KY
251 (delete-region (line-beginning-position) (line-end-position))
252 (insert (format "211 %s Article retrieved." article))
253 (forward-line 1)
a46359d4
LMI
254 (when size
255 (insert (format "Chars: %s\n" size)))
20a673b2
KY
256 (when lines
257 (insert (format "Lines: %s\n" lines)))
579d49fa
LI
258 ;; Most servers have a blank line after the headers, but
259 ;; Davmail doesn't.
260 (unless (re-search-forward "^\r$\\|^)\r?$" nil t)
b5c575e6 261 (goto-char (point-max)))
20a673b2
KY
262 (delete-region (line-beginning-position) (line-end-position))
263 (insert ".")
264 (forward-line 1)))))
265
a56a1cce
LMI
266(defun nnimap-unfold-quoted-lines ()
267 ;; Unfold quoted {number} strings.
733de8e2
LMI
268 (let (size string)
269 (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
270 (setq size (string-to-number (match-string 1)))
271 (delete-region (1+ (match-beginning 0)) (point))
272 (setq string (buffer-substring (point) (+ (point) size)))
273 (delete-region (point) (+ (point) size))
274 (insert (format "%S" string)))))
a56a1cce 275
20a673b2
KY
276(defun nnimap-get-length ()
277 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
278 (string-to-number (match-string 1))))
279
280(defun nnimap-article-ranges (ranges)
281 (let (result)
282 (cond
283 ((numberp ranges)
284 (number-to-string ranges))
285 ((numberp (cdr ranges))
286 (format "%d:%d" (car ranges) (cdr ranges)))
287 (t
288 (dolist (elem ranges)
289 (push
290 (if (consp elem)
291 (format "%d:%d" (car elem) (cdr elem))
292 (number-to-string elem))
293 result))
294 (mapconcat #'identity (nreverse result) ",")))))
295
98366438 296(deffoo nnimap-open-server (server &optional defs no-reconnect)
c113de23
GM
297 (if (nnimap-server-opened server)
298 t
c113de23 299 (unless (assq 'nnimap-address defs)
20a673b2 300 (setq defs (append defs (list (list 'nnimap-address server)))))
c113de23 301 (nnoo-change-server 'nnimap server defs)
98366438
LI
302 (if no-reconnect
303 (nnimap-find-connection nntp-server-buffer)
304 (or (nnimap-find-connection nntp-server-buffer)
305 (nnimap-open-connection nntp-server-buffer)))))
20a673b2
KY
306
307(defun nnimap-make-process-buffer (buffer)
308 (with-current-buffer
3d2af193 309 (generate-new-buffer (format " *nnimap %s %s %s*"
20a673b2
KY
310 nnimap-address nnimap-server-port
311 (gnus-buffer-exists-p buffer)))
312 (mm-disable-multibyte)
313 (buffer-disable-undo)
314 (gnus-add-buffer)
315 (set (make-local-variable 'after-change-functions) nil)
b069e5a6 316 (set (make-local-variable 'nnimap-object)
b5235dd9
LI
317 (make-nnimap :server (nnoo-current-server 'nnimap)
318 :initial-resync 0))
20a673b2 319 (push (list buffer (current-buffer)) nnimap-connection-alist)
61b1af82 320 (push (current-buffer) nnimap-process-buffers)
20a673b2
KY
321 (current-buffer)))
322
5e68f861 323(defun nnimap-credentials (address ports user)
733afdf4
TZ
324 (let* ((auth-source-creation-prompts
325 '((user . "IMAP user at %h: ")
326 (secret . "IMAP password for %u@%h: ")))
327 (found (nth 0 (auth-source-search :max 1
328 :host address
329 :port ports
5e68f861 330 :user user
733afdf4
TZ
331 :require '(:user :secret)
332 :create t))))
b8e0f0cd 333 (if found
c13bc26b
LI
334 (list (plist-get found :user)
335 (let ((secret (plist-get found :secret)))
336 (if (functionp secret)
337 (funcall secret)
733afdf4
TZ
338 secret))
339 (plist-get found :save-function))
b8e0f0cd 340 nil)))
286c4fc2 341
61b1af82
G
342(defun nnimap-keepalive ()
343 (let ((now (current-time)))
344 (dolist (buffer nnimap-process-buffers)
345 (when (buffer-name buffer)
346 (with-current-buffer buffer
347 (when (and nnimap-object
348 (nnimap-last-command-time nnimap-object)
2b1e1ff4 349 (> (gnus-float-time
61b1af82
G
350 (time-subtract
351 now
352 (nnimap-last-command-time nnimap-object)))
353 ;; More than five minutes since the last command.
354 (* 5 60)))
ef821434
SM
355 (ignore-errors ;E.g. "buffer foo has no process".
356 (nnimap-send-command "NOOP"))))))))
61b1af82 357
20a673b2 358(defun nnimap-open-connection (buffer)
ed797193
G
359 ;; Be backwards-compatible -- the earlier value of nnimap-stream was
360 ;; `ssl' when nnimap-server-port was nil. Sort of.
361 (when (and nnimap-server-port
362 (eq nnimap-stream 'undecided))
363 (setq nnimap-stream 'ssl))
364 (let ((stream
365 (if (eq nnimap-stream 'undecided)
e742e117 366 (loop for type in '(ssl network)
ed797193
G
367 for stream = (let ((nnimap-stream type))
368 (nnimap-open-connection-1 buffer))
369 while (eq stream 'no-connect)
370 finally (return stream))
371 (nnimap-open-connection-1 buffer))))
372 (if (eq stream 'no-connect)
373 nil
374 stream)))
375
a5166359
LMI
376(defun nnimap-map-port (port)
377 (if (equal port "imaps")
378 "993"
379 port))
380
ed797193 381(defun nnimap-open-connection-1 (buffer)
61b1af82
G
382 (unless nnimap-keepalive-timer
383 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
ef821434 384 #'nnimap-keepalive)))
ed797193
G
385 (with-current-buffer (nnimap-make-process-buffer buffer)
386 (let* ((coding-system-for-read 'binary)
387 (coding-system-for-write 'binary)
ed797193 388 (ports
dab0271f 389 (cond
e742e117 390 ((memq nnimap-stream '(network plain starttls))
ed797193
G
391 (nnheader-message 7 "Opening connection to %s..."
392 nnimap-address)
003522ce 393 '("imap" "143"))
ed797193
G
394 ((eq nnimap-stream 'shell)
395 (nnheader-message 7 "Opening connection to %s via shell..."
396 nnimap-address)
397 '("imap"))
398 ((memq nnimap-stream '(ssl tls))
399 (nnheader-message 7 "Opening connection to %s via tls..."
400 nnimap-address)
003522ce 401 '("imaps" "imap" "993" "143"))
ed797193
G
402 (t
403 (error "Unknown stream type: %s" nnimap-stream))))
ed797193
G
404 login-result credentials)
405 (when nnimap-server-port
003522ce 406 (push nnimap-server-port ports))
f2eefd24
CY
407 (let* ((stream-list
408 (open-protocol-stream
a5166359
LMI
409 "*nnimap*" (current-buffer) nnimap-address
410 (nnimap-map-port (car ports))
f2eefd24
CY
411 :type nnimap-stream
412 :return-list t
413 :shell-command nnimap-shell-program
414 :capability-command "1 CAPABILITY\r\n"
da91b5f2 415 :end-of-command "\r\n"
f2eefd24
CY
416 :success " OK "
417 :starttls-function
418 (lambda (capabilities)
419 (when (gnus-string-match-p "STARTTLS" capabilities)
420 "1 STARTTLS\r\n"))))
421 (stream (car stream-list))
422 (props (cdr stream-list))
423 (greeting (plist-get props :greeting))
424 (capabilities (plist-get props :capabilities))
425 (stream-type (plist-get props :type)))
426 (when (and stream (not (memq (process-status stream) '(open run))))
427 (setq stream nil))
3ccc1742
SM
428
429 (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
430 (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
431 (eq (process-type stream) 'network))
432 ;; Use TCP-keepalive so that connections that pass through a NAT
433 ;; router don't hang when left idle.
434 (set-network-process-option stream :keepalive t))
435
ed797193 436 (setf (nnimap-process nnimap-object) stream)
008cad90 437 (setf (nnimap-stream-type nnimap-object) stream-type)
ed797193
G
438 (if (not stream)
439 (progn
440 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
bc320087 441 nnimap-address (car ports) nnimap-stream)
ed797193
G
442 'no-connect)
443 (gnus-set-process-query-on-exit-flag stream nil)
444 (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
445 (nnheader-report 'nnimap "%s" greeting)
446 ;; Store the greeting (for debugging purposes).
447 (setf (nnimap-greeting nnimap-object) greeting)
448 (setf (nnimap-capabilities nnimap-object)
449 (mapcar #'upcase
450 (split-string capabilities)))
451 (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
9f2d52e7
G
452 (if (not (setq credentials
453 (if (eq nnimap-authenticator 'anonymous)
454 (list "anonymous"
455 (message-make-address))
b8e0f0cd
G
456 ;; Look for the credentials based on
457 ;; the virtual server name and the address
458 (nnimap-credentials
7ba93e94
G
459 (gnus-delete-duplicates
460 (list
0bdb7b45
TZ
461 (nnoo-current-server 'nnimap)
462 nnimap-address))
5e68f861
TZ
463 ports
464 nnimap-user))))
9f2d52e7 465 (setq nnimap-object nil)
d5e9a4e9
LI
466 (let ((nnimap-inhibit-logging t))
467 (setq login-result
468 (nnimap-login (car credentials) (cadr credentials))))
733afdf4 469 (if (car login-result)
a5954fa5 470 (progn
b534ed40
LMI
471 ;; Save the credentials if a save function exists
472 ;; (such a function will only be passed if a new
473 ;; token was created).
a5954fa5
G
474 (when (functionp (nth 2 credentials))
475 (funcall (nth 2 credentials)))
476 ;; See if CAPABILITY is set as part of login
477 ;; response.
478 (dolist (response (cddr login-result))
479 (when (string= "CAPABILITY" (upcase (car response)))
480 (setf (nnimap-capabilities nnimap-object)
481 (mapcar #'upcase (cdr response))))))
9f2d52e7
G
482 ;; If the login failed, then forget the credentials
483 ;; that are now possibly cached.
484 (dolist (host (list (nnoo-current-server 'nnimap)
485 nnimap-address))
486 (dolist (port ports)
35123c04 487 (auth-source-forget+ :host host :port port)))
9f2d52e7
G
488 (delete-process (nnimap-process nnimap-object))
489 (setq nnimap-object nil))))
490 (when nnimap-object
389b76fa 491 (when (nnimap-capability "QRESYNC")
9f2d52e7 492 (nnimap-command "ENABLE QRESYNC"))
c8f8221f
SM
493 (nnheader-message 7 "Opening connection to %s...done"
494 nnimap-address)
6b958814
G
495 (nnimap-process nnimap-object))))))))
496
84d89ede
LMI
497(autoload 'rfc2104-hash "rfc2104")
498
499(defun nnimap-login (user password)
500 (cond
008cad90
G
501 ;; Prefer plain LOGIN if it's enabled (since it requires fewer
502 ;; round trips than CRAM-MD5, and it's less likely to be buggy),
503 ;; and we're using an encrypted connection.
504 ((and (not (nnimap-capability "LOGINDISABLED"))
45dd6480
LI
505 (eq (nnimap-stream-type nnimap-object) 'tls)
506 (or (null nnimap-authenticator)
507 (eq nnimap-authenticator 'login)))
008cad90 508 (nnimap-command "LOGIN %S %S" user password))
45dd6480
LI
509 ((and (nnimap-capability "AUTH=CRAM-MD5")
510 (or (null nnimap-authenticator)
511 (eq nnimap-authenticator 'cram-md5)))
84d89ede
LMI
512 (erase-buffer)
513 (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
514 (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
515 (process-send-string
516 (get-buffer-process (current-buffer))
517 (concat
518 (base64-encode-string
519 (concat user " "
520 (rfc2104-hash 'md5 64 16 password
521 (base64-decode-string challenge))))
522 "\r\n"))
523 (nnimap-wait-for-response sequence)))
45dd6480
LI
524 ((and (not (nnimap-capability "LOGINDISABLED"))
525 (or (null nnimap-authenticator)
526 (eq nnimap-authenticator 'login)))
84d89ede 527 (nnimap-command "LOGIN %S %S" user password))
45dd6480
LI
528 ((and (nnimap-capability "AUTH=PLAIN")
529 (or (null nnimap-authenticator)
530 (eq nnimap-authenticator 'plain)))
84d89ede
LMI
531 (nnimap-command
532 "AUTHENTICATE PLAIN %s"
533 (base64-encode-string
534 (format "\000%s\000%s"
535 (nnimap-quote-specials user)
536 (nnimap-quote-specials password)))))))
537
99e65b2d
G
538(defun nnimap-quote-specials (string)
539 (with-temp-buffer
540 (insert string)
541 (goto-char (point-min))
542 (while (re-search-forward "[\\\"]" nil t)
543 (forward-char -1)
544 (insert "\\")
545 (forward-char 1))
546 (buffer-string)))
547
20a673b2
KY
548(defun nnimap-find-parameter (parameter elems)
549 (let (result)
550 (dolist (elem elems)
551 (cond
552 ((equal (car elem) parameter)
553 (setq result (cdr elem)))
554 ((and (equal (car elem) "OK")
555 (consp (cadr elem))
556 (equal (caadr elem) parameter))
557 (setq result (cdr (cadr elem))))))
558 result))
559
286c4fc2 560(deffoo nnimap-close-server (&optional server)
71e691a5
G
561 (when (nnoo-change-server 'nnimap server nil)
562 (ignore-errors
563 (delete-process (get-buffer-process (nnimap-buffer))))
d1090fe8 564 (nnoo-close-server 'nnimap server)
71e691a5 565 t))
c113de23 566
286c4fc2 567(deffoo nnimap-request-close ()
20a673b2 568 t)
23f87bed 569
286c4fc2 570(deffoo nnimap-server-opened (&optional server)
20a673b2
KY
571 (and (nnoo-current-server-p 'nnimap server)
572 nntp-server-buffer
573 (gnus-buffer-live-p nntp-server-buffer)
574 (nnimap-find-connection nntp-server-buffer)))
c113de23 575
286c4fc2 576(deffoo nnimap-status-message (&optional server)
20a673b2 577 nnimap-status-string)
c113de23 578
286c4fc2 579(deffoo nnimap-request-article (article &optional group server to-buffer)
e21bac42
G
580 (when group
581 (setq group (nnimap-decode-gnus-group group)))
c113de23 582 (with-current-buffer nntp-server-buffer
eaa610c3 583 (let ((result (nnimap-change-group group server))
8ccbef23 584 parts structure)
20a673b2 585 (when (stringp article)
eaa610c3 586 (setq article (nnimap-find-article-by-message-id group server article)))
20a673b2
KY
587 (when (and result
588 article)
589 (erase-buffer)
590 (with-current-buffer (nnimap-buffer)
591 (erase-buffer)
9f2d52e7
G
592 (when nnimap-fetch-partial-articles
593 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
594 (goto-char (point-min))
595 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
229b59da
G
596 (setq structure (ignore-errors
597 (let ((start (point)))
598 (forward-sexp 1)
599 (downcase-region start (point))
9d1bf25d 600 (goto-char start)
229b59da 601 (read (current-buffer))))
9f2d52e7 602 parts (nnimap-find-wanted-parts structure))))
8ccbef23
G
603 (when (if parts
604 (nnimap-get-partial-article article parts structure)
605 (nnimap-get-whole-article article))
606 (let ((buffer (current-buffer)))
607 (with-current-buffer (or to-buffer nntp-server-buffer)
9f5e78f7 608 (nnheader-insert-buffer-substring buffer)
b87f32fc
G
609 (nnheader-ms-strip-cr)))
610 (cons group article)))))))
8ccbef23 611
b5c575e6 612(deffoo nnimap-request-head (article &optional group server to-buffer)
e21bac42
G
613 (when group
614 (setq group (nnimap-decode-gnus-group group)))
eaa610c3 615 (when (nnimap-change-group group server)
b5c575e6
G
616 (with-current-buffer (nnimap-buffer)
617 (when (stringp article)
eaa610c3 618 (setq article (nnimap-find-article-by-message-id group server article)))
228724bc
LI
619 (if (null article)
620 nil
621 (nnimap-get-whole-article
622 article (format "UID FETCH %%d %s"
623 (nnimap-header-parameters)))
624 (let ((buffer (current-buffer)))
625 (with-current-buffer (or to-buffer nntp-server-buffer)
626 (erase-buffer)
627 (insert-buffer-substring buffer)
628 (nnheader-ms-strip-cr)
629 (cons group article)))))))
b5c575e6
G
630
631(defun nnimap-get-whole-article (article &optional command)
8ccbef23
G
632 (let ((result
633 (nnimap-command
b5c575e6
G
634 (or command
635 (if (nnimap-ver4-p)
636 "UID FETCH %d BODY.PEEK[]"
637 "UID FETCH %d RFC822.PEEK"))
8ccbef23
G
638 article)))
639 ;; Check that we really got an article.
640 (goto-char (point-min))
4478e074 641 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
8ccbef23
G
642 (setq result nil))
643 (when result
4478e074
G
644 ;; Remove any data that may have arrived before the FETCH data.
645 (beginning-of-line)
646 (unless (bobp)
647 (delete-region (point-min) (point)))
8ccbef23
G
648 (let ((bytes (nnimap-get-length)))
649 (delete-region (line-beginning-position)
650 (progn (forward-line 1) (point)))
651 (goto-char (+ (point) bytes))
652 (delete-region (point) (point-max)))
653 t)))
654
389b76fa
G
655(defun nnimap-capability (capability)
656 (member capability (nnimap-capabilities nnimap-object)))
657
8ccbef23 658(defun nnimap-ver4-p ()
389b76fa 659 (nnimap-capability "IMAP4REV1"))
8ccbef23
G
660
661(defun nnimap-get-partial-article (article parts structure)
662 (let ((result
663 (nnimap-command
664 "UID FETCH %d (%s %s)"
665 article
666 (if (nnimap-ver4-p)
667 "BODY.PEEK[HEADER]"
668 "RFC822.HEADER")
669 (if (nnimap-ver4-p)
670 (mapconcat (lambda (part)
671 (format "BODY.PEEK[%s]" part))
672 parts " ")
673 (mapconcat (lambda (part)
674 (format "RFC822.PEEK[%s]" part))
675 parts " ")))))
676 (when result
677 (nnimap-convert-partial-article structure))))
678
679(defun nnimap-convert-partial-article (structure)
680 ;; First just skip past the headers.
681 (goto-char (point-min))
682 (let ((bytes (nnimap-get-length))
683 id parts)
684 ;; Delete "FETCH" line.
685 (delete-region (line-beginning-position)
686 (progn (forward-line 1) (point)))
687 (goto-char (+ (point) bytes))
688 ;; Collect all the body parts.
689 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
690 (setq id (match-string 1)
c516cd6d 691 bytes (or (nnimap-get-length) 0))
8ccbef23
G
692 (beginning-of-line)
693 (delete-region (point) (progn (forward-line 1) (point)))
694 (push (list id (buffer-substring (point) (+ (point) bytes)))
695 parts)
696 (delete-region (point) (+ (point) bytes)))
697 ;; Delete trailing junk.
698 (delete-region (point) (point-max))
699 ;; Now insert all the parts again where they fit in the structure.
700 (nnimap-insert-partial-structure structure parts)
701 t))
702
703(defun nnimap-insert-partial-structure (structure parts &optional subp)
229b59da
G
704 (let (type boundary)
705 (let ((bstruc structure))
706 (while (consp (car bstruc))
707 (pop bstruc))
708 (setq type (car bstruc))
709 (setq bstruc (car (cdr bstruc)))
2526f423
G
710 (let ((has-boundary (member "boundary" bstruc)))
711 (when has-boundary
712 (setq boundary (cadr has-boundary)))))
8ccbef23
G
713 (when subp
714 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
715 (downcase type) boundary)))
716 (while (not (stringp (car structure)))
717 (insert "\n--" boundary "\n")
718 (if (consp (caar structure))
719 (nnimap-insert-partial-structure (pop structure) parts t)
720 (let ((bit (pop structure)))
943399bc
LMI
721 (insert (format "Content-type: %s/%s"
722 (downcase (nth 0 bit))
723 (downcase (nth 1 bit))))
724 (if (member-ignore-case "CHARSET" (nth 2 bit))
8ccbef23 725 (insert (format
943399bc
LMI
726 "; charset=%S\n"
727 (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
8ccbef23
G
728 (insert "\n"))
729 (insert (format "Content-transfer-encoding: %s\n"
730 (nth 5 bit)))
731 (insert "\n")
732 (when (assoc (nth 9 bit) parts)
733 (insert (cadr (assoc (nth 9 bit) parts)))))))
734 (insert "\n--" boundary "--\n")))
bdaa75c7
LMI
735
736(defun nnimap-find-wanted-parts (structure)
737 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
738
739(defun nnimap-find-wanted-parts-1 (structure prefix)
740 (let ((num 1)
741 parts)
742 (while (consp (car structure))
743 (let ((sub (pop structure)))
744 (if (consp (car sub))
745 (push (nnimap-find-wanted-parts-1
746 sub (if (string= prefix "")
747 (number-to-string num)
748 (format "%s.%s" prefix num)))
749 parts)
8ccbef23
G
750 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
751 (id (if (string= prefix "")
bdaa75c7 752 (number-to-string num)
8ccbef23
G
753 (format "%s.%s" prefix num))))
754 (setcar (nthcdr 9 sub) id)
9f2d52e7
G
755 (when (if (eq nnimap-fetch-partial-articles t)
756 (equal id "1")
757 (string-match nnimap-fetch-partial-articles type))
8ccbef23
G
758 (push id parts))))
759 (incf num)))
bdaa75c7 760 (nreverse parts)))
20a673b2 761
e21bac42
G
762(defun nnimap-decode-gnus-group (group)
763 (decode-coding-string group 'utf-8))
764
286c4fc2 765(deffoo nnimap-request-group (group &optional server dont-check info)
e21bac42 766 (setq group (nnimap-decode-gnus-group group))
eaa610c3 767 (let ((result (nnimap-change-group
7cad71ad
G
768 ;; Don't SELECT the group if we're going to select it
769 ;; later, anyway.
bb7f5cbc 770 (if (and (not dont-check)
9310f19d 771 (assoc group nnimap-current-infos))
7cad71ad
G
772 nil
773 group)
774 server))
a46359d4
LMI
775 articles active marks high low)
776 (with-current-buffer nntp-server-buffer
20a673b2 777 (when result
286c4fc2
LMI
778 (if (and dont-check
779 (setq active (nth 2 (assoc group nnimap-current-infos))))
780 (insert (format "211 %d %d %d %S\n"
781 (- (cdr active) (car active))
782 (car active)
783 (cdr active)
784 group))
785 (with-current-buffer (nnimap-buffer)
786 (erase-buffer)
787 (let ((group-sequence
0617bb00 788 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
286c4fc2
LMI
789 (flag-sequence
790 (nnimap-send-command "UID FETCH 1:* FLAGS")))
7cad71ad 791 (setf (nnimap-group nnimap-object) group)
286c4fc2
LMI
792 (nnimap-wait-for-response flag-sequence)
793 (setq marks
794 (nnimap-flags-to-marks
795 (nnimap-parse-flags
f7aa248a
G
796 (list (list group-sequence flag-sequence
797 1 group "SELECT")))))
798 (when (and info
799 marks)
9310f19d
LMI
800 (nnimap-update-infos marks (list info))
801 (nnimap-store-info info (gnus-active (gnus-info-group info))))
286c4fc2 802 (goto-char (point-max))
b1ae92ba 803 (let ((uidnext (nth 5 (car marks))))
a3f57c41
G
804 (setq high (or (if uidnext
805 (1- uidnext)
806 (nth 3 (car marks)))
807 0)
808 low (or (nth 4 (car marks)) uidnext 1)))))
286c4fc2
LMI
809 (erase-buffer)
810 (insert
811 (format
0617bb00
LMI
812 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
813 t))))
814
815(deffoo nnimap-request-create-group (group &optional server args)
e21bac42 816 (setq group (nnimap-decode-gnus-group group))
eaa610c3 817 (when (nnimap-change-group nil server)
0617bb00
LMI
818 (with-current-buffer (nnimap-buffer)
819 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
c113de23 820
a46359d4 821(deffoo nnimap-request-delete-group (group &optional force server)
e21bac42 822 (setq group (nnimap-decode-gnus-group group))
eaa610c3 823 (when (nnimap-change-group nil server)
a46359d4 824 (with-current-buffer (nnimap-buffer)
0617bb00
LMI
825 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
826
a7dcc87b 827(deffoo nnimap-request-rename-group (group new-name &optional server)
e21bac42 828 (setq group (nnimap-decode-gnus-group group))
eaa610c3 829 (when (nnimap-change-group nil server)
a7dcc87b 830 (with-current-buffer (nnimap-buffer)
e39a5583 831 (nnimap-unselect-group)
f7aa248a
G
832 (car (nnimap-command "RENAME %S %S"
833 (utf7-encode group t) (utf7-encode new-name t))))))
a7dcc87b 834
e39a5583
LMI
835(defun nnimap-unselect-group ()
836 ;; Make sure we don't have this group open read/write by asking
837 ;; to examine a mailbox that doesn't exist. This seems to be
838 ;; the only way that allows us to reliably go back to unselected
839 ;; state on Courier.
840 (nnimap-command "EXAMINE DOES.NOT.EXIST"))
841
0617bb00 842(deffoo nnimap-request-expunge-group (group &optional server)
e21bac42 843 (setq group (nnimap-decode-gnus-group group))
eaa610c3 844 (when (nnimap-change-group group server)
0617bb00
LMI
845 (with-current-buffer (nnimap-buffer)
846 (car (nnimap-command "EXPUNGE")))))
a46359d4 847
20a673b2
KY
848(defun nnimap-get-flags (spec)
849 (let ((articles nil)
f7aa248a 850 elems end)
20a673b2 851 (with-current-buffer (nnimap-buffer)
c113de23 852 (erase-buffer)
20a673b2
KY
853 (nnimap-wait-for-response (nnimap-send-command
854 "UID FETCH %s FLAGS" spec))
f7aa248a
G
855 (setq end (point))
856 (subst-char-in-region (point-min) (point-max)
857 ?\\ ?% t)
20a673b2 858 (goto-char (point-min))
f7aa248a
G
859 (while (search-forward " FETCH " end t)
860 (setq elems (read (current-buffer)))
861 (push (cons (cadr (memq 'UID elems))
862 (cadr (memq 'FLAGS elems)))
20a673b2
KY
863 articles)))
864 (nreverse articles)))
a1506d29 865
286c4fc2 866(deffoo nnimap-close-group (group &optional server)
20a673b2 867 t)
c113de23 868
01c52d31 869(deffoo nnimap-request-move-article (article group server accept-form
20a673b2 870 &optional last internal-move-group)
e21bac42 871 (setq group (nnimap-decode-gnus-group group))
eaa610c3
KY
872 (when internal-move-group
873 (setq internal-move-group (nnimap-decode-gnus-group internal-move-group)))
0617bb00 874 (with-temp-buffer
a04f9e26 875 (mm-disable-multibyte)
b5c575e6
G
876 (when (funcall (if internal-move-group
877 'nnimap-request-head
878 'nnimap-request-article)
879 article group server (current-buffer))
0617bb00
LMI
880 ;; If the move is internal (on the same server), just do it the easy
881 ;; way.
882 (let ((message-id (message-field-value "message-id")))
883 (if internal-move-group
884 (let ((result
885 (with-current-buffer (nnimap-buffer)
886 (nnimap-command "UID COPY %d %S"
887 article
888 (utf7-encode internal-move-group t)))))
889 (when (car result)
a46359d4 890 (nnimap-delete-article article)
0617bb00 891 (cons internal-move-group
cccb4b4c
LMI
892 (or (nnimap-find-uid-response "COPYUID" (cadr result))
893 (nnimap-find-article-by-message-id
eaa610c3
KY
894 internal-move-group server message-id
895 nnimap-request-articles-find-limit)))))
0617bb00
LMI
896 ;; Move the article to a different method.
897 (let ((result (eval accept-form)))
898 (when result
eaa610c3 899 (nnimap-change-group group server)
0617bb00
LMI
900 (nnimap-delete-article article)
901 result)))))))
20a673b2
KY
902
903(deffoo nnimap-request-expire-articles (articles group &optional server force)
e21bac42 904 (setq group (nnimap-decode-gnus-group group))
20a673b2 905 (cond
0617bb00
LMI
906 ((null articles)
907 nil)
eaa610c3 908 ((not (nnimap-change-group group server))
20a673b2 909 articles)
0617bb00
LMI
910 ((and force
911 (eq nnmail-expiry-target 'delete))
4478e074 912 (unless (nnimap-delete-article (gnus-compress-sequence articles))
283f7b93 913 (nnheader-message 7 "Article marked for deletion, but not expunged."))
20a673b2
KY
914 nil)
915 (t
0617bb00 916 (let ((deletable-articles
b069e5a6
G
917 (if (or force
918 (eq nnmail-expiry-wait 'immediate))
0617bb00
LMI
919 articles
920 (gnus-sorted-intersection
921 articles
922 (nnimap-find-expired-articles group)))))
923 (if (null deletable-articles)
924 articles
925 (if (eq nnmail-expiry-target 'delete)
4478e074 926 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
0617bb00
LMI
927 (setq deletable-articles
928 (nnimap-process-expiry-targets
929 deletable-articles group server)))
930 ;; Return the articles we didn't delete.
931 (gnus-sorted-complement articles deletable-articles))))))
932
933(defun nnimap-process-expiry-targets (articles group server)
934 (let ((deleted-articles nil))
04db63bc
G
935 (cond
936 ;; shortcut further processing if we're going to delete the articles
937 ((eq nnmail-expiry-target 'delete)
938 (setq deleted-articles articles)
939 t)
940 ;; or just move them to another folder on the same IMAP server
941 ((and (not (functionp nnmail-expiry-target))
942 (gnus-server-equal (gnus-group-method nnmail-expiry-target)
943 (gnus-server-to-method
944 (format "nnimap:%s" server))))
eaa610c3 945 (and (nnimap-change-group group server)
04db63bc
G
946 (with-current-buffer (nnimap-buffer)
947 (nnheader-message 7 "Expiring articles from %s: %s" group articles)
948 (nnimap-command
949 "UID COPY %s %S"
950 (nnimap-article-ranges (gnus-compress-sequence articles))
951 (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
952 (setq deleted-articles articles)))
953 t)
954 (t
955 (dolist (article articles)
956 (let ((target nnmail-expiry-target))
957 (with-temp-buffer
958 (mm-disable-multibyte)
959 (when (nnimap-request-article article group server (current-buffer))
04db63bc
G
960 (when (functionp target)
961 (setq target (funcall target group)))
d0b36cbe
LMI
962 (if (and target
963 (not (eq target 'delete)))
964 (if (or (gnus-request-group target t)
965 (gnus-request-create-group target))
966 (progn
967 (nnmail-expiry-target-group target group)
968 (nnheader-message 7 "Expiring article %s:%d to %s"
969 group article target))
970 (setq target nil))
971 (nnheader-message 7 "Expiring article %s:%d" group article))
04db63bc
G
972 (when target
973 (push article deleted-articles))))))))
0617bb00 974 ;; Change back to the current group again.
eaa610c3 975 (nnimap-change-group group server)
0617bb00 976 (setq deleted-articles (nreverse deleted-articles))
4478e074 977 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
0617bb00
LMI
978 deleted-articles))
979
980(defun nnimap-find-expired-articles (group)
981 (let ((cutoff (nnmail-expired-article-p group nil nil)))
982 (with-current-buffer (nnimap-buffer)
983 (let ((result
984 (nnimap-command
985 "UID SEARCH SENTBEFORE %s"
986 (format-time-string
987 (format "%%d-%s-%%Y"
988 (upcase
989 (car (rassoc (nth 4 (decode-time cutoff))
990 parse-time-months))))
991 cutoff))))
992 (and (car result)
993 (delete 0 (mapcar #'string-to-number
994 (cdr (assoc "SEARCH" (cdr result))))))))))
995
20a673b2 996
eaa610c3
KY
997(defun nnimap-find-article-by-message-id (group server message-id
998 &optional limit)
999 "Search for message with MESSAGE-ID in GROUP from SERVER.
1000If LIMIT, first try to limit the search to the N last articles."
6b958814
G
1001 (with-current-buffer (nnimap-buffer)
1002 (erase-buffer)
eaa610c3
KY
1003 (let* ((change-group-result (nnimap-change-group group server nil t))
1004 (number-of-article
1005 (and (listp change-group-result)
1006 (catch 'found
1007 (dolist (result (cdr change-group-result))
1008 (when (equal "EXISTS" (cadr result))
1009 (throw 'found (car result)))))))
1010 (sequence
1011 (nnimap-send-command
1012 "UID SEARCH%s HEADER Message-Id %S"
1013 (if (and limit number-of-article)
1014 ;; The -1 is because IMAP message
1015 ;; numbers are one-based rather than
1016 ;; zero-based.
1017 (format " %s:*" (- (string-to-number number-of-article)
1018 limit -1))
1019 "")
1020 message-id)))
1021 (when (nnimap-wait-for-response sequence)
1022 (let ((article (car (last (cdr (assoc "SEARCH"
1023 (nnimap-parse-response)))))))
1024 (if article
1025 (string-to-number article)
1026 (when (and limit number-of-article)
1027 (nnimap-find-article-by-message-id group server message-id))))))))
20a673b2
KY
1028
1029(defun nnimap-delete-article (articles)
1030 (with-current-buffer (nnimap-buffer)
1031 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
1032 (nnimap-article-ranges articles))
0617bb00 1033 (cond
389b76fa 1034 ((nnimap-capability "UIDPLUS")
0617bb00
LMI
1035 (nnimap-command "UID EXPUNGE %s"
1036 (nnimap-article-ranges articles))
1037 t)
1038 (nnimap-expunge
1039 (nnimap-command "EXPUNGE")
7390c1cd
TZ
1040 t)
1041 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
1042 "server doesn't support UIDPLUS, so we won't "
1043 "delete this article now"))))))
20a673b2
KY
1044
1045(deffoo nnimap-request-scan (&optional group server)
e21bac42
G
1046 (when group
1047 (setq group (nnimap-decode-gnus-group group)))
eaa610c3 1048 (when (and (nnimap-change-group nil server)
20a673b2
KY
1049 nnimap-inbox
1050 nnimap-split-methods)
283f7b93 1051 (nnheader-message 7 "nnimap %s splitting mail..." server)
eaa610c3
KY
1052 (if (listp nnimap-inbox)
1053 (dolist (nnimap-inbox nnimap-inbox)
1054 (nnimap-split-incoming-mail))
1055 (nnimap-split-incoming-mail))
4d19331f 1056 (nnheader-message 7 "nnimap %s splitting mail...done" server)))
20a673b2
KY
1057
1058(defun nnimap-marks-to-flags (marks)
1059 (let (flags flag)
1060 (dolist (mark marks)
1061 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1062 (push flag flags)))
1063 flags))
1064
549c9aed 1065(deffoo nnimap-request-update-group-status (group status &optional server)
e21bac42 1066 (setq group (nnimap-decode-gnus-group group))
eaa610c3 1067 (when (nnimap-change-group nil server)
549c9aed
G
1068 (let ((command (assoc
1069 status
1070 '((subscribe "SUBSCRIBE")
1071 (unsubscribe "UNSUBSCRIBE")))))
1072 (when command
1073 (with-current-buffer (nnimap-buffer)
1074 (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1075
286c4fc2 1076(deffoo nnimap-request-set-mark (group actions &optional server)
e21bac42 1077 (setq group (nnimap-decode-gnus-group group))
eaa610c3 1078 (when (nnimap-change-group group server)
20a673b2
KY
1079 (let (sequence)
1080 (with-current-buffer (nnimap-buffer)
229b59da 1081 (erase-buffer)
20a673b2
KY
1082 ;; Just send all the STORE commands without waiting for
1083 ;; response. If they're successful, they're successful.
1084 (dolist (action actions)
1085 (destructuring-bind (range action marks) action
1086 (let ((flags (nnimap-marks-to-flags marks)))
1087 (when flags
1088 (setq sequence (nnimap-send-command
1089 "UID STORE %s %sFLAGS.SILENT (%s)"
1090 (nnimap-article-ranges range)
5f285722
LMI
1091 (cond
1092 ((eq action 'del) "-")
57cc52be 1093 ((eq action 'add) "+")
5f285722 1094 ((eq action 'set) ""))
20a673b2
KY
1095 (mapconcat #'identity flags " ")))))))
1096 ;; Wait for the last command to complete to avoid later
e1dbe924 1097 ;; synchronization problems with the stream.
a46359d4
LMI
1098 (when sequence
1099 (nnimap-wait-for-response sequence))))))
a1506d29 1100
c113de23 1101(deffoo nnimap-request-accept-article (group &optional server last)
e21bac42 1102 (setq group (nnimap-decode-gnus-group group))
eaa610c3 1103 (when (nnimap-change-group nil server)
20a673b2 1104 (nnmail-check-syntax)
6b958814
G
1105 (let ((message-id (message-field-value "message-id"))
1106 sequence message)
1107 (nnimap-add-cr)
728fd3b9 1108 (setq message (buffer-substring-no-properties (point-min) (point-max)))
20a673b2 1109 (with-current-buffer (nnimap-buffer)
114fe546
G
1110 (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1111 message))
41d579ce
LI
1112 ;; If we have this group open read-only, then unselect it
1113 ;; before appending to it.
1114 (when (equal (nnimap-examined nnimap-object) group)
1115 (nnimap-unselect-group))
1116 (erase-buffer)
1117 (setq sequence (nnimap-send-command
1118 "APPEND %S {%d}" (utf7-encode group t)
1119 (length message)))
1120 (unless nnimap-streaming
1121 (nnimap-wait-for-connection "^[+]"))
1122 (process-send-string (get-buffer-process (current-buffer)) message)
1123 (process-send-string (get-buffer-process (current-buffer))
1124 (if (nnimap-newlinep nnimap-object)
1125 "\n"
1126 "\r\n"))
1127 (let ((result (nnimap-get-response sequence)))
1128 (if (not (nnimap-ok-p result))
1129 (progn
1130 (nnheader-report 'nnimap "%s" result)
1131 nil)
1132 (cons group
1133 (or (nnimap-find-uid-response "APPENDUID" (car result))
1134 (nnimap-find-article-by-message-id
eaa610c3
KY
1135 group server message-id
1136 nnimap-request-articles-find-limit))))))))))
41d579ce
LI
1137
1138(defun nnimap-process-quirk (greeting-match type data)
1139 (when (and (nnimap-greeting nnimap-object)
114fe546 1140 (string-match greeting-match (nnimap-greeting nnimap-object))
41d579ce
LI
1141 (eq type 'append)
1142 (string-match "\000" data))
1143 (let ((choice (gnus-multiple-choice
1144 "Message contains NUL characters. Delete, continue, abort? "
1145 '((?d "Delete NUL characters")
1146 (?c "Try to APPEND the message as is")
1147 (?a "Abort")))))
1148 (cond
1149 ((eq choice ?a)
1150 (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1151 ((eq choice ?c)
1152 data)
1153 (t
1154 (with-temp-buffer
1155 (insert data)
1156 (goto-char (point-min))
1157 (while (search-forward "\000" nil t)
1158 (replace-match "" t t))
1159 (buffer-string)))))))
cccb4b4c 1160
0d1c2cc8
G
1161(defun nnimap-ok-p (value)
1162 (and (consp value)
1163 (consp (car value))
1164 (equal (caar value) "OK")))
1165
cccb4b4c 1166(defun nnimap-find-uid-response (name list)
17dd2281 1167 (let ((result (car (last (nnimap-find-response-element name list)))))
cccb4b4c
LMI
1168 (and result
1169 (string-to-number result))))
1170
1171(defun nnimap-find-response-element (name list)
1172 (let (result)
1173 (dolist (elem list)
1174 (when (and (consp elem)
1175 (equal name (car elem)))
1176 (setq result elem)))
1177 result))
20a673b2 1178
728fd3b9 1179(deffoo nnimap-request-replace-article (article group buffer)
e21bac42 1180 (setq group (nnimap-decode-gnus-group group))
728fd3b9 1181 (let (group-art)
eaa610c3 1182 (when (and (nnimap-change-group group)
728fd3b9
LMI
1183 ;; Put the article into the group.
1184 (with-current-buffer buffer
1185 (setq group-art
1186 (nnimap-request-accept-article group nil t))))
1187 (nnimap-delete-article (list article))
1188 ;; Return the new article number.
1189 (cdr group-art))))
1190
20a673b2
KY
1191(defun nnimap-add-cr ()
1192 (goto-char (point-min))
1193 (while (re-search-forward "\r?\n" nil t)
1194 (replace-match "\r\n" t t)))
1195
1196(defun nnimap-get-groups ()
cccb4b4c
LMI
1197 (erase-buffer)
1198 (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
20a673b2 1199 groups)
cccb4b4c
LMI
1200 (nnimap-wait-for-response sequence)
1201 (subst-char-in-region (point-min) (point-max)
1202 ?\\ ?% t)
1203 (goto-char (point-min))
1204 (nnimap-unfold-quoted-lines)
1205 (goto-char (point-min))
1206 (while (search-forward "* LIST " nil t)
1207 (let ((flags (read (current-buffer)))
1208 (separator (read (current-buffer)))
1209 (group (read (current-buffer))))
1210 (unless (member '%NoSelect flags)
bca46f6b
G
1211 (push (utf7-decode (if (stringp group)
1212 group
1213 (format "%s" group)) t)
36af6c65 1214 groups))))
cccb4b4c 1215 (nreverse groups)))
20a673b2 1216
eaa610c3
KY
1217(defun nnimap-get-responses (sequences)
1218 (let (responses)
1219 (dolist (sequence sequences)
1220 (goto-char (point-min))
1221 (when (re-search-forward (format "^%d " sequence) nil t)
1222 (push (list sequence (nnimap-parse-response))
1223 responses)))
1224 responses))
1225
286c4fc2 1226(deffoo nnimap-request-list (&optional server)
eaa610c3 1227 (when (nnimap-change-group nil server)
c13bc26b
LI
1228 (with-current-buffer nntp-server-buffer
1229 (erase-buffer)
1230 (let ((groups
1231 (with-current-buffer (nnimap-buffer)
1232 (nnimap-get-groups)))
1233 sequences responses)
1234 (when groups
1235 (with-current-buffer (nnimap-buffer)
1236 (setf (nnimap-group nnimap-object) nil)
1237 (dolist (group groups)
1238 (setf (nnimap-examined nnimap-object) group)
1239 (push (list (nnimap-send-command "EXAMINE %S"
1240 (utf7-encode group t))
1241 group)
1242 sequences))
1243 (nnimap-wait-for-response (caar sequences))
1244 (setq responses
1245 (nnimap-get-responses (mapcar #'car sequences))))
1246 (dolist (response responses)
1247 (let* ((sequence (car response))
1248 (response (cadr response))
75a4d9cc
LI
1249 (group (cadr (assoc sequence sequences)))
1250 (egroup (encode-coding-string group 'utf-8)))
c13bc26b
LI
1251 (when (and group
1252 (equal (caar response) "OK"))
1253 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1254 highest exists)
1255 (dolist (elem response)
1256 (when (equal (cadr elem) "EXISTS")
1257 (setq exists (string-to-number (car elem)))))
1258 (when uidnext
1259 (setq highest (1- (string-to-number (car uidnext)))))
1260 (cond
1261 ((null highest)
75a4d9cc 1262 (insert (format "%S 0 1 y\n" egroup)))
c13bc26b
LI
1263 ((zerop exists)
1264 ;; Empty group.
75a4d9cc 1265 (insert (format "%S %d %d y\n" egroup
c13bc26b
LI
1266 highest (1+ highest))))
1267 (t
1268 ;; Return the widest possible range.
75a4d9cc 1269 (insert (format "%S %d 1 y\n" egroup
c13bc26b
LI
1270 (or highest exists)))))))))
1271 t)))))
c113de23 1272
a3f57c41 1273(deffoo nnimap-request-newgroups (date &optional server)
eaa610c3 1274 (when (nnimap-change-group nil server)
c13bc26b
LI
1275 (with-current-buffer nntp-server-buffer
1276 (erase-buffer)
1277 (dolist (group (with-current-buffer (nnimap-buffer)
1278 (nnimap-get-groups)))
1279 (unless (assoc group nnimap-current-infos)
1280 ;; Insert dummy numbers here -- they don't matter.
75a4d9cc 1281 (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
c13bc26b 1282 t)))
a3f57c41 1283
286c4fc2 1284(deffoo nnimap-retrieve-group-data-early (server infos)
eaa610c3 1285 (when (and (nnimap-change-group nil server)
964646c4 1286 infos)
20a673b2 1287 (with-current-buffer (nnimap-buffer)
f7aa248a
G
1288 (erase-buffer)
1289 (setf (nnimap-group nnimap-object) nil)
b5235dd9 1290 (setf (nnimap-initial-resync nnimap-object) 0)
389b76fa 1291 (let ((qresyncp (nnimap-capability "QRESYNC"))
eaa610c3
KY
1292 params groups sequences active uidvalidity modseq group
1293 unexist)
20a673b2
KY
1294 ;; Go through the infos and gather the data needed to know
1295 ;; what and how to request the data.
1296 (dolist (info infos)
f7aa248a 1297 (setq params (gnus-info-params info)
e21bac42
G
1298 group (nnimap-decode-gnus-group
1299 (gnus-group-real-name (gnus-info-group info)))
f7aa248a 1300 active (cdr (assq 'active params))
eaa610c3 1301 unexist (assq 'unexist (gnus-info-marks info))
f7aa248a
G
1302 uidvalidity (cdr (assq 'uidvalidity params))
1303 modseq (cdr (assq 'modseq params)))
e39a5583 1304 (setf (nnimap-examined nnimap-object) group)
20a673b2 1305 (if (and qresyncp
f7aa248a 1306 uidvalidity
4a3988d5 1307 active
eaa610c3
KY
1308 modseq
1309 unexist)
20a673b2 1310 (push
549c9aed 1311 (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
dab0271f 1312 (utf7-encode group t)
549c9aed 1313 (nnimap-quirk "QRESYNC")
dab0271f 1314 uidvalidity modseq)
f7aa248a
G
1315 'qresync
1316 nil group 'qresync)
20a673b2 1317 sequences)
b7645a9d 1318 (let ((command
f7aa248a
G
1319 (if uidvalidity
1320 "EXAMINE"
1321 ;; If we don't have a UIDVALIDITY, then this is
1322 ;; the first time we've seen the group, so we
1323 ;; have to do a SELECT (which is slower than an
1324 ;; examine), but will tell us whether the group
1325 ;; is read-only or not.
b7645a9d
LI
1326 "SELECT"))
1327 start)
eaa610c3 1328 (if (and active uidvalidity unexist)
b7645a9d
LI
1329 ;; Fetch the last 100 flags.
1330 (setq start (max 1 (- (cdr active) 100)))
eaa610c3 1331 (incf (nnimap-initial-resync nnimap-object))
b7645a9d 1332 (setq start 1))
dab0271f
G
1333 (push (list (nnimap-send-command "%s %S" command
1334 (utf7-encode group t))
20a673b2 1335 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
f7aa248a 1336 start group command)
b5c575e6 1337 sequences))))
20a673b2
KY
1338 sequences))))
1339
549c9aed
G
1340(defun nnimap-quirk (command)
1341 (let ((quirk (assoc command nnimap-quirks)))
1342 ;; If this server is of a type that matches a quirk, then return
1343 ;; the "quirked" command instead of the proper one.
1344 (if (or (null quirk)
1345 (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1346 command
1347 (nth 2 quirk))))
1348
286c4fc2 1349(deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
20a673b2 1350 (when (and sequences
eaa610c3 1351 (nnimap-change-group nil server t)
3451795c
LMI
1352 ;; Check that the process is still alive.
1353 (get-buffer-process (nnimap-buffer))
1354 (memq (process-status (get-buffer-process (nnimap-buffer)))
7e67562f 1355 '(open run)))
20a673b2
KY
1356 (with-current-buffer (nnimap-buffer)
1357 ;; Wait for the final data to trickle in.
f7aa248a
G
1358 (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1359 (caar sequences)
1360 (cadar sequences))
1361 t)
1362 ;; Now we should have most of the data we need, no matter
1363 ;; whether we're QRESYNCING, fetching all the flags from
1364 ;; scratch, or just fetching the last 100 flags per group.
8ccbef23
G
1365 (nnimap-update-infos (nnimap-flags-to-marks
1366 (nnimap-parse-flags
1367 (nreverse sequences)))
1368 infos)
1369 ;; Finally, just return something resembling an active file in
1370 ;; the nntp buffer, so that the agent can save the info, too.
1371 (with-current-buffer nntp-server-buffer
1372 (erase-buffer)
1373 (dolist (info infos)
1374 (let* ((group (gnus-info-group info))
1375 (active (gnus-active group)))
1376 (when active
1377 (insert (format "%S %d %d y\n"
e21bac42
G
1378 (decode-coding-string
1379 (gnus-group-real-name group) 'utf-8)
8ccbef23
G
1380 (cdr active)
1381 (car active)))))))))))
20a673b2
KY
1382
1383(defun nnimap-update-infos (flags infos)
1384 (dolist (info infos)
e21bac42
G
1385 (let* ((group (nnimap-decode-gnus-group
1386 (gnus-group-real-name (gnus-info-group info))))
f7aa248a
G
1387 (marks (cdr (assoc group flags))))
1388 (when marks
1389 (nnimap-update-info info marks)))))
20a673b2
KY
1390
1391(defun nnimap-update-info (info marks)
f7aa248a
G
1392 (destructuring-bind (existing flags high low uidnext start-article
1393 permanent-flags uidvalidity
1394 vanished highestmodseq) marks
1395 (cond
1396 ;; Ignore groups with no UIDNEXT/marks. This happens for
1397 ;; completely empty groups.
1398 ((and (not existing)
1399 (not uidnext))
dab0271f
G
1400 (let ((active (cdr (assq 'active (gnus-info-params info)))))
1401 (when active
1402 (gnus-set-active (gnus-info-group info) active))))
f7aa248a
G
1403 ;; We have a mismatch between the old and new UIDVALIDITY
1404 ;; identifiers, so we have to re-request the group info (the next
1405 ;; time). This virtually never happens.
1406 ((let ((old-uidvalidity
1407 (cdr (assq 'uidvalidity (gnus-info-params info)))))
1408 (and old-uidvalidity
1409 (not (equal old-uidvalidity uidvalidity))
7e67562f
G
1410 (or (not start-article)
1411 (> start-article 1))))
f7aa248a
G
1412 (gnus-group-remove-parameter info 'uidvalidity)
1413 (gnus-group-remove-parameter info 'modseq))
1414 ;; We have the data needed to update.
1415 (t
dab0271f
G
1416 (let* ((group (gnus-info-group info))
1417 (completep (and start-article
1418 (= start-article 1)))
1419 (active (or (gnus-active group)
1420 (cdr (assq 'active (gnus-info-params info))))))
b1ae92ba
G
1421 (when uidnext
1422 (setq high (1- uidnext)))
20a673b2
KY
1423 ;; First set the active ranges based on high/low.
1424 (if (or completep
1425 (not (gnus-active group)))
1426 (gnus-set-active group
61b1af82 1427 (cond
a7f6e5b9
LMI
1428 (active
1429 (cons (min (or low (car active))
1430 (car active))
1431 (max (or high (cdr active))
1432 (cdr active))))
61b1af82
G
1433 ((and low high)
1434 (cons low high))
1435 (uidnext
20a673b2 1436 ;; No articles in this group.
61b1af82
G
1437 (cons uidnext (1- uidnext)))
1438 (start-article
1439 (cons start-article (1- start-article)))
1440 (t
1441 ;; No articles and no uidnext.
1442 nil)))
41d579ce
LI
1443 (gnus-set-active group
1444 (cons (car active)
1445 (or high (1- uidnext)))))
f7aa248a
G
1446 ;; See whether this is a read-only group.
1447 (unless (eq permanent-flags 'not-scanned)
1448 (gnus-group-set-parameter
1449 info 'permanent-flags
7cad71ad
G
1450 (and (or (memq '%* permanent-flags)
1451 (memq '%Seen permanent-flags))
1452 permanent-flags)))
f7aa248a
G
1453 ;; Update marks and read articles if this isn't a
1454 ;; read-only IMAP group.
7cad71ad
G
1455 (when (setq permanent-flags
1456 (cdr (assq 'permanent-flags (gnus-info-params info))))
f7aa248a
G
1457 (if (and highestmodseq
1458 (not start-article))
1459 ;; We've gotten the data by QRESYNCing.
1460 (nnimap-update-qresync-info
dab0271f 1461 info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
f7aa248a
G
1462 ;; Do normal non-QRESYNC flag updates.
1463 ;; Update the list of read articles.
1464 (let* ((unread
1465 (gnus-compress-sequence
1466 (gnus-set-difference
1467 (gnus-set-difference
1468 existing
9d9ffa13
LMI
1469 (gnus-sorted-union
1470 (cdr (assoc '%Seen flags))
1471 (cdr (assoc '%Deleted flags))))
f7aa248a
G
1472 (cdr (assoc '%Flagged flags)))))
1473 (read (gnus-range-difference
1474 (cons start-article high) unread)))
1475 (when (> start-article 1)
1476 (setq read
1477 (gnus-range-nconcat
1478 (if (> start-article 1)
1479 (gnus-sorted-range-intersection
1480 (cons 1 (1- start-article))
1481 (gnus-info-read info))
1482 (gnus-info-read info))
1483 read)))
7cad71ad
G
1484 (when (or (not (listp permanent-flags))
1485 (memq '%Seen permanent-flags))
1486 (gnus-info-set-read info read))
f7aa248a
G
1487 ;; Update the marks.
1488 (setq marks (gnus-info-marks info))
1489 (dolist (type (cdr nnimap-mark-alist))
7cad71ad 1490 (when (or (not (listp permanent-flags))
1e961f10
KAH
1491 (memq (car (assoc (caddr type) flags))
1492 permanent-flags)
7cad71ad
G
1493 (memq '%* permanent-flags))
1494 (let ((old-marks (assoc (car type) marks))
1495 (new-marks
1496 (gnus-compress-sequence
1497 (cdr (or (assoc (caddr type) flags) ; %Flagged
1498 (assoc (intern (cadr type) obarray) flags)
1499 (assoc (cadr type) flags)))))) ; "\Flagged"
1500 (setq marks (delq old-marks marks))
1501 (pop old-marks)
1502 (when (and old-marks
1503 (> start-article 1))
1504 (setq old-marks (gnus-range-difference
1505 old-marks
1506 (cons start-article high)))
1507 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1508 (when new-marks
1509 (push (cons (car type) new-marks) marks)))))
eaa610c3
KY
1510 ;; Keep track of non-existing articles.
1511 (let* ((old-unexists (assq 'unexist marks))
1512 (active (gnus-active group))
1513 (unexists
1514 (if completep
1515 (gnus-range-difference
1516 active
1517 (gnus-compress-sequence existing))
1518 (gnus-add-to-range
1519 (cdr old-unexists)
1520 (gnus-list-range-difference
1521 existing (gnus-active group))))))
1522 (when (> (car active) 1)
1523 (setq unexists (gnus-range-add
1524 (cons 1 (1- (car active)))
1525 unexists)))
1526 (if old-unexists
1527 (setcdr old-unexists unexists)
1528 (push (cons 'unexist unexists) marks)))
7cad71ad 1529 (gnus-info-set-marks info marks t))))
41d579ce
LI
1530 ;; Tell Gnus whether there are any \Recent messages in any of
1531 ;; the groups.
1532 (let ((recent (cdr (assoc '%Recent flags))))
b52daf3d
LI
1533 (when (and active
1534 recent
1535 (> (car (last recent)) (cdr active)))
1536 (push (list (cons (gnus-group-real-name group) 0))
1537 nnmail-split-history)))
f7aa248a
G
1538 ;; Note the active level for the next run-through.
1539 (gnus-group-set-parameter info 'active (gnus-active group))
1540 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1541 (gnus-group-set-parameter info 'modseq highestmodseq)
1542 (nnimap-store-info info (gnus-active group)))))))
1543
dab0271f 1544(defun nnimap-update-qresync-info (info existing vanished flags)
f7aa248a
G
1545 ;; Add all the vanished articles to the list of read articles.
1546 (gnus-info-set-read
1547 info
dab0271f
G
1548 (gnus-add-to-range
1549 (gnus-add-to-range
1550 (gnus-range-add (gnus-info-read info)
1551 vanished)
1552 (cdr (assq '%Flagged flags)))
1553 (cdr (assq '%Seen flags))))
1554 (let ((marks (gnus-info-marks info)))
1555 (dolist (type (cdr nnimap-mark-alist))
1556 (let ((ticks (assoc (car type) marks))
1557 (new-marks
1558 (cdr (or (assoc (caddr type) flags) ; %Flagged
1559 (assoc (intern (cadr type) obarray) flags)
1560 (assoc (cadr type) flags))))) ; "\Flagged"
1561 (setq marks (delq ticks marks))
1562 (pop ticks)
1563 ;; Add the new marks we got.
1564 (setq ticks (gnus-add-to-range ticks new-marks))
1565 ;; Remove the marks from messages that don't have them.
1566 (setq ticks (gnus-remove-from-range
1567 ticks
1568 (gnus-compress-sequence
1569 (gnus-sorted-complement existing new-marks))))
1570 (when ticks
1571 (push (cons (car type) ticks) marks)))
eaa610c3
KY
1572 (gnus-info-set-marks info marks t))
1573 ;; Add vanished to the list of unexisting articles.
1574 (when vanished
1575 (let* ((old-unexists (assq 'unexist marks))
1576 (unexists (gnus-range-add (cdr old-unexists) vanished)))
1577 (if old-unexists
1578 (setcdr old-unexists unexists)
1579 (push (cons 'unexist unexists) marks)))
dab0271f 1580 (gnus-info-set-marks info marks t))))
f7aa248a
G
1581
1582(defun nnimap-imap-ranges-to-gnus-ranges (irange)
1583 (if (zerop (length irange))
1584 nil
1585 (let ((result nil))
1586 (dolist (elem (split-string irange ","))
1587 (push
1588 (if (string-match ":" elem)
1589 (let ((numbers (split-string elem ":")))
1590 (cons (string-to-number (car numbers))
1591 (string-to-number (cadr numbers))))
1592 (string-to-number elem))
1593 result))
1594 (nreverse result))))
286c4fc2
LMI
1595
1596(defun nnimap-store-info (info active)
1597 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1598 (entry (assoc group nnimap-current-infos)))
1599 (if entry
1600 (setcdr entry (list info active))
1601 (push (list group info active) nnimap-current-infos))))
20a673b2
KY
1602
1603(defun nnimap-flags-to-marks (groups)
f7aa248a
G
1604 (let (data group totalp uidnext articles start-article mark permanent-flags
1605 uidvalidity vanished highestmodseq)
20a673b2
KY
1606 (dolist (elem groups)
1607 (setq group (car elem)
b069e5a6
G
1608 uidnext (nth 1 elem)
1609 start-article (nth 2 elem)
1610 permanent-flags (nth 3 elem)
f7aa248a
G
1611 uidvalidity (nth 4 elem)
1612 vanished (nth 5 elem)
1613 highestmodseq (nth 6 elem)
1614 articles (nthcdr 7 elem))
20a673b2
KY
1615 (let ((high (caar articles))
1616 marks low existing)
1617 (dolist (article articles)
1618 (setq low (car article))
1619 (push (car article) existing)
1620 (dolist (flag (cdr article))
1621 (setq mark (assoc flag marks))
1622 (if (not mark)
1623 (push (list flag (car article)) marks)
b069e5a6
G
1624 (setcdr mark (cons (car article) (cdr mark))))))
1625 (push (list group existing marks high low uidnext start-article
f7aa248a 1626 permanent-flags uidvalidity vanished highestmodseq)
b069e5a6 1627 data)))
20a673b2
KY
1628 data))
1629
1630(defun nnimap-parse-flags (sequences)
1631 (goto-char (point-min))
4eff9c1a
LI
1632 ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1633 ;; read it.
b069e5a6
G
1634 (subst-char-in-region (point-min) (point-max)
1635 ?\\ ?% t)
a123622d
G
1636 ;; Remove any MODSEQ entries in the buffer, because they may contain
1637 ;; numbers that are too large for 32-bit Emacsen.
1638 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1639 (replace-match "" t t))
1640 (goto-char (point-min))
f7aa248a
G
1641 (let (start end articles groups uidnext elems permanent-flags
1642 uidvalidity vanished highestmodseq)
20a673b2 1643 (dolist (elem sequences)
f7aa248a
G
1644 (destructuring-bind (group-sequence flag-sequence totalp group command)
1645 elem
b069e5a6 1646 (setq start (point))
f7aa248a
G
1647 (when (and
1648 ;; The EXAMINE was successful.
1649 (search-forward (format "\n%d OK " group-sequence) nil t)
1650 (progn
1651 (forward-line 1)
1652 (setq end (point))
1653 (goto-char start)
1654 (setq permanent-flags
1655 (if (equal command "SELECT")
b069e5a6 1656 (and (search-forward "PERMANENTFLAGS "
f7aa248a
G
1657 (or end (point-min)) t)
1658 (read (current-buffer)))
1659 'not-scanned))
1660 (goto-char start)
1661 (setq uidnext
1662 (and (search-forward "UIDNEXT "
1663 (or end (point-min)) t)
1664 (read (current-buffer))))
1665 (goto-char start)
1666 (setq uidvalidity
1667 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1668 (or end (point-min)) t)
1669 ;; Store UIDVALIDITY as a string, as it's
1670 ;; too big for 32-bit Emacsen, usually.
1671 (match-string 1)))
1672 (goto-char start)
1673 (setq vanished
1674 (and (eq flag-sequence 'qresync)
a5166359 1675 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
f7aa248a
G
1676 (or end (point-min)) t)
1677 (match-string 1)))
1678 (goto-char start)
1679 (setq highestmodseq
a123622d 1680 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
f7aa248a 1681 (or end (point-min)) t)
a123622d 1682 (match-string 1)))
f7aa248a
G
1683 (goto-char end)
1684 (forward-line -1))
1685 ;; The UID FETCH FLAGS was successful.
1686 (or (eq flag-sequence 'qresync)
1687 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1688 (if (eq flag-sequence 'qresync)
1689 (progn
1690 (goto-char start)
1691 (setq start end))
1692 (setq start (point))
1693 (goto-char end))
a1d16a7b 1694 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
71f8b7ed 1695 (let ((p (point)))
a123622d 1696 (setq elems (read (current-buffer)))
71f8b7ed
G
1697 (push (cons (cadr (memq 'UID elems))
1698 (cadr (memq 'FLAGS elems)))
1699 articles)))
f7aa248a
G
1700 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1701 vanished highestmodseq)
1702 articles)
b069e5a6 1703 groups)
4eff9c1a
LI
1704 (if (eq flag-sequence 'qresync)
1705 (goto-char end)
1706 (setq end (point)))
20a673b2
KY
1707 (setq articles nil))))
1708 groups))
1709
1710(defun nnimap-find-process-buffer (buffer)
1711 (cadr (assoc buffer nnimap-connection-alist)))
1712
286c4fc2 1713(deffoo nnimap-request-post (&optional server)
20a673b2
KY
1714 (setq nnimap-status-string "Read-only server")
1715 nil)
c113de23 1716
eaa610c3 1717(defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
5a6a61f7
GM
1718(declare-function gnus-fetch-headers "gnus-sum"
1719 (articles &optional limit force-new dependencies))
1720
18cd34c1
LI
1721(autoload 'nnir-search-thread "nnir")
1722
0c136286 1723(deffoo nnimap-request-thread (header &optional group server)
e21bac42
G
1724 (when group
1725 (setq group (nnimap-decode-gnus-group group)))
bca46f6b 1726 (if gnus-refer-thread-use-nnir
47f0b35e 1727 (nnir-search-thread header)
eaa610c3 1728 (when (nnimap-change-group group server)
47f0b35e
AC
1729 (let* ((cmd (nnimap-make-thread-query header))
1730 (result (with-current-buffer (nnimap-buffer)
1731 (nnimap-command "UID SEARCH %s" cmd))))
1732 (when result
1733 (gnus-fetch-headers
7e67562f
G
1734 (and (car result)
1735 (delete 0 (mapcar #'string-to-number
1736 (cdr (assoc "SEARCH" (cdr result))))))
47f0b35e 1737 nil t))))))
030158f3 1738
eaa610c3
KY
1739(defun nnimap-change-group (group &optional server no-reconnect read-only)
1740 "Change group to GROUP if non-nil.
1741If SERVER is set, check that server is connected, otherwise retry
1742to reconnect, unless NO-RECONNECT is set to t. Return nil if
1743unsuccessful in connecting.
1744If GROUP is nil, return t.
1745If READ-ONLY is set, send EXAMINE rather than SELECT to the server.
1746Return the server's response to the SELECT or EXAMINE command."
20a673b2
KY
1747 (let ((open-result t))
1748 (when (and server
1749 (not (nnimap-server-opened server)))
98366438 1750 (setq open-result (nnimap-open-server server nil no-reconnect)))
20a673b2
KY
1751 (cond
1752 ((not open-result)
1753 nil)
1754 ((not group)
1755 t)
1756 (t
1757 (with-current-buffer (nnimap-buffer)
eaa610c3
KY
1758 (let ((result (nnimap-command "%s %S"
1759 (if read-only
1760 "EXAMINE"
1761 "SELECT")
1762 (utf7-encode group t))))
1763 (when (car result)
1764 (setf (nnimap-group nnimap-object) group
1765 (nnimap-select-result nnimap-object) result)
1766 result)))))))
20a673b2
KY
1767
1768(defun nnimap-find-connection (buffer)
1769 "Find the connection delivering to BUFFER."
1770 (let ((entry (assoc buffer nnimap-connection-alist)))
1771 (when entry
1772 (if (and (buffer-name (cadr entry))
1773 (get-buffer-process (cadr entry))
1774 (memq (process-status (get-buffer-process (cadr entry)))
1775 '(open run)))
1776 (get-buffer-process (cadr entry))
1777 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1778 nil))))
1779
1780(defvar nnimap-sequence 0)
1781
1782(defun nnimap-send-command (&rest args)
d5e9a4e9 1783 (setf (nnimap-last-command-time nnimap-object) (current-time))
20a673b2
KY
1784 (process-send-string
1785 (get-buffer-process (current-buffer))
1786 (nnimap-log-command
286c4fc2 1787 (format "%d %s%s\n"
20a673b2 1788 (incf nnimap-sequence)
286c4fc2
LMI
1789 (apply #'format args)
1790 (if (nnimap-newlinep nnimap-object)
1791 ""
1792 "\r"))))
b5c575e6
G
1793 ;; Some servers apparently can't have many outstanding
1794 ;; commands, so throttle them.
1795 (unless nnimap-streaming
1796 (nnimap-wait-for-response nnimap-sequence))
20a673b2
KY
1797 nnimap-sequence)
1798
3d2af193
LI
1799(defvar nnimap-record-commands nil
1800 "If non-nil, log commands to the \"*imap log*\" buffer.")
1801
eaa610c3
KY
1802(defun nnimap-log-buffer ()
1803 (let ((name "*imap log*"))
1804 (or (get-buffer name)
1805 (with-current-buffer (get-buffer-create name)
1806 (when (boundp 'window-point-insertion-type)
1807 (make-local-variable 'window-point-insertion-type)
1808 (setq window-point-insertion-type t))
1809 (current-buffer)))))
1810
20a673b2 1811(defun nnimap-log-command (command)
3d2af193 1812 (when nnimap-record-commands
eaa610c3 1813 (with-current-buffer (nnimap-log-buffer)
3d2af193 1814 (goto-char (point-max))
b0668aa8 1815 (insert (format-time-string "%H:%M:%S")
eaa610c3
KY
1816 " [" nnimap-address "] "
1817 (if nnimap-inhibit-logging
1818 "(inhibited)\n"
1819 command))))
20a673b2
KY
1820 command)
1821
1822(defun nnimap-command (&rest args)
1823 (erase-buffer)
1824 (let* ((sequence (apply #'nnimap-send-command args))
1825 (response (nnimap-get-response sequence)))
1826 (if (equal (caar response) "OK")
1827 (cons t response)
1828 (nnheader-report 'nnimap "%s"
a46359d4
LMI
1829 (mapconcat (lambda (a)
1830 (format "%s" a))
1831 (car response) " "))
20a673b2
KY
1832 nil)))
1833
1834(defun nnimap-get-response (sequence)
1835 (nnimap-wait-for-response sequence)
1836 (nnimap-parse-response))
1837
389b76fa 1838(defun nnimap-wait-for-connection (&optional regexp)
84d89ede
LMI
1839 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1840
1841(defun nnimap-wait-for-line (regexp &optional response-regexp)
286c4fc2
LMI
1842 (let ((process (get-buffer-process (current-buffer))))
1843 (goto-char (point-min))
1844 (while (and (memq (process-status process)
1845 '(open run))
389b76fa 1846 (not (re-search-forward regexp nil t)))
286c4fc2
LMI
1847 (nnheader-accept-process-output process)
1848 (goto-char (point-min)))
bdaa75c7 1849 (forward-line -1)
84d89ede 1850 (and (looking-at (or response-regexp regexp))
bdaa75c7 1851 (match-string 1))))
286c4fc2 1852
20a673b2 1853(defun nnimap-wait-for-response (sequence &optional messagep)
8ccbef23
G
1854 (let ((process (get-buffer-process (current-buffer)))
1855 openp)
dab0271f
G
1856 (condition-case nil
1857 (progn
1858 (goto-char (point-max))
1859 (while (and (setq openp (memq (process-status process)
1860 '(open run)))
0832490d
LI
1861 (progn
1862 ;; Skip past any "*" lines that the server has
1863 ;; output.
1864 (while (and (not (bobp))
1865 (progn
1866 (forward-line -1)
1867 (looking-at "\\*"))))
01baa1e6 1868 (not (looking-at (format "%d .*\n" sequence)))))
dab0271f 1869 (when messagep
2146e256 1870 (nnheader-message-maybe
b5235dd9
LI
1871 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1872 nnimap-address
1873 (if (not (zerop (nnimap-initial-resync nnimap-object)))
65e6fb28
LI
1874 (format " (initial sync of %d group%s; please wait)"
1875 (nnimap-initial-resync nnimap-object)
1876 (if (= (nnimap-initial-resync nnimap-object) 1)
1877 ""
1878 "s"))
b5235dd9 1879 "")))
dab0271f
G
1880 (nnheader-accept-process-output process)
1881 (goto-char (point-max)))
b5235dd9 1882 (setf (nnimap-initial-resync nnimap-object) 0)
dab0271f
G
1883 openp)
1884 (quit
a123622d
G
1885 (when debug-on-quit
1886 (debug "Quit"))
dab0271f
G
1887 ;; The user hit C-g while we were waiting: kill the process, in case
1888 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1889 ;; NAT routers).
1890 (delete-process process)
1891 nil))))
20a673b2
KY
1892
1893(defun nnimap-parse-response ()
1894 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1895 result)
1896 (dolist (line lines)
1897 (push (cdr (nnimap-parse-line line)) result))
1898 ;; Return the OK/error code first, and then all the "continuation
1899 ;; lines" afterwards.
1900 (cons (pop result)
1901 (nreverse result))))
1902
1903;; Parse an IMAP response line lightly. They look like
1904;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1905;; the lines into a list of strings and lists of string.
1906(defun nnimap-parse-line (line)
1907 (let (char result)
1908 (with-temp-buffer
a04f9e26 1909 (mm-disable-multibyte)
20a673b2
KY
1910 (insert line)
1911 (goto-char (point-min))
1912 (while (not (eobp))
1913 (if (eql (setq char (following-char)) ? )
1914 (forward-char 1)
1915 (push
1916 (cond
1917 ((eql char ?\[)
f7aa248a
G
1918 (split-string
1919 (buffer-substring
1920 (1+ (point))
9310f19d
LMI
1921 (if (search-forward "]" (line-end-position) 'move)
1922 (1- (point))
1923 (point)))))
20a673b2 1924 ((eql char ?\()
f7aa248a
G
1925 (split-string
1926 (buffer-substring
1927 (1+ (point))
9310f19d
LMI
1928 (if (search-forward ")" (line-end-position) 'move)
1929 (1- (point))
1930 (point)))))
20a673b2
KY
1931 ((eql char ?\")
1932 (forward-char 1)
9f2d52e7
G
1933 (buffer-substring
1934 (point)
1935 (1- (or (search-forward "\"" (line-end-position) 'move)
1936 (point)))))
20a673b2
KY
1937 (t
1938 (buffer-substring (point) (if (search-forward " " nil t)
1939 (1- (point))
1940 (goto-char (point-max))))))
1941 result)))
1942 (nreverse result))))
1943
1944(defun nnimap-last-response-string ()
1945 (save-excursion
1946 (forward-line 1)
1947 (let ((end (point)))
1948 (forward-line -1)
1949 (when (not (bobp))
1950 (forward-line -1)
1951 (while (and (not (bobp))
1952 (eql (following-char) ?*))
1953 (forward-line -1))
1954 (unless (eql (following-char) ?*)
1955 (forward-line 1)))
1956 (buffer-substring (point) end))))
1957
20a673b2
KY
1958(defvar nnimap-incoming-split-list nil)
1959
1960(defun nnimap-fetch-inbox (articles)
1961 (erase-buffer)
1962 (nnimap-wait-for-response
1963 (nnimap-send-command
1964 "UID FETCH %s %s"
1965 (nnimap-article-ranges articles)
1966 (format "(UID %s%s)"
1967 (format
8ccbef23 1968 (if (nnimap-ver4-p)
1518e4f0 1969 "BODY.PEEK"
20a673b2 1970 "RFC822.PEEK"))
1518e4f0
G
1971 (cond
1972 (nnimap-split-download-body-default
1973 "[]")
1974 ((nnimap-ver4-p)
1975 "[HEADER]")
1976 (t
1977 "[1]"))))
20a673b2
KY
1978 t))
1979
1980(defun nnimap-split-incoming-mail ()
1981 (with-current-buffer (nnimap-buffer)
1982 (let ((nnimap-incoming-split-list nil)
656e1aab
LMI
1983 (nnmail-split-methods
1984 (cond
1985 ((eq nnimap-split-methods 'default)
1986 nnmail-split-methods)
1987 (nnimap-split-methods
1988 nnimap-split-methods)
1989 (nnimap-split-fancy
1990 'nnmail-split-fancy)))
6b958814
G
1991 (nnmail-split-fancy (or nnimap-split-fancy
1992 nnmail-split-fancy))
20a673b2
KY
1993 (nnmail-inhibit-default-split-group t)
1994 (groups (nnimap-get-groups))
1995 new-articles)
1996 (erase-buffer)
1997 (nnimap-command "SELECT %S" nnimap-inbox)
99e65b2d 1998 (setf (nnimap-group nnimap-object) nnimap-inbox)
20a673b2
KY
1999 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
2000 (when new-articles
2001 (nnimap-fetch-inbox new-articles)
2002 (nnimap-transform-split-mail)
2003 (nnheader-ms-strip-cr)
2004 (nnmail-cache-open)
2005 (nnmail-split-incoming (current-buffer)
2006 #'nnimap-save-mail-spec
2007 nil nil
b069e5a6
G
2008 #'nnimap-dummy-active-number
2009 #'nnimap-save-mail-spec)
20a673b2
KY
2010 (when nnimap-incoming-split-list
2011 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
b069e5a6 2012 sequences junk-articles)
20a673b2
KY
2013 ;; Create any groups that doesn't already exist on the
2014 ;; server first.
2015 (dolist (spec specs)
b069e5a6
G
2016 (when (and (not (member (car spec) groups))
2017 (not (eq (car spec) 'junk)))
20a673b2
KY
2018 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
2019 ;; Then copy over all the messages.
2020 (erase-buffer)
2021 (dolist (spec specs)
2022 (let ((group (car spec))
2023 (ranges (cdr spec)))
b069e5a6
G
2024 (if (eq group 'junk)
2025 (setq junk-articles ranges)
2026 (push (list (nnimap-send-command
2027 "UID COPY %s %S"
2028 (nnimap-article-ranges ranges)
2029 (utf7-encode group t))
2030 ranges)
2031 sequences))))
20a673b2
KY
2032 ;; Wait for the last COPY response...
2033 (when sequences
2034 (nnimap-wait-for-response (caar sequences))
2035 ;; And then mark the successful copy actions as deleted,
2036 ;; and possibly expunge them.
2037 (nnimap-mark-and-expunge-incoming
61b1af82
G
2038 (nnimap-parse-copied-articles sequences)))
2039 (nnimap-mark-and-expunge-incoming junk-articles)))))))
20a673b2
KY
2040
2041(defun nnimap-mark-and-expunge-incoming (range)
2042 (when range
2043 (setq range (nnimap-article-ranges range))
229b59da 2044 (erase-buffer)
0617bb00
LMI
2045 (let ((sequence
2046 (nnimap-send-command
2047 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
2048 (cond
2049 ;; If the server supports it, we now delete the message we have
2050 ;; just copied over.
389b76fa 2051 ((nnimap-capability "UIDPLUS")
0617bb00
LMI
2052 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
2053 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
2054 ;; user has configured it.
b069e5a6 2055 (nnimap-expunge
0617bb00
LMI
2056 (setq sequence (nnimap-send-command "EXPUNGE"))))
2057 (nnimap-wait-for-response sequence))))
20a673b2
KY
2058
2059(defun nnimap-parse-copied-articles (sequences)
2060 (let (sequence copied range)
2061 (goto-char (point-min))
56e96bed 2062 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
20a673b2
KY
2063 (setq sequence (string-to-number (match-string 1)))
2064 (when (setq range (cadr (assq sequence sequences)))
2065 (push (gnus-uncompress-range range) copied)))
2066 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2067
2068(defun nnimap-new-articles (flags)
2069 (let (new)
2070 (dolist (elem flags)
99e65b2d
G
2071 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2072 (cdr elem))
20a673b2
KY
2073 (push (car elem) new)))
2074 (gnus-compress-sequence (nreverse new))))
2075
2076(defun nnimap-make-split-specs (list)
2077 (let ((specs nil)
2078 entry)
2079 (dolist (elem list)
2080 (destructuring-bind (article spec) elem
2081 (dolist (group (delete nil (mapcar #'car spec)))
2082 (unless (setq entry (assoc group specs))
2083 (push (setq entry (list group)) specs))
2084 (setcdr entry (cons article (cdr entry))))))
2085 (dolist (entry specs)
2086 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2087 specs))
2088
2089(defun nnimap-transform-split-mail ()
2090 (goto-char (point-min))
2091 (let (article bytes)
2092 (block nil
2093 (while (not (eobp))
b5244046 2094 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
20a673b2
KY
2095 (delete-region (point) (progn (forward-line 1) (point)))
2096 (when (eobp)
2097 (return)))
2098 (setq article (match-string 1)
2099 bytes (nnimap-get-length))
2100 (delete-region (line-beginning-position) (line-end-position))
2101 ;; Insert MMDF separator, and a way to remember what this
2102 ;; article UID is.
2103 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2104 (forward-char (1+ bytes))
2105 (setq bytes (nnimap-get-length))
2106 (delete-region (line-beginning-position) (line-end-position))
6b7df8d3
G
2107 ;; There's a body; skip past that.
2108 (when bytes
2109 (forward-char (1+ bytes))
2110 (delete-region (line-beginning-position) (line-end-position)))))))
20a673b2
KY
2111
2112(defun nnimap-dummy-active-number (group &optional server)
2113 1)
2114
2115(defun nnimap-save-mail-spec (group-art &optional server full-nov)
2116 (let (article)
2117 (goto-char (point-min))
2118 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2119 (error "Invalid nnimap mail")
2120 (setq article (string-to-number (match-string 1))))
b069e5a6
G
2121 (push (list article
2122 (if (eq group-art 'junk)
2123 (list (cons 'junk 1))
2124 group-art))
20a673b2 2125 nnimap-incoming-split-list)))
c113de23 2126
af92e247
AC
2127(defun nnimap-make-thread-query (header)
2128 (let* ((id (mail-header-id header))
2129 (refs (split-string
2130 (or (mail-header-references header)
2131 "")))
43a0a4fa
AC
2132 (value
2133 (format
2134 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2135 id id)))
af92e247
AC
2136 (dolist (refid refs value)
2137 (setq value (format
43a0a4fa 2138 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
af92e247
AC
2139 refid refid value)))))
2140
2141
c113de23
GM
2142(provide 'nnimap)
2143
2144;;; nnimap.el ends here