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