* gnus-cite.el (gnus-message-highlight-citation): Move to gnus-msg.el.
[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-request-extra-headers
298            ;; ISTM setting a Connection header was a workaround for
299            ;; older versions of url included with w3, but it does more
300            ;; harm than good with the one shipped with Emacs. --ansel
301            (if (not (and (boundp 'url-version)
302                          (equal url-version "Emacs")))
303                (list (cons "Connection" "Close"))))
304           (url-package-name (or mm-url-package-name
305                                 url-package-name))
306           (url-package-version (or mm-url-package-version
307                                    url-package-version))
308           result)
309       (setq result (url-insert-file-contents url))
310       (save-excursion
311         (goto-char (point-min))
312         (while (re-search-forward "\r 1000\r ?" nil t)
313           (replace-match "")))
314       (setq buffer-file-name name)
315       (if (and (fboundp 'url-generic-parse-url)
316                (listp result))
317           (setq url-current-object (url-generic-parse-url
318                                     (car result))))
319       result)))
320
321 ;;;###autoload
322 (defun mm-url-insert-file-contents-external (url)
323   "Insert file contents of URL using `mm-url-program'."
324   (let (program args)
325     (if (symbolp mm-url-program)
326         (let ((item (cdr (assq mm-url-program mm-url-predefined-programs))))
327           (setq program (car item)
328                 args (append (cdr item) (list url))))
329       (setq program mm-url-program
330             args (append mm-url-arguments (list url))))
331     (unless (eq 0 (apply 'call-process program nil t nil args))
332       (error "Couldn't fetch %s" url))))
333
334 (defvar mm-url-timeout 30
335   "The number of seconds before timing out an URL fetch.")
336
337 (defvar mm-url-retries 10
338   "The number of retries after timing out when fetching an URL.")
339
340 (defun mm-url-insert (url &optional follow-refresh)
341   "Insert the contents from an URL in the current buffer.
342 If FOLLOW-REFRESH is non-nil, redirect refresh url in META."
343   (let ((times mm-url-retries)
344         (done nil)
345         (first t)
346         result)
347     (while (and (not (zerop (decf times)))
348                 (not done))
349       (with-timeout (mm-url-timeout)
350         (unless first
351           (message "Trying again (%s)..." (- mm-url-retries times)))
352         (setq first nil)
353         (if follow-refresh
354             (save-restriction
355               (narrow-to-region (point) (point))
356               (mm-url-insert-file-contents url)
357               (goto-char (point-min))
358               (when (re-search-forward
359                      "<meta[ \t\r\n]*http-equiv=\"Refresh\"[^>]*URL=\\([^\"]+\\)\"" nil t)
360                 (let ((url (match-string 1)))
361                   (delete-region (point-min) (point-max))
362                   (setq result (mm-url-insert url t)))))
363           (setq result (mm-url-insert-file-contents url)))
364         (setq done t)))
365     result))
366
367 (defun mm-url-decode-entities ()
368   "Decode all HTML entities."
369   (goto-char (point-min))
370   (while (re-search-forward "&\\(#[0-9]+\\|[a-z]+[0-9]*\\);" nil t)
371     (let ((elem (if (eq (aref (match-string 1) 0) ?\#)
372                         (let ((c
373                                (string-to-number (substring
374                                                   (match-string 1) 1))))
375                           (if (mm-char-or-char-int-p c) c 32))
376                       (or (cdr (assq (intern (match-string 1))
377                                      mm-url-html-entities))
378                           ?#))))
379       (unless (stringp elem)
380         (setq elem (char-to-string elem)))
381       (replace-match elem t t))))
382
383 (defun mm-url-decode-entities-nbsp ()
384   "Decode all HTML entities and &nbsp; to a space."
385   (let ((mm-url-html-entities (cons '(nbsp . 32) mm-url-html-entities)))
386     (mm-url-decode-entities)))
387
388 (defun mm-url-decode-entities-string (string)
389   (with-temp-buffer
390     (insert string)
391     (mm-url-decode-entities)
392     (buffer-string)))
393
394 (defun mm-url-form-encode-xwfu (chunk)
395   "Escape characters in a string for application/x-www-form-urlencoded.
396 Blasphemous crap because someone didn't think %20 was good enough for encoding
397 spaces.  Die Die Die."
398   ;; This will get rid of the 'attributes' specified by the file type,
399   ;; which are useless for an application/x-www-form-urlencoded form.
400   (if (consp chunk)
401       (setq chunk (cdr chunk)))
402
403   (mapconcat
404    (lambda (char)
405      (cond
406       ((= char ?  ) "+")
407       ((memq char mm-url-unreserved-chars) (char-to-string char))
408       (t (upcase (format "%%%02x" char)))))
409    ;; Fixme: Should this actually be accepting multibyte?  Is there a
410    ;; better way in XEmacs?
411    (if (featurep 'mule)
412        (encode-coding-string chunk
413                              (if (fboundp 'find-coding-systems-string)
414                                  (car (find-coding-systems-string chunk))
415                                  buffer-file-coding-system))
416      chunk)
417    ""))
418
419 (defun mm-url-encode-www-form-urlencoded (pairs)
420   "Return PAIRS encoded for forms."
421   (mapconcat
422    (lambda (data)
423      (concat (mm-url-form-encode-xwfu (car data)) "="
424              (mm-url-form-encode-xwfu (cdr data))))
425    pairs "&"))
426
427 (defun mm-url-fetch-form (url pairs)
428   "Fetch a form from URL with PAIRS as the data using the POST method."
429   (mm-url-load-url)
430   (let ((url-request-data (mm-url-encode-www-form-urlencoded pairs))
431         (url-request-method "POST")
432         (url-request-extra-headers
433          '(("Content-type" . "application/x-www-form-urlencoded"))))
434     (url-insert-file-contents url)
435     (setq buffer-file-name nil))
436   t)
437
438 (defun mm-url-fetch-simple (url content)
439   (mm-url-load-url)
440   (let ((url-request-data content)
441         (url-request-method "POST")
442         (url-request-extra-headers
443          '(("Content-type" . "application/x-www-form-urlencoded"))))
444     (url-insert-file-contents url)
445     (setq buffer-file-name nil))
446   t)
447
448 (defun mm-url-remove-markup ()
449   "Remove all HTML markup, leaving just plain text."
450   (goto-char (point-min))
451   (while (search-forward "<!--" nil t)
452     (delete-region (match-beginning 0)
453                    (or (search-forward "-->" nil t)
454                        (point-max))))
455   (goto-char (point-min))
456   (while (re-search-forward "<[^>]+>" nil t)
457     (replace-match "" t t)))
458
459 (provide 'mm-url)
460
461 ;;; arch-tag: 0594f9b3-417c-48b0-adc2-5082e1e7917f
462 ;;; mm-url.el ends here