2000-10-08 10:59:13 ShengHuo ZHU <zsh@cs.rochester.edu>
[gnus] / lisp / nnweb.el
1 ;;; nnweb.el --- retrieving articles via web search engines
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news
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 2, or (at your option)
13 ;; 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; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Note: You need to have `url' and `w3' installed for this
28 ;; backend to work.
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33
34 (require 'nnoo)
35 (require 'message)
36 (require 'gnus-util)
37 (require 'gnus)
38 (require 'nnmail)
39 (require 'mm-util)
40 (eval-when-compile
41   (ignore-errors
42     (require 'w3)
43     (require 'url)
44     (require 'w3-forms)))
45 ;; Report failure to find w3 at load time if appropriate.
46 (eval '(progn
47          (require 'w3)
48          (require 'url)
49          (require 'w3-forms)))
50
51 (nnoo-declare nnweb)
52
53 (defvoo nnweb-directory (nnheader-concat gnus-directory "nnweb/")
54   "Where nnweb will save its files.")
55
56 (defvoo nnweb-type 'dejanews
57   "What search engine type is being used.
58 Valid types include `dejanews', `dejanewsold', `reference',
59 and `altavista'.")
60
61 (defvar nnweb-type-definition
62   '((dejanews
63      (article . ignore)
64      (id . "http://search.dejanews.com/msgid.xp?MID=%s&fmt=text")
65      (map . nnweb-dejanews-create-mapping)
66      (search . nnweb-dejanews-search)
67      (address . "http://www.deja.com/=dnc/qs.xp")
68      (identifier . nnweb-dejanews-identity))
69     (dejanewsold
70      (article . ignore)
71      (map . nnweb-dejanews-create-mapping)
72      (search . nnweb-dejanewsold-search)
73      (address . "http://www.deja.com/dnquery.xp")
74      (identifier . nnweb-dejanews-identity))
75     (reference
76      (article . nnweb-reference-wash-article)
77      (map . nnweb-reference-create-mapping)
78      (search . nnweb-reference-search)
79      (address . "http://www.reference.com/cgi-bin/pn/go")
80      (identifier . identity))
81     (altavista
82      (article . nnweb-altavista-wash-article)
83      (map . nnweb-altavista-create-mapping)
84      (search . nnweb-altavista-search)
85      (address . "http://www.altavista.digital.com/cgi-bin/query")
86      (id . "/cgi-bin/news?id@%s")
87      (identifier . identity)))
88   "Type-definition alist.")
89
90 (defvoo nnweb-search nil
91   "Search string to feed to DejaNews.")
92
93 (defvoo nnweb-max-hits 999
94   "Maximum number of hits to display.")
95
96 (defvoo nnweb-ephemeral-p nil
97   "Whether this nnweb server is ephemeral.")
98
99 ;;; Internal variables
100
101 (defvoo nnweb-articles nil)
102 (defvoo nnweb-buffer nil)
103 (defvoo nnweb-group-alist nil)
104 (defvoo nnweb-group nil)
105 (defvoo nnweb-hashtb nil)
106
107 ;;; Interface functions
108
109 (nnoo-define-basics nnweb)
110
111 (deffoo nnweb-retrieve-headers (articles &optional group server fetch-old)
112   (nnweb-possibly-change-server group server)
113   (save-excursion
114     (set-buffer nntp-server-buffer)
115     (erase-buffer)
116     (let (article header)
117       (mm-with-unibyte-current-buffer
118         (while (setq article (pop articles))
119           (when (setq header (cadr (assq article nnweb-articles)))
120             (nnheader-insert-nov header))))
121       'nov)))
122
123 (deffoo nnweb-request-scan (&optional group server)
124   (nnweb-possibly-change-server group server)
125   (funcall (nnweb-definition 'map))
126   (unless nnweb-ephemeral-p
127     (nnweb-write-active)
128     (nnweb-write-overview group)))
129
130 (deffoo nnweb-request-group (group &optional server dont-check)
131   (nnweb-possibly-change-server nil server)
132   (when (and group
133              (not (equal group nnweb-group))
134              (not nnweb-ephemeral-p))
135     (let ((info (assoc group nnweb-group-alist)))
136       (when info
137         (setq nnweb-group group)
138         (setq nnweb-type (nth 2 info))
139         (setq nnweb-search (nth 3 info))
140         (unless dont-check
141           (nnweb-read-overview group)))))
142   (cond
143    ((not nnweb-articles)
144     (nnheader-report 'nnweb "No matching articles"))
145    (t
146     (let ((active (if nnweb-ephemeral-p
147                       (cons (caar nnweb-articles)
148                             (caar (last nnweb-articles)))
149                     (cadr (assoc group nnweb-group-alist)))))
150       (nnheader-report 'nnweb "Opened group %s" group)
151       (nnheader-insert
152        "211 %d %d %d %s\n" (length nnweb-articles)
153        (car active) (cdr active) group)))))
154
155 (deffoo nnweb-close-group (group &optional server)
156   (nnweb-possibly-change-server group server)
157   (when (gnus-buffer-live-p nnweb-buffer)
158     (save-excursion
159       (set-buffer nnweb-buffer)
160       (set-buffer-modified-p nil)
161       (kill-buffer nnweb-buffer)))
162   t)
163
164 (deffoo nnweb-request-article (article &optional group server buffer)
165   (nnweb-possibly-change-server group server)
166   (save-excursion
167     (set-buffer (or buffer nntp-server-buffer))
168     (let* ((header (cadr (assq article nnweb-articles)))
169            (url (and header (mail-header-xref header))))
170       (when (or (and url
171                      (mm-with-unibyte-current-buffer
172                        (nnweb-fetch-url url)))
173                 (and (stringp article)
174                      (nnweb-definition 'id t)
175                      (let ((fetch (nnweb-definition 'id))
176                            art)
177                        (when (string-match "^<\\(.*\\)>$" article)
178                          (setq art (match-string 1 article)))
179                        (and fetch
180                             art
181                             (mm-with-unibyte-current-buffer
182                               (nnweb-fetch-url
183                                (format fetch article)))))))
184         (unless nnheader-callback-function
185           (funcall (nnweb-definition 'article))
186           (nnweb-decode-entities))
187         (nnheader-report 'nnweb "Fetched article %s" article)
188         (cons group (and (numberp article) article))))))
189
190 (deffoo nnweb-close-server (&optional server)
191   (when (and (nnweb-server-opened server)
192              (gnus-buffer-live-p nnweb-buffer))
193     (save-excursion
194       (set-buffer nnweb-buffer)
195       (set-buffer-modified-p nil)
196       (kill-buffer nnweb-buffer)))
197   (nnoo-close-server 'nnweb server))
198
199 (deffoo nnweb-request-list (&optional server)
200   (nnweb-possibly-change-server nil server)
201   (save-excursion
202     (set-buffer nntp-server-buffer)
203     (nnmail-generate-active nnweb-group-alist)
204     t))
205
206 (deffoo nnweb-request-update-info (group info &optional server)
207   (nnweb-possibly-change-server group server))
208
209 (deffoo nnweb-asynchronous-p ()
210   t)
211
212 (deffoo nnweb-request-create-group (group &optional server args)
213   (nnweb-possibly-change-server nil server)
214   (nnweb-request-delete-group group)
215   (push `(,group ,(cons 1 0) ,@args) nnweb-group-alist)
216   (nnweb-write-active)
217   t)
218
219 (deffoo nnweb-request-delete-group (group &optional force server)
220   (nnweb-possibly-change-server group server)
221   (gnus-pull group nnweb-group-alist t)
222   (nnweb-write-active)
223   (gnus-delete-file (nnweb-overview-file group))
224   t)
225
226 (nnoo-define-skeleton nnweb)
227
228 ;;; Internal functions
229
230 (defun nnweb-read-overview (group)
231   "Read the overview of GROUP and build the map."
232   (when (file-exists-p (nnweb-overview-file group))
233     (mm-with-unibyte-buffer
234       (nnheader-insert-file-contents (nnweb-overview-file group))
235       (goto-char (point-min))
236       (let (header)
237         (while (not (eobp))
238           (setq header (nnheader-parse-nov))
239           (forward-line 1)
240           (push (list (mail-header-number header)
241                       header (mail-header-xref header))
242                 nnweb-articles)
243           (nnweb-set-hashtb header (car nnweb-articles)))))))
244
245 (defun nnweb-write-overview (group)
246   "Write the overview file for GROUP."
247   (with-temp-file (nnweb-overview-file group)
248     (let ((articles nnweb-articles))
249       (while articles
250         (nnheader-insert-nov (cadr (pop articles)))))))
251
252 (defun nnweb-set-hashtb (header data)
253   (gnus-sethash (nnweb-identifier (mail-header-xref header))
254                 data nnweb-hashtb))
255
256 (defun nnweb-get-hashtb (url)
257   (gnus-gethash (nnweb-identifier url) nnweb-hashtb))
258
259 (defun nnweb-identifier (ident)
260   (funcall (nnweb-definition 'identifier) ident))
261
262 (defun nnweb-overview-file (group)
263   "Return the name of the overview file of GROUP."
264   (nnheader-concat nnweb-directory group ".overview"))
265
266 (defun nnweb-write-active ()
267   "Save the active file."
268   (gnus-make-directory nnweb-directory)
269   (with-temp-file (nnheader-concat nnweb-directory "active")
270     (prin1 `(setq nnweb-group-alist ',nnweb-group-alist) (current-buffer))))
271
272 (defun nnweb-read-active ()
273   "Read the active file."
274   (load (nnheader-concat nnweb-directory "active") t t t))
275
276 (defun nnweb-definition (type &optional noerror)
277   "Return the definition of TYPE."
278   (let ((def (cdr (assq type (assq nnweb-type nnweb-type-definition)))))
279     (when (and (not def)
280                (not noerror))
281       (error "Undefined definition %s" type))
282     def))
283
284 (defun nnweb-possibly-change-server (&optional group server)
285   (nnweb-init server)
286   (when server
287     (unless (nnweb-server-opened server)
288       (nnweb-open-server server)))
289   (unless nnweb-group-alist
290     (nnweb-read-active))
291   (when group
292     (when (and (not nnweb-ephemeral-p)
293                (not (equal group nnweb-group)))
294       (setq nnweb-hashtb (gnus-make-hashtable 4095))
295       (nnweb-request-group group nil t))))
296
297 (defun nnweb-init (server)
298   "Initialize buffers and such."
299   (unless (gnus-buffer-live-p nnweb-buffer)
300     (setq nnweb-buffer
301           (save-excursion
302             (mm-with-unibyte
303               (nnheader-set-temp-buffer
304                (format " *nnweb %s %s %s*"
305                        nnweb-type nnweb-search server))
306               (current-buffer))))))
307
308 (defun nnweb-fetch-url (url)
309   (let (buf)
310     (save-excursion
311       (if (not nnheader-callback-function)
312           (progn
313             (with-temp-buffer
314               (mm-enable-multibyte)
315               (let ((coding-system-for-read 'binary)
316                     (coding-system-for-write 'binary)
317                     (default-process-coding-system 'binary))
318                 (nnweb-insert url))
319               (setq buf (buffer-string)))
320             (erase-buffer)
321             (insert buf)
322             t)
323         (nnweb-url-retrieve-asynch
324          url 'nnweb-callback (current-buffer) nnheader-callback-function)
325         t))))
326
327 (defun nnweb-callback (buffer callback)
328   (when (gnus-buffer-live-p url-working-buffer)
329     (save-excursion
330       (set-buffer url-working-buffer)
331       (funcall (nnweb-definition 'article))
332       (nnweb-decode-entities)
333       (set-buffer buffer)
334       (goto-char (point-max))
335       (insert-buffer-substring url-working-buffer))
336     (funcall callback t)
337     (gnus-kill-buffer url-working-buffer)))
338
339 (if (fboundp 'url-retrieve-synchronously)
340     (defalias 'nnweb-url-retrieve-asynch 'url-retrieve)
341   (defun nnweb-url-retrieve-asynch (url callback &rest data)
342     (let ((url-request-method "GET")
343           (old-asynch url-be-asynchronous)
344           (url-request-data nil)
345           (url-request-extra-headers nil)
346           (url-working-buffer (generate-new-buffer-name " *nnweb*")))
347       (setq-default url-be-asynchronous t)
348       (save-excursion
349         (set-buffer (get-buffer-create url-working-buffer))
350         (setq url-current-callback-data data
351               url-be-asynchronous t
352               url-current-callback-func callback)
353         (url-retrieve url nil))
354       (setq-default url-be-asynchronous old-asynch))))
355
356 ;;;
357 ;;; DejaNews functions.
358 ;;;
359
360 (defun nnweb-dejanews-create-mapping ()
361   "Perform the search and create an number-to-url alist."
362   (save-excursion
363     (set-buffer nnweb-buffer)
364     (erase-buffer)
365     (when (funcall (nnweb-definition 'search) nnweb-search)
366       (let ((i 0)
367             (more t)
368             (case-fold-search t)
369             (active (or (cadr (assoc nnweb-group nnweb-group-alist))
370                         (cons 1 0)))
371             subject date from
372             map url parse a table group text)
373         (while more
374           ;; Go through all the article hits on this page.
375           (goto-char (point-min))
376           (setq parse (w3-parse-buffer (current-buffer))
377                 table (nth 1 (nnweb-parse-find-all 'table parse)))
378           (dolist (row (nth 2 (car (nth 2 table))))
379             (setq a (nnweb-parse-find 'a row)
380                   url (cdr (assq 'href (nth 1 a)))
381                   text (nreverse (nnweb-text row)))
382             (when a
383               (setq subject (nth 4 text)
384                     group (nth 2 text)
385                     date (nth 1 text)
386                     from (nth 0 text))
387               (if (string-match "\\([0-9]+\\)/\\([0-9]+\\)/\\([0-9]+\\)" date)
388                   (setq date (format "%s %s 00:00:00 %s"
389                                      (car (rassq (string-to-number
390                                                   (match-string 2 date))
391                                                  parse-time-months))
392                                      (match-string 3 date) 
393                                      (match-string 1 date)))
394                 (setq date "Jan 1 00:00:00 0000"))
395               (incf i)
396               (setq url (concat url "&fmt=text"))
397               (when (string-match "&context=[^&]+" url)
398                 (setq url (replace-match "" t t url)))
399               (unless (nnweb-get-hashtb url)
400                 (push
401                  (list
402                   (incf (cdr active))
403                   (make-full-mail-header
404                    (cdr active) (concat subject " (" group ")") from date
405                    (concat "<" (nnweb-identifier url) "@dejanews>")
406                    nil 0 0 url))
407                  map)
408                 (nnweb-set-hashtb (cadar map) (car map)))))
409           ;; See whether there is a "Get next 20 hits" button here.
410           (goto-char (point-min))
411           (if (or (not (re-search-forward
412                         "HREF=\"\\([^\"]+\\)\"[<>b]+Next result" nil t))
413                   (>= i nnweb-max-hits))
414               (setq more nil)
415             ;; Yup -- fetch it.
416             (setq more (match-string 1))
417             (erase-buffer)
418             (url-insert-file-contents more)))
419         ;; Return the articles in the right order.
420         (setq nnweb-articles
421               (sort (nconc nnweb-articles map) 'car-less-than-car))))))
422
423 (defun nnweb-dejanews-search (search)
424   (nnweb-insert
425    (concat
426     (nnweb-definition 'address)
427     "?"
428     (nnweb-encode-www-form-urlencoded
429      `(("ST" . "PS")
430        ("svcclass" . "dnyr")
431        ("QRY" . ,search)
432        ("defaultOp" . "AND")
433        ("DBS" . "1")
434        ("OP" . "dnquery.xp")
435        ("LNG" . "ALL")
436        ("maxhits" . "100")
437        ("threaded" . "0")
438        ("format" . "verbose2")
439        ("showsort" . "date")
440        ("agesign" . "1")
441        ("ageweight" . "1")))))
442   t)
443
444 (defun nnweb-dejanewsold-search (search)
445   (nnweb-fetch-form
446    (nnweb-definition 'address)
447    `(("query" . ,search)
448      ("defaultOp" . "AND")
449      ("svcclass" . "dnold")
450      ("maxhits" . "100")
451      ("format" . "verbose2")
452      ("threaded" . "0")
453      ("showsort" . "date")
454      ("agesign" . "1")
455      ("ageweight" . "1")))
456   t)
457
458 (defun nnweb-dejanews-identity (url)
459   "Return an unique identifier based on URL."
460   (if (string-match "AN=\\([0-9]+\\)" url)
461       (match-string 1 url)
462     url))
463
464 ;;;
465 ;;; InReference
466 ;;;
467
468 (defun nnweb-reference-create-mapping ()
469   "Perform the search and create an number-to-url alist."
470   (save-excursion
471     (set-buffer nnweb-buffer)
472     (erase-buffer)
473     (when (funcall (nnweb-definition 'search) nnweb-search)
474       (let ((i 0)
475             (more t)
476             (case-fold-search t)
477             (active (or (cadr (assoc nnweb-group nnweb-group-alist))
478                         (cons 1 0)))
479             Subject Score Date Newsgroups From Message-ID
480             map url)
481         (while more
482           ;; Go through all the article hits on this page.
483           (goto-char (point-min))
484           (search-forward "</pre><hr>" nil t)
485           (delete-region (point-min) (point))
486           (goto-char (point-min))
487           (while (re-search-forward "^ +[0-9]+\\." nil t)
488             (narrow-to-region
489              (point)
490              (if (re-search-forward "^$" nil t)
491                  (match-beginning 0)
492                (point-max)))
493             (goto-char (point-min))
494             (when (looking-at ".*href=\"\\([^\"]+\\)\"")
495               (setq url (match-string 1)))
496             (nnweb-remove-markup)
497             (goto-char (point-min))
498             (while (search-forward "\t" nil t)
499               (replace-match " "))
500             (goto-char (point-min))
501             (while (re-search-forward "^\\([^:]+\\): \\(.*\\)$" nil t)
502               (set (intern (match-string 1)) (match-string 2)))
503             (widen)
504             (search-forward "</pre>" nil t)
505             (incf i)
506             (unless (nnweb-get-hashtb url)
507               (push
508                (list
509                 (incf (cdr active))
510                 (make-full-mail-header
511                  (cdr active) (concat  "(" Newsgroups ") " Subject) From Date
512                  Message-ID
513                  nil 0 (string-to-int Score) url))
514                map)
515               (nnweb-set-hashtb (cadar map) (car map))))
516           (setq more nil))
517         ;; Return the articles in the right order.
518         (setq nnweb-articles
519               (sort (nconc nnweb-articles map) 'car-less-than-car))))))
520
521 (defun nnweb-reference-wash-article ()
522   (let ((case-fold-search t))
523     (goto-char (point-min))
524     (re-search-forward "^</center><hr>" nil t)
525     (delete-region (point-min) (point))
526     (search-forward "<pre>" nil t)
527     (forward-line -1)
528     (let ((body (point-marker)))
529       (search-forward "</pre>" nil t)
530       (delete-region (point) (point-max))
531       (nnweb-remove-markup)
532       (goto-char (point-min))
533       (while (looking-at " *$")
534         (gnus-delete-line))
535       (narrow-to-region (point-min) body)
536       (while (and (re-search-forward "^$" nil t)
537                   (not (eobp)))
538         (gnus-delete-line))
539       (goto-char (point-min))
540       (while (looking-at "\\(^[^ ]+:\\) *")
541         (replace-match "\\1 " t)
542         (forward-line 1))
543       (goto-char (point-min))
544       (when (re-search-forward "^References:" nil t)
545         (narrow-to-region
546          (point) (if (re-search-forward "^$\\|^[^:]+:" nil t)
547                      (match-beginning 0)
548                    (point-max)))
549         (goto-char (point-min))
550         (while (not (eobp))
551           (unless (looking-at "References")
552             (insert "\t")
553             (forward-line 1)))
554         (goto-char (point-min))
555         (while (search-forward "," nil t)
556           (replace-match " " t t)))
557       (widen)
558       (set-marker body nil))))
559
560 (defun nnweb-reference-search (search)
561   (url-insert-file-contents
562    (concat
563     (nnweb-definition 'address)
564     "?"
565     (nnweb-encode-www-form-urlencoded
566      `(("search" . "advanced")
567        ("querytext" . ,search)
568        ("subj" . "")
569        ("name" . "")
570        ("login" . "")
571        ("host" . "")
572        ("organization" . "")
573        ("groups" . "")
574        ("keywords" . "")
575        ("choice" . "Search")
576        ("startmonth" . "Jul")
577        ("startday" . "25")
578        ("startyear" . "1996")
579        ("endmonth" . "Aug")
580        ("endday" . "24")
581        ("endyear" . "1996")
582        ("mode" . "Quick")
583        ("verbosity" . "Verbose")
584        ("ranking" . "Relevance")
585        ("first" . "1")
586        ("last" . "25")
587        ("score" . "50")))))
588   (setq buffer-file-name nil)
589   t)
590
591 ;;;
592 ;;; Alta Vista
593 ;;;
594
595 (defun nnweb-altavista-create-mapping ()
596   "Perform the search and create an number-to-url alist."
597   (save-excursion
598     (set-buffer nnweb-buffer)
599     (erase-buffer)
600     (let ((part 0))
601       (when (funcall (nnweb-definition 'search) nnweb-search part)
602         (let ((i 0)
603               (more t)
604               (case-fold-search t)
605               (active (or (cadr (assoc nnweb-group nnweb-group-alist))
606                           (cons 1 0)))
607               subject date from id group
608               map url)
609           (while more
610             ;; Go through all the article hits on this page.
611             (goto-char (point-min))
612             (search-forward "<dt>" nil t)
613             (delete-region (point-min) (match-beginning 0))
614             (goto-char (point-min))
615             (while (search-forward "<dt>" nil t)
616               (replace-match "\n<blubb>"))
617             (nnweb-decode-entities)
618             (goto-char (point-min))
619             (while (re-search-forward "<blubb>.*href=\"\\([^\"]+\\)\"><strong>\\([^>]*\\)</strong></a><dd>\\([^-]+\\)- <b>\\([^<]+\\)<.*href=\"news:\\([^\"]+\\)\">.*\">\\(.+\\)</a><P>"
620                                       nil t)
621               (setq url (match-string 1)
622                     subject (match-string 2)
623                     date (match-string 3)
624                     group (match-string 4)
625                     id (concat "<" (match-string 5) ">")
626                     from (match-string 6))
627               (incf i)
628               (unless (nnweb-get-hashtb url)
629                 (push
630                  (list
631                   (incf (cdr active))
632                   (make-full-mail-header
633                    (cdr active) (concat  "(" group ") " subject) from date
634                    id nil 0 0 url))
635                  map)
636                 (nnweb-set-hashtb (cadar map) (car map))))
637             ;; See if we want more.
638             (when (or (not nnweb-articles)
639                       (>= i nnweb-max-hits)
640                       (not (funcall (nnweb-definition 'search)
641                                     nnweb-search (incf part))))
642               (setq more nil)))
643           ;; Return the articles in the right order.
644           (setq nnweb-articles
645                 (sort (nconc nnweb-articles map) 'car-less-than-car)))))))
646
647 (defun nnweb-altavista-wash-article ()
648   (goto-char (point-min))
649   (let ((case-fold-search t))
650     (when (re-search-forward "^<strong>" nil t)
651       (delete-region (point-min) (match-beginning 0)))
652     (goto-char (point-min))
653     (while (looking-at "<strong>\\([^ ]+\\) +</strong> +\\(.*\\)$")
654       (replace-match "\\1: \\2" t)
655       (forward-line 1))
656     (when (re-search-backward "^References:" nil t)
657       (narrow-to-region (point) (progn (forward-line 1) (point)))
658       (goto-char (point-min))
659       (while (re-search-forward "<A.*\\?id@\\([^\"]+\\)\">[0-9]+</A>" nil t)
660         (replace-match "&lt;\\1&gt; " t)))
661     (widen)
662     (nnweb-remove-markup)))
663
664 (defun nnweb-altavista-search (search &optional part)
665   (url-insert-file-contents
666    (concat
667     (nnweb-definition 'address)
668     "?"
669     (nnweb-encode-www-form-urlencoded
670      `(("pg" . "aq")
671        ("what" . "news")
672        ,@(when part `(("stq" . ,(int-to-string (* part 30)))))
673        ("fmt" . "d")
674        ("q" . ,search)
675        ("r" . "")
676        ("d0" . "")
677        ("d1" . "")))))
678   (setq buffer-file-name nil)
679   t)
680
681 ;;;
682 ;;; General web/w3 interface utility functions
683 ;;;
684
685 (defun nnweb-insert-html (parse)
686   "Insert HTML based on a w3 parse tree."
687   (if (stringp parse)
688       (insert parse)
689     (insert "<" (symbol-name (car parse)) " ")
690     (insert (mapconcat
691              (lambda (param)
692                (concat (symbol-name (car param)) "="
693                        (prin1-to-string
694                         (if (consp (cdr param))
695                             (cadr param)
696                           (cdr param)))))
697              (nth 1 parse)
698              " "))
699     (insert ">\n")
700     (mapcar 'nnweb-insert-html (nth 2 parse))
701     (insert "</" (symbol-name (car parse)) ">\n")))
702
703 (defun nnweb-encode-www-form-urlencoded (pairs)
704   "Return PAIRS encoded for forms."
705   (mapconcat
706    (function
707     (lambda (data)
708       (concat (w3-form-encode-xwfu (car data)) "="
709               (w3-form-encode-xwfu (cdr data)))))
710    pairs "&"))
711
712 (defun nnweb-fetch-form (url pairs)
713   "Fetch a form from URL with PAIRS as the data using the POST method."
714   (let ((url-request-data (nnweb-encode-www-form-urlencoded pairs))
715         (url-request-method "POST")
716         (url-request-extra-headers
717          '(("Content-type" . "application/x-www-form-urlencoded"))))
718     (url-insert-file-contents url)
719     (setq buffer-file-name nil))
720   t)
721
722 (defun nnweb-decode-entities ()
723   "Decode all HTML entities."
724   (goto-char (point-min))
725   (while (re-search-forward "&\\(#[0-9]+\\|[a-z]+\\);" nil t)
726     (let ((elem (if (eq (aref (match-string 1) 0) ?\#)
727                         (let ((c
728                                (string-to-number (substring 
729                                                   (match-string 1) 1))))
730                           (if (mm-char-or-char-int-p c) c 32))
731                       (or (cdr (assq (intern (match-string 1))
732                                      w3-html-entities))
733                           ?#))))
734       (unless (stringp elem)
735         (setq elem (char-to-string elem)))
736       (replace-match elem t t))))
737
738 (defun nnweb-decode-entities-string (str)
739   (with-temp-buffer
740     (insert str)
741     (nnweb-decode-entities)
742     (buffer-substring (point-min) (point-max))))
743
744 (defun nnweb-remove-markup ()
745   "Remove all HTML markup, leaving just plain text."
746   (goto-char (point-min))
747   (while (search-forward "<!--" nil t)
748     (delete-region (match-beginning 0)
749                    (or (search-forward "-->" nil t)
750                        (point-max))))
751   (goto-char (point-min))
752   (while (re-search-forward "<[^>]+>" nil t)
753     (replace-match "" t t)))
754
755 (defun nnweb-insert (url &optional follow-refresh)
756   "Insert the contents from an URL in the current buffer.
757 If FOLLOW-REFRESH is non-nil, redirect refresh url in META."
758   (let ((name buffer-file-name))
759     (if follow-refresh
760         (save-restriction
761           (narrow-to-region (point) (point))
762           (url-insert-file-contents url)
763           (goto-char (point-min))
764           (when (re-search-forward 
765                  "<meta[ \t\r\n]*http-equiv=\"Refresh\"[^>]*URL=\\([^\"]+\\)\"" nil t)
766             (let ((url (match-string 1)))
767               (delete-region (point-min) (point-max))
768               (nnweb-insert url t))))
769       (url-insert-file-contents url))
770     (setq buffer-file-name name)))
771
772 (defun nnweb-parse-find (type parse &optional maxdepth)
773   "Find the element of TYPE in PARSE."
774   (catch 'found
775     (nnweb-parse-find-1 type parse maxdepth)))
776
777 (defun nnweb-parse-find-1 (type contents maxdepth)
778   (when (or (null maxdepth)
779             (not (zerop maxdepth)))
780     (when (consp contents)
781       (when (eq (car contents) type)
782         (throw 'found contents))
783       (when (listp (cdr contents))
784         (dolist (element contents)
785           (when (consp element)
786             (nnweb-parse-find-1 type element
787                                 (and maxdepth (1- maxdepth)))))))))
788
789 (defun nnweb-parse-find-all (type parse)
790   "Find all elements of TYPE in PARSE."
791   (catch 'found
792     (nnweb-parse-find-all-1 type parse)))
793
794 (defun nnweb-parse-find-all-1 (type contents)
795   (let (result)
796     (when (consp contents)
797       (if (eq (car contents) type)
798           (push contents result)
799         (when (listp (cdr contents))
800           (dolist (element contents)
801             (when (consp element)
802               (setq result
803                     (nconc result (nnweb-parse-find-all-1 type element))))))))
804     result))
805
806 (defvar nnweb-text)
807 (defun nnweb-text (parse)
808   "Return a list of text contents in PARSE."
809   (let ((nnweb-text nil))
810     (nnweb-text-1 parse)
811     (nreverse nnweb-text)))
812
813 (defun nnweb-text-1 (contents)
814   (dolist (element contents)
815     (if (stringp element)
816         (push element nnweb-text)
817       (when (and (consp element)
818                  (listp (cdr element)))
819         (nnweb-text-1 element)))))
820
821 (provide 'nnweb)
822
823 ;;; nnweb.el ends here