* gnus-bookmark.el (gnus-bookmark-jump): Don't mark unrelated articles
[gnus] / lisp / mm-url.el
1 ;;; mm-url.el --- a wrapper of url functions/commands for Gnus
2
3 ;; Copyright (C) 2001, 2002, 2003, 2004, 2005,
4 ;;   2006 Free Software Foundation, Inc.
5
6 ;; Author: Shenghuo Zhu <zsh@cs.rochester.edu>
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
12 ;; by the Free Software Foundation; either version 2, or (at your
13 ;; option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 ;; 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., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
24
25 ;;; Commentary:
26
27 ;; Some codes are stolen from w3 and url packages. Some are moved from
28 ;; nnweb.
29
30 ;; TODO: Support POST, cookie.
31
32 ;;; Code:
33
34 (eval-when-compile (require 'cl))
35
36 (require 'mm-util)
37 (require 'gnus)
38
39 (defvar url-current-object)
40 (defvar url-package-name)
41 (defvar url-package-version)
42
43 (defgroup mm-url nil
44   "A wrapper of url package and external url command for Gnus."
45   :group 'gnus)
46
47 (defcustom mm-url-use-external (not
48                                 (condition-case nil
49                                     (require 'url)
50                                   (error nil)))
51   "*If non-nil, use external grab program `mm-url-program'."
52   :version "22.1"
53   :type 'boolean
54   :group 'mm-url)
55
56 (defvar mm-url-predefined-programs
57   '((wget "wget" "--user-agent=mm-url" "-q" "-O" "-")
58     (w3m  "w3m" "-dump_source")
59     (lynx "lynx" "-source")
60     (curl "curl" "--silent" "--user-agent mm-url" "--location")))
61
62 (defcustom mm-url-program
63   (cond
64    ((executable-find "wget") 'wget)
65    ((executable-find "w3m") 'w3m)
66    ((executable-find "lynx") 'lynx)
67    ((executable-find "curl") 'curl)
68    (t "GET"))
69   "The url grab program.
70 Likely values are `wget', `w3m', `lynx' and `curl'."
71   :version "22.1"
72   :type '(choice
73           (symbol :tag "wget" wget)
74           (symbol :tag "w3m" w3m)
75           (symbol :tag "lynx" lynx)
76           (symbol :tag "curl" curl)
77           (string :tag "other"))
78   :group 'mm-url)
79
80 (defcustom mm-url-arguments nil
81   "The arguments for `mm-url-program'."
82   :version "22.1"
83   :type '(repeat string)
84   :group 'mm-url)
85
86 \f
87 ;;; Internal variables
88
89 (defvar mm-url-package-name
90   (gnus-replace-in-string
91    (gnus-replace-in-string gnus-version " v.*$" "")
92    " " "-"))
93
94 (defvar mm-url-package-version gnus-version-number)
95
96 ;; Stolen from w3.
97 (defvar mm-url-html-entities
98   '(
99     ;;(excl        .  33)
100     (quot        .  34)
101     ;;(num         .  35)
102     ;;(dollar      .  36)
103     ;;(percent     .  37)
104     (amp         .  38)
105     (rsquo       .  39)                 ; should be U+8217
106     ;;(apos        .  39)
107     ;;(lpar        .  40)
108     ;;(rpar        .  41)
109     ;;(ast         .  42)
110     ;;(plus        .  43)
111     ;;(comma       .  44)
112     ;;(period      .  46)
113     ;;(colon       .  58)
114     ;;(semi        .  59)
115     (lt          .  60)
116     ;;(equals      .  61)
117     (gt          .  62)
118     ;;(quest       .  63)
119     ;;(commat      .  64)
120     ;;(lsqb        .  91)
121     ;;(rsqb        .  93)
122     (uarr        .  94)                 ; should be U+8593
123     ;;(lowbar      .  95)
124     (lsquo       .  96)                 ; should be U+8216
125     (lcub        . 123)
126     ;;(verbar      . 124)
127     (rcub        . 125)
128     (tilde       . 126)
129     (nbsp        . 160)
130     (iexcl       . 161)
131     (cent        . 162)
132     (pound       . 163)
133     (curren      . 164)
134     (yen         . 165)
135     (brvbar      . 166)
136     (sect        . 167)
137     (uml         . 168)
138     (copy        . 169)
139     (ordf        . 170)
140     (laquo       . 171)
141     (not         . 172)
142     (shy         . 173)
143     (reg         . 174)
144     (macr        . 175)
145     (deg         . 176)
146     (plusmn      . 177)
147     (sup2        . 178)
148     (sup3        . 179)
149     (acute       . 180)
150     (micro       . 181)
151     (para        . 182)
152     (middot      . 183)
153     (cedil       . 184)
154     (sup1        . 185)
155     (ordm        . 186)
156     (raquo       . 187)
157     (frac14      . 188)
158     (frac12      . 189)
159     (frac34      . 190)
160     (iquest      . 191)
161     (Agrave      . 192)
162     (Aacute      . 193)
163     (Acirc       . 194)
164     (Atilde      . 195)
165     (Auml        . 196)
166     (Aring       . 197)
167     (AElig       . 198)
168     (Ccedil      . 199)
169     (Egrave      . 200)
170     (Eacute      . 201)
171     (Ecirc       . 202)
172     (Euml        . 203)
173     (Igrave      . 204)
174     (Iacute      . 205)
175     (Icirc       . 206)
176     (Iuml        . 207)
177     (ETH         . 208)
178     (Ntilde      . 209)
179     (Ograve      . 210)
180     (Oacute      . 211)
181     (Ocirc       . 212)
182     (Otilde      . 213)
183     (Ouml        . 214)
184     (times       . 215)
185     (Oslash      . 216)
186     (Ugrave      . 217)
187     (Uacute      . 218)
188     (Ucirc       . 219)
189     (Uuml        . 220)
190     (Yacute      . 221)
191     (THORN       . 222)
192     (szlig       . 223)
193     (agrave      . 224)
194     (aacute      . 225)
195     (acirc       . 226)
196     (atilde      . 227)
197     (auml        . 228)
198     (aring       . 229)
199     (aelig       . 230)
200     (ccedil      . 231)
201     (egrave      . 232)
202     (eacute      . 233)
203     (ecirc       . 234)
204     (euml        . 235)
205     (igrave      . 236)
206     (iacute      . 237)
207     (icirc       . 238)
208     (iuml        . 239)
209     (eth         . 240)
210     (ntilde      . 241)
211     (ograve      . 242)
212     (oacute      . 243)
213     (ocirc       . 244)
214     (otilde      . 245)
215     (ouml        . 246)
216     (divide      . 247)
217     (oslash      . 248)
218     (ugrave      . 249)
219     (uacute      . 250)
220     (ucirc       . 251)
221     (uuml        . 252)
222     (yacute      . 253)
223     (thorn       . 254)
224     (yuml        . 255)
225
226     ;; Special handling of these
227     (frac56      . "5/6")
228     (frac16      . "1/6")
229     (frac45      . "4/5")
230     (frac35      . "3/5")
231     (frac25      . "2/5")
232     (frac15      . "1/5")
233     (frac23      . "2/3")
234     (frac13      . "1/3")
235     (frac78      . "7/8")
236     (frac58      . "5/8")
237     (frac38      . "3/8")
238     (frac18      . "1/8")
239
240     ;; The following 5 entities are not mentioned in the HTML 2.0
241     ;; standard, nor in any other HTML proposed standard of which I
242     ;; am aware.  I am not even sure they are ISO entity names.  ***
243     ;; Hence, some arrangement should be made to give a bad HTML
244     ;; message when they are seen.
245     (ndash       .  45)
246     (mdash       .  45)
247     (emsp        .  32)
248     (ensp        .  32)
249     (sim         . 126)
250     (le          . "<=")
251     (agr         . "alpha")
252     (rdquo       . "''")
253     (ldquo       . "``")
254     (trade       . "(TM)")
255     ;; To be done
256     ;; (shy      . ????) ; soft hyphen
257     )
258   "*An assoc list of entity names and how to actually display them.")
259
260 (defconst mm-url-unreserved-chars
261   '(
262     ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z
263     ?A ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z
264     ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9
265     ?- ?_ ?. ?! ?~ ?* ?' ?\( ?\))
266   "A list of characters that are _NOT_ reserved in the URL spec.
267 This is taken from RFC 2396.")
268
269 (defun mm-url-load-url ()
270   "Load `url-insert-file-contents'."
271   (unless (condition-case ()
272               (progn
273                 (require 'url-handlers)
274                 (require 'url-parse)
275                 (require 'url-vars))
276             (error nil))
277     ;; w3-4.0pre0.46 or earlier version.
278     (require 'w3-vars)
279     (require 'url)))
280
281 ;;;###autoload
282 (defun mm-url-insert-file-contents (url)
283   "Insert file contents of URL.
284 If `mm-url-use-external' is non-nil, use `mm-url-program'."
285   (if mm-url-use-external
286       (progn
287         (if (string-match "^file:/+" url)
288             (insert-file-contents (substring url (1- (match-end 0))))
289           (mm-url-insert-file-contents-external url))
290         (goto-char (point-min))
291         (if (fboundp 'url-generic-parse-url)
292             (setq url-current-object
293                   (url-generic-parse-url url)))
294         (list url (buffer-size)))
295     (mm-url-load-url)
296     (let ((name buffer-file-name)
297           (url-package-name (or mm-url-package-name
298                                 url-package-name))
299           (url-package-version (or mm-url-package-version
300                                    url-package-version))
301           result)
302       (setq result (url-insert-file-contents url))
303       (save-excursion
304         (goto-char (point-min))
305         (while (re-search-forward "\r 1000\r ?" nil t)
306           (replace-match "")))
307       (setq buffer-file-name name)
308       (if (and (fboundp 'url-generic-parse-url)
309                (listp result))
310           (setq url-current-object (url-generic-parse-url
311                                     (car result))))
312       result)))
313
314 ;;;###autoload
315 (defun mm-url-insert-file-contents-external (url)
316   "Insert file contents of URL using `mm-url-program'."
317   (let (program args)
318     (if (symbolp mm-url-program)
319         (let ((item (cdr (assq mm-url-program mm-url-predefined-programs))))
320           (setq program (car item)
321                 args (append (cdr item) (list url))))
322       (setq program mm-url-program
323             args (append mm-url-arguments (list url))))
324     (unless (eq 0 (apply 'call-process program nil t nil args))
325       (error "Couldn't fetch %s" url))))
326
327 (defvar mm-url-timeout 30
328   "The number of seconds before timing out an URL fetch.")
329
330 (defvar mm-url-retries 10
331   "The number of retries after timing out when fetching an URL.")
332
333 (defun mm-url-insert (url &optional follow-refresh)
334   "Insert the contents from an URL in the current buffer.
335 If FOLLOW-REFRESH is non-nil, redirect refresh url in META."
336   (let ((times mm-url-retries)
337         (done nil)
338         (first t)
339         result)
340     (while (and (not (zerop (decf times)))
341                 (not done))
342       (with-timeout (mm-url-timeout)
343         (unless first
344           (message "Trying again (%s)..." (- mm-url-retries times)))
345         (setq first nil)
346         (if follow-refresh
347             (save-restriction
348               (narrow-to-region (point) (point))
349               (mm-url-insert-file-contents url)
350               (goto-char (point-min))
351               (when (re-search-forward
352                      "<meta[ \t\r\n]*http-equiv=\"Refresh\"[^>]*URL=\\([^\"]+\\)\"" nil t)
353                 (let ((url (match-string 1)))
354                   (delete-region (point-min) (point-max))
355                   (setq result (mm-url-insert url t)))))
356           (setq result (mm-url-insert-file-contents url)))
357         (setq done t)))
358     result))
359
360 (defun mm-url-decode-entities ()
361   "Decode all HTML entities."
362   (goto-char (point-min))
363   (while (re-search-forward "&\\(#[0-9]+\\|[a-z]+[0-9]*\\);" nil t)
364     (let ((elem (if (eq (aref (match-string 1) 0) ?\#)
365                         (let ((c
366                                (string-to-number (substring
367                                                   (match-string 1) 1))))
368                           (if (mm-char-or-char-int-p c) c 32))
369                       (or (cdr (assq (intern (match-string 1))
370                                      mm-url-html-entities))
371                           ?#))))
372       (unless (stringp elem)
373         (setq elem (char-to-string elem)))
374       (replace-match elem t t))))
375
376 (defun mm-url-decode-entities-nbsp ()
377   "Decode all HTML entities and &nbsp; to a space."
378   (let ((mm-url-html-entities (cons '(nbsp . 32) mm-url-html-entities)))
379     (mm-url-decode-entities)))
380
381 (defun mm-url-decode-entities-string (string)
382   (with-temp-buffer
383     (insert string)
384     (mm-url-decode-entities)
385     (buffer-string)))
386
387 (defun mm-url-form-encode-xwfu (chunk)
388   "Escape characters in a string for application/x-www-form-urlencoded.
389 Blasphemous crap because someone didn't think %20 was good enough for encoding
390 spaces.  Die Die Die."
391   ;; This will get rid of the 'attributes' specified by the file type,
392   ;; which are useless for an application/x-www-form-urlencoded form.
393   (if (consp chunk)
394       (setq chunk (cdr chunk)))
395
396   (mapconcat
397    (lambda (char)
398      (cond
399       ((= char ?  ) "+")
400       ((memq char mm-url-unreserved-chars) (char-to-string char))
401       (t (upcase (format "%%%02x" char)))))
402    ;; Fixme: Should this actually be accepting multibyte?  Is there a
403    ;; better way in XEmacs?
404    (if (featurep 'mule)
405        (encode-coding-string chunk
406                              (if (fboundp 'find-coding-systems-string)
407                                  (car (find-coding-systems-string chunk))
408                                  buffer-file-coding-system))
409      chunk)
410    ""))
411
412 (defun mm-url-encode-www-form-urlencoded (pairs)
413   "Return PAIRS encoded for forms."
414   (mapconcat
415    (lambda (data)
416      (concat (mm-url-form-encode-xwfu (car data)) "="
417              (mm-url-form-encode-xwfu (cdr data))))
418    pairs "&"))
419
420 (defun mm-url-fetch-form (url pairs)
421   "Fetch a form from URL with PAIRS as the data using the POST method."
422   (mm-url-load-url)
423   (let ((url-request-data (mm-url-encode-www-form-urlencoded pairs))
424         (url-request-method "POST")
425         (url-request-extra-headers
426          '(("Content-type" . "application/x-www-form-urlencoded"))))
427     (url-insert-file-contents url)
428     (setq buffer-file-name nil))
429   t)
430
431 (defun mm-url-fetch-simple (url content)
432   (mm-url-load-url)
433   (let ((url-request-data content)
434         (url-request-method "POST")
435         (url-request-extra-headers
436          '(("Content-type" . "application/x-www-form-urlencoded"))))
437     (url-insert-file-contents url)
438     (setq buffer-file-name nil))
439   t)
440
441 (defun mm-url-remove-markup ()
442   "Remove all HTML markup, leaving just plain text."
443   (goto-char (point-min))
444   (while (search-forward "<!--" nil t)
445     (delete-region (match-beginning 0)
446                    (or (search-forward "-->" nil t)
447                        (point-max))))
448   (goto-char (point-min))
449   (while (re-search-forward "<[^>]+>" nil t)
450     (replace-match "" t t)))
451
452 (provide 'mm-url)
453
454 ;;; arch-tag: 0594f9b3-417c-48b0-adc2-5082e1e7917f
455 ;;; mm-url.el ends here