0c2b80c9ca7899105cd5544694c907e6be5399c4
[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]+\\|#x[0-9a-f]+\\|[a-z]+[0-9]*\\);"
369                             nil t)
370     (let* ((entity (match-string 1))
371            (elem (if (eq (aref entity 0) ?\#)
372                      (let ((c
373                             ;; Hex number: &#x3212
374                             (if (eq (aref entity 1) ?x)
375                                 (string-to-number (substring entity 2)
376                                                   16)
377                               ;; Decimal number: &#23
378                               (string-to-number (substring entity 1)))))
379                        (setq c (or (cdr (assq c mm-extra-numeric-entities))
380                                    (mm-ucs-to-char c)))
381                        (if (mm-char-or-char-int-p c) c ?#))
382                    (or (cdr (assq (intern entity)
383                                   mm-url-html-entities))
384                        ?#))))
385       (unless (stringp elem)
386         (setq elem (char-to-string elem)))
387       (replace-match elem t t))))
388
389 (defun mm-url-decode-entities-nbsp ()
390   "Decode all HTML entities and &nbsp; to a space."
391   (let ((mm-url-html-entities (cons '(nbsp . 32) mm-url-html-entities)))
392     (mm-url-decode-entities)))
393
394 (defun mm-url-decode-entities-string (string)
395   (with-temp-buffer
396     (insert string)
397     (mm-url-decode-entities)
398     (buffer-string)))
399
400 (defun mm-url-form-encode-xwfu (chunk)
401   "Escape characters in a string for application/x-www-form-urlencoded.
402 Blasphemous crap because someone didn't think %20 was good enough for encoding
403 spaces.  Die Die Die."
404   ;; This will get rid of the 'attributes' specified by the file type,
405   ;; which are useless for an application/x-www-form-urlencoded form.
406   (if (consp chunk)
407       (setq chunk (cdr chunk)))
408
409   (mapconcat
410    (lambda (char)
411      (cond
412       ((= char ?  ) "+")
413       ((memq char mm-url-unreserved-chars) (char-to-string char))
414       (t (upcase (format "%%%02x" char)))))
415    (mm-encode-coding-string chunk
416                             (if (fboundp 'find-coding-systems-string)
417                                 (car (find-coding-systems-string chunk))
418                               buffer-file-coding-system))
419    ""))
420
421 (defun mm-url-encode-www-form-urlencoded (pairs)
422   "Return PAIRS encoded for forms."
423   (mapconcat
424    (lambda (data)
425      (concat (mm-url-form-encode-xwfu (car data)) "="
426              (mm-url-form-encode-xwfu (cdr data))))
427    pairs "&"))
428
429 (autoload 'mml-compute-boundary "mml")
430
431 (defun mm-url-encode-multipart-form-data (pairs &optional boundary)
432   "Return PAIRS encoded in multipart/form-data."
433   ;; RFC1867
434
435   ;; Get a good boundary
436   (unless boundary
437     (setq boundary (mml-compute-boundary '())))
438
439   (concat
440
441    ;; Start with the boundary
442    "--" boundary "\r\n"
443
444    ;; Create name value pairs
445    (mapconcat
446     'identity
447     ;; Delete any returned items that are empty
448     (delq nil
449           (mapcar (lambda (data)
450             (when (car data)
451               ;; For each pair
452               (concat
453
454                ;; Encode the name
455                "Content-Disposition: form-data; name=\""
456                (car data) "\"\r\n"
457                "Content-Type: text/plain; charset=utf-8\r\n"
458                "Content-Transfer-Encoding: binary\r\n\r\n"
459
460                (cond ((stringp (cdr data))
461                       (cdr data))
462                      ((integerp (cdr data))
463                       (int-to-string (cdr data))))
464
465                "\r\n")))
466                   pairs))
467     ;; use the boundary as a separator
468     (concat "--" boundary "\r\n"))
469
470    ;; put a boundary at the end.
471    "--" boundary "--\r\n"))
472
473 (defun mm-url-fetch-form (url pairs)
474   "Fetch a form from URL with PAIRS as the data using the POST method."
475   (mm-url-load-url)
476   (let ((url-request-data (mm-url-encode-www-form-urlencoded pairs))
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-fetch-simple (url content)
485   (mm-url-load-url)
486   (let ((url-request-data content)
487         (url-request-method "POST")
488         (url-request-extra-headers
489          '(("Content-type" . "application/x-www-form-urlencoded"))))
490     (url-insert-file-contents url)
491     (setq buffer-file-name nil))
492   t)
493
494 (defun mm-url-remove-markup ()
495   "Remove all HTML markup, leaving just plain text."
496   (goto-char (point-min))
497   (while (search-forward "<!--" nil t)
498     (delete-region (match-beginning 0)
499                    (or (search-forward "-->" nil t)
500                        (point-max))))
501   (goto-char (point-min))
502   (while (re-search-forward "<[^>]+>" nil t)
503     (replace-match "" t t)))
504
505 (provide 'mm-url)
506
507 ;;; mm-url.el ends here